{doc['name']}"
+ for f in doc["fields"]:
+ content += f"{f['name']}\n"
+ fc = field_content(f["content"])
+ content += fc.get_text()
+ content += "\n"
+ return Document(
+ metadata={"source": f"rspace: {doc['name']}-{doc['globalId']}"},
+ page_content=content,
+ )
+
+ def _load_structured_doc(self) -> Iterator[Document]:
+ cli, field_content = self._create_rspace_client()
+ yield self._get_doc(cli, field_content, self.global_id)
+
+ def _load_folder_tree(self) -> Iterator[Document]:
+ cli, field_content = self._create_rspace_client()
+ if self.global_id:
+ docs_in_folder = cli.list_folder_tree(
+ folder_id=self.global_id[2:], typesToInclude=["document"]
+ )
+ doc_ids: List[int] = [d["id"] for d in docs_in_folder["records"]]
+ for doc_id in doc_ids:
+ yield self._get_doc(cli, field_content, doc_id)
+
+ def _load_pdf(self) -> Iterator[Document]:
+ cli, field_content = self._create_rspace_client()
+ file_info = cli.get_file_info(self.global_id)
+ _, ext = os.path.splitext(file_info["name"])
+ if ext.lower() == ".pdf":
+ outfile = f"{self.global_id}.pdf"
+ cli.download_file(self.global_id, outfile)
+ pdf_loader = PyPDFLoader(outfile)
+ for pdf in pdf_loader.lazy_load():
+ pdf.metadata["rspace_src"] = self.global_id
+ yield pdf
+
+ def lazy_load(self) -> Iterator[Document]:
+ if self.global_id and "GL" in self.global_id:
+ for d in self._load_pdf():
+ yield d
+ elif self.global_id and "SD" in self.global_id:
+ for d in self._load_structured_doc():
+ yield d
+ elif self.global_id and self.global_id[0:2] in ["FL", "NB"]:
+ for d in self._load_folder_tree():
+ yield d
+ else:
+ raise ValueError("Unknown global ID type")
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rss.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rss.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d0cd92829134f11193648fb58472a0ade1d1df3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rss.py
@@ -0,0 +1,133 @@
+import logging
+from typing import Any, Iterator, List, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.news import NewsURLLoader
+
+logger = logging.getLogger(__name__)
+
+
+class RSSFeedLoader(BaseLoader):
+ """Load news articles from `RSS` feeds using `Unstructured`.
+
+ Args:
+ urls: URLs for RSS feeds to load. Each articles in the feed is loaded into its own document.
+ opml: OPML file to load feed urls from. Only one of urls or opml should be provided. The value
+ can be a URL string, or OPML markup contents as byte or string.
+ continue_on_failure: If True, continue loading documents even if
+ loading fails for a particular URL.
+ show_progress_bar: If True, use tqdm to show a loading progress bar. Requires
+ tqdm to be installed, ``pip install tqdm``.
+ **newsloader_kwargs: Any additional named arguments to pass to
+ NewsURLLoader.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import RSSFeedLoader
+
+ loader = RSSFeedLoader(
+ urls=["", ""],
+ )
+ docs = loader.load()
+
+ The loader uses feedparser to parse RSS feeds. The feedparser library is not installed by default so you should
+ install it if using this loader:
+ https://pythonhosted.org/feedparser/
+
+ If you use OPML, you should also install listparser:
+ https://pythonhosted.org/listparser/
+
+ Finally, newspaper is used to process each article:
+ https://newspaper.readthedocs.io/en/latest/
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ urls: Optional[Sequence[str]] = None,
+ opml: Optional[str] = None,
+ continue_on_failure: bool = True,
+ show_progress_bar: bool = False,
+ **newsloader_kwargs: Any,
+ ) -> None:
+ """Initialize with urls or OPML."""
+ if (urls is None) == (
+ opml is None
+ ): # This is True if both are None or neither is None
+ raise ValueError(
+ "Provide either the urls or the opml argument, but not both."
+ )
+ self.urls = urls
+ self.opml = opml
+ self.continue_on_failure = continue_on_failure
+ self.show_progress_bar = show_progress_bar
+ self.newsloader_kwargs = newsloader_kwargs
+
+ def load(self) -> List[Document]:
+ iter = self.lazy_load()
+ if self.show_progress_bar:
+ try:
+ from tqdm import tqdm
+ except ImportError as e:
+ raise ImportError(
+ "Package tqdm must be installed if show_progress_bar=True. "
+ "Please install with 'pip install tqdm' or set "
+ "show_progress_bar=False."
+ ) from e
+ iter = tqdm(iter)
+ return list(iter)
+
+ @property
+ def _get_urls(self) -> Sequence[str]:
+ if self.urls:
+ return self.urls
+ try:
+ import listparser
+ except ImportError as e:
+ raise ImportError(
+ "Package listparser must be installed if the opml arg is used. "
+ "Please install with 'pip install listparser' or use the "
+ "urls arg instead."
+ ) from e
+ rss = listparser.parse(self.opml)
+ return [feed.url for feed in rss.feeds]
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ import feedparser
+ except ImportError:
+ raise ImportError(
+ "feedparser package not found, please install it with "
+ "`pip install feedparser`"
+ )
+
+ for url in self._get_urls:
+ try:
+ feed = feedparser.parse(url)
+ if getattr(feed, "bozo", False):
+ raise ValueError(
+ f"Error fetching {url}, exception: {feed.bozo_exception}"
+ )
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching {url}, exception: {e}")
+ continue
+ else:
+ raise e
+ try:
+ for entry in feed.entries:
+ loader = NewsURLLoader(
+ urls=[entry.link],
+ **self.newsloader_kwargs,
+ )
+ article = loader.load()[0]
+ article.metadata["feed"] = url
+ yield article
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error processing entry {entry.link}, exception: {e}")
+ continue
+ else:
+ raise e
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rst.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rst.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa76979692d1c104ec6f9b9c2caa881f029e92fb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rst.py
@@ -0,0 +1,59 @@
+"""Loads RST files."""
+
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredRSTLoader(UnstructuredFileLoader):
+ """Load `RST` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredRSTLoader
+
+ loader = UnstructuredRSTLoader(
+ "example.rst", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-rst
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+ Initialize with a file path.
+
+ Args:
+ file_path: The path to the file to load.
+ mode: The mode to use for partitioning. See unstructured for details.
+ Defaults to "single".
+ **unstructured_kwargs: Additional keyword arguments to pass
+ to unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.7.5")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.rst import partition_rst
+
+ return partition_rst(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rtf.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rtf.py
new file mode 100644
index 0000000000000000000000000000000000000000..871da2b4823cc4672e72ea9dbf9a349498e456fd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/rtf.py
@@ -0,0 +1,59 @@
+"""Loads rich text files."""
+
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredRTFLoader(UnstructuredFileLoader):
+ """Load `RTF` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredRTFLoader
+
+ loader = UnstructuredRTFLoader(
+ "example.rtf", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-rtf
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+ Initialize with a file path.
+
+ Args:
+ file_path: The path to the file to load.
+ mode: The mode to use for partitioning. See unstructured for details.
+ Defaults to "single".
+ **unstructured_kwargs: Additional keyword arguments to pass
+ to unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version("0.5.12")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.rtf import partition_rtf
+
+ return partition_rtf(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_directory.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..24d4afab623653de1f50d70b4a0112ab0664e022
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_directory.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.s3_file import S3FileLoader
+
+if TYPE_CHECKING:
+ import botocore
+
+
+class S3DirectoryLoader(BaseLoader):
+ """Load from `Amazon AWS S3` directory."""
+
+ def __init__(
+ self,
+ bucket: str,
+ prefix: str = "",
+ *,
+ region_name: Optional[str] = None,
+ api_version: Optional[str] = None,
+ use_ssl: Optional[bool] = True,
+ verify: Union[str, bool, None] = None,
+ endpoint_url: Optional[str] = None,
+ aws_access_key_id: Optional[str] = None,
+ aws_secret_access_key: Optional[str] = None,
+ aws_session_token: Optional[str] = None,
+ boto_config: Optional[botocore.client.Config] = None,
+ ):
+ """Initialize with bucket and key name.
+
+ :param bucket: The name of the S3 bucket.
+ :param prefix: The prefix of the S3 key. Defaults to "".
+
+ :param region_name: The name of the region associated with the client.
+ A client is associated with a single region.
+
+ :param api_version: The API version to use. By default, botocore will
+ use the latest API version when creating a client. You only need
+ to specify this parameter if you want to use a previous API version
+ of the client.
+
+ :param use_ssl: Whether to use SSL. By default, SSL is used.
+ Note that not all services support non-ssl connections.
+
+ :param verify: Whether to verify SSL certificates.
+ By default SSL certificates are verified. You can provide the
+ following values:
+
+ * False - do not validate SSL certificates. SSL will still be
+ used (unless use_ssl is False), but SSL certificates
+ will not be verified.
+ * path/to/cert/bundle.pem - A filename of the CA cert bundle to
+ uses. You can specify this argument if you want to use a
+ different CA cert bundle than the one used by botocore.
+
+ :param endpoint_url: The complete URL to use for the constructed
+ client. Normally, botocore will automatically construct the
+ appropriate URL to use when communicating with a service. You can
+ specify a complete URL (including the "http/https" scheme) to
+ override this behavior. If this value is provided, then
+ ``use_ssl`` is ignored.
+
+ :param aws_access_key_id: The access key to use when creating
+ the client. This is entirely optional, and if not provided,
+ the credentials configured for the session will automatically
+ be used. You only need to provide this argument if you want
+ to override the credentials used for this specific client.
+
+ :param aws_secret_access_key: The secret key to use when creating
+ the client. Same semantics as aws_access_key_id above.
+
+ :param aws_session_token: The session token to use when creating
+ the client. Same semantics as aws_access_key_id above.
+
+ :type boto_config: botocore.client.Config
+ :param boto_config: Advanced boto3 client configuration options. If a value
+ is specified in the client config, its value will take precedence
+ over environment variables and configuration values, but not over
+ a value passed explicitly to the method. If a default config
+ object is set on the session, the config object used when creating
+ the client will be the result of calling ``merge()`` on the
+ default config with the config provided to this call.
+ """
+ self.bucket = bucket
+ self.prefix = prefix
+ self.region_name = region_name
+ self.api_version = api_version
+ self.use_ssl = use_ssl
+ self.verify = verify
+ self.endpoint_url = endpoint_url
+ self.aws_access_key_id = aws_access_key_id
+ self.aws_secret_access_key = aws_secret_access_key
+ self.aws_session_token = aws_session_token
+ self.boto_config = boto_config
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ try:
+ import boto3
+ except ImportError:
+ raise ImportError(
+ "Could not import boto3 python package. "
+ "Please install it with `pip install boto3`."
+ )
+ s3 = boto3.resource(
+ "s3",
+ region_name=self.region_name,
+ api_version=self.api_version,
+ use_ssl=self.use_ssl,
+ verify=self.verify,
+ endpoint_url=self.endpoint_url,
+ aws_access_key_id=self.aws_access_key_id,
+ aws_secret_access_key=self.aws_secret_access_key,
+ aws_session_token=self.aws_session_token,
+ config=self.boto_config,
+ )
+ bucket = s3.Bucket(self.bucket)
+ docs = []
+ for obj in bucket.objects.filter(Prefix=self.prefix):
+ # Skip directories
+ if obj.size == 0 and obj.key.endswith("/"):
+ continue
+ loader = S3FileLoader(
+ self.bucket,
+ obj.key,
+ region_name=self.region_name,
+ api_version=self.api_version,
+ use_ssl=self.use_ssl,
+ verify=self.verify,
+ endpoint_url=self.endpoint_url,
+ aws_access_key_id=self.aws_access_key_id,
+ aws_secret_access_key=self.aws_secret_access_key,
+ aws_session_token=self.aws_session_token,
+ boto_config=self.boto_config,
+ )
+ docs.extend(loader.load())
+ return docs
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_file.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb0f0c675aba92c10101025b0ce4eacecdec34b1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/s3_file.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+import os
+import tempfile
+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
+
+from langchain_community.document_loaders.unstructured import UnstructuredBaseLoader
+
+if TYPE_CHECKING:
+ import botocore
+
+
+class S3FileLoader(UnstructuredBaseLoader):
+ """Load from `Amazon AWS S3` file."""
+
+ def __init__(
+ self,
+ bucket: str,
+ key: str,
+ *,
+ region_name: Optional[str] = None,
+ api_version: Optional[str] = None,
+ use_ssl: Optional[bool] = True,
+ verify: Union[str, bool, None] = None,
+ endpoint_url: Optional[str] = None,
+ aws_access_key_id: Optional[str] = None,
+ aws_secret_access_key: Optional[str] = None,
+ aws_session_token: Optional[str] = None,
+ boto_config: Optional[botocore.client.Config] = None,
+ mode: str = "single",
+ post_processors: Optional[List[Callable]] = None,
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with bucket and key name.
+
+ :param bucket: The name of the S3 bucket.
+ :param key: The key of the S3 object.
+
+ :param region_name: The name of the region associated with the client.
+ A client is associated with a single region.
+
+ :param api_version: The API version to use. By default, botocore will
+ use the latest API version when creating a client. You only need
+ to specify this parameter if you want to use a previous API version
+ of the client.
+
+ :param use_ssl: Whether or not to use SSL. By default, SSL is used.
+ Note that not all services support non-ssl connections.
+
+ :param verify: Whether or not to verify SSL certificates.
+ By default SSL certificates are verified. You can provide the
+ following values:
+
+ * False - do not validate SSL certificates. SSL will still be
+ used (unless use_ssl is False), but SSL certificates
+ will not be verified.
+ * path/to/cert/bundle.pem - A filename of the CA cert bundle to
+ uses. You can specify this argument if you want to use a
+ different CA cert bundle than the one used by botocore.
+
+ :param endpoint_url: The complete URL to use for the constructed
+ client. Normally, botocore will automatically construct the
+ appropriate URL to use when communicating with a service. You can
+ specify a complete URL (including the "http/https" scheme) to
+ override this behavior. If this value is provided, then
+ ``use_ssl`` is ignored.
+
+ :param aws_access_key_id: The access key to use when creating
+ the client. This is entirely optional, and if not provided,
+ the credentials configured for the session will automatically
+ be used. You only need to provide this argument if you want
+ to override the credentials used for this specific client.
+
+ :param aws_secret_access_key: The secret key to use when creating
+ the client. Same semantics as aws_access_key_id above.
+
+ :param aws_session_token: The session token to use when creating
+ the client. Same semantics as aws_access_key_id above.
+
+ :type boto_config: botocore.client.Config
+ :param boto_config: Advanced boto3 client configuration options. If a value
+ is specified in the client config, its value will take precedence
+ over environment variables and configuration values, but not over
+ a value passed explicitly to the method. If a default config
+ object is set on the session, the config object used when creating
+ the client will be the result of calling ``merge()`` on the
+ default config with the config provided to this call.
+ :param mode: Mode in which to read the file. Valid options are: single,
+ paged and elements.
+ :param post_processors: Post processing functions to be applied to
+ extracted elements.
+ :param **unstructured_kwargs: Arbitrary additional kwargs to pass in when
+ calling `partition`
+ """
+ super().__init__(mode, post_processors, **unstructured_kwargs)
+ self.bucket = bucket
+ self.key = key
+ self.region_name = region_name
+ self.api_version = api_version
+ self.use_ssl = use_ssl
+ self.verify = verify
+ self.endpoint_url = endpoint_url
+ self.aws_access_key_id = aws_access_key_id
+ self.aws_secret_access_key = aws_secret_access_key
+ self.aws_session_token = aws_session_token
+ self.boto_config = boto_config
+
+ def _get_elements(self) -> List:
+ """Get elements."""
+ from unstructured.partition.auto import partition
+
+ try:
+ import boto3
+ except ImportError:
+ raise ImportError(
+ "Could not import `boto3` python package. "
+ "Please install it with `pip install boto3`."
+ )
+ s3 = boto3.client(
+ "s3",
+ region_name=self.region_name,
+ api_version=self.api_version,
+ use_ssl=self.use_ssl,
+ verify=self.verify,
+ endpoint_url=self.endpoint_url,
+ aws_access_key_id=self.aws_access_key_id,
+ aws_secret_access_key=self.aws_secret_access_key,
+ aws_session_token=self.aws_session_token,
+ config=self.boto_config,
+ )
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.key}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ s3.download_file(self.bucket, self.key, file_path)
+ return partition(filename=file_path, **self.unstructured_kwargs)
+
+ def _get_metadata(self) -> dict:
+ return {"source": f"s3://{self.bucket}/{self.key}"}
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapfly.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapfly.py
new file mode 100644
index 0000000000000000000000000000000000000000..91a95c1642f151729051cbd3e9aa4c2caf6f4aa8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapfly.py
@@ -0,0 +1,70 @@
+"""Scrapfly Web Reader."""
+
+import logging
+from typing import Iterator, List, Literal, Optional
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+logger = logging.getLogger(__file__)
+
+
+class ScrapflyLoader(BaseLoader):
+ """Turn a url to llm accessible markdown with `Scrapfly.io`.
+
+ For further details, visit: https://scrapfly.io/docs/sdk/python
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ *,
+ api_key: Optional[str] = None,
+ scrape_format: Literal["markdown", "text"] = "markdown",
+ scrape_config: Optional[dict] = None,
+ continue_on_failure: bool = True,
+ ) -> None:
+ """Initialize client.
+
+ Args:
+ urls: List of urls to scrape.
+ api_key: The Scrapfly API key. If not specified must have env var
+ SCRAPFLY_API_KEY set.
+ scrape_format: Scrape result format, one or "markdown" or "text".
+ scrape_config: Dictionary of ScrapFly scrape config object.
+ continue_on_failure: Whether to continue if scraping a url fails.
+ """
+ try:
+ from scrapfly import ScrapflyClient
+ except ImportError:
+ raise ImportError(
+ "`scrapfly` package not found, please run `pip install scrapfly-sdk`"
+ )
+ if not urls:
+ raise ValueError("URLs must be provided.")
+ api_key = api_key or get_from_env("api_key", "SCRAPFLY_API_KEY")
+ self.scrapfly = ScrapflyClient(key=api_key)
+ self.urls = urls
+ self.scrape_format = scrape_format
+ self.scrape_config = scrape_config
+ self.continue_on_failure = continue_on_failure
+
+ def lazy_load(self) -> Iterator[Document]:
+ from scrapfly import ScrapeConfig
+
+ scrape_config = self.scrape_config if self.scrape_config is not None else {}
+ for url in self.urls:
+ try:
+ response = self.scrapfly.scrape(
+ ScrapeConfig(url, format=self.scrape_format, **scrape_config)
+ )
+ yield Document(
+ page_content=response.scrape_result["content"],
+ metadata={"url": url},
+ )
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching data from {url}, exception: {e}")
+ else:
+ raise e
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapingant.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapingant.py
new file mode 100644
index 0000000000000000000000000000000000000000..43b3bfd417271161f8df8357a2c3f3753ba76c4f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/scrapingant.py
@@ -0,0 +1,66 @@
+"""ScrapingAnt Web Extractor."""
+
+import logging
+from typing import Iterator, List, Optional
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+logger = logging.getLogger(__file__)
+
+
+class ScrapingAntLoader(BaseLoader):
+ """Turn an url to LLM accessible markdown with `ScrapingAnt`.
+
+ For further details, visit: https://docs.scrapingant.com/python-client
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ *,
+ api_key: Optional[str] = None,
+ scrape_config: Optional[dict] = None,
+ continue_on_failure: bool = True,
+ ) -> None:
+ """Initialize client.
+
+ Args:
+ urls: List of urls to scrape.
+ api_key: The ScrapingAnt API key. If not specified must have env var
+ SCRAPINGANT_API_KEY set.
+ scrape_config: The scraping config from ScrapingAntClient.markdown_request
+ continue_on_failure: Whether to continue if scraping an url fails.
+ """
+ try:
+ from scrapingant_client import ScrapingAntClient
+ except ImportError:
+ raise ImportError(
+ "`scrapingant-client` package not found,"
+ " run `pip install scrapingant-client`"
+ )
+ if not urls:
+ raise ValueError("URLs must be provided.")
+ api_key = api_key or get_from_env("api_key", "SCRAPINGANT_API_KEY")
+ self.client = ScrapingAntClient(token=api_key)
+ self.urls = urls
+ self.scrape_config = scrape_config
+ self.continue_on_failure = continue_on_failure
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Fetch data from ScrapingAnt."""
+
+ scrape_config = self.scrape_config if self.scrape_config is not None else {}
+ for url in self.urls:
+ try:
+ result = self.client.markdown_request(url=url, **scrape_config)
+ yield Document(
+ page_content=result.markdown,
+ metadata={"url": result.url},
+ )
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching data from {url}, exception: {e}")
+ else:
+ raise e
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sharepoint.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sharepoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce19d881e4fdf88aaf4a338ef1d49e91a6f317fb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sharepoint.py
@@ -0,0 +1,208 @@
+"""Loader that loads data from Sharepoint Document Library"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import requests
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from pydantic import Field
+
+from langchain_community.document_loaders.base_o365 import (
+ O365BaseLoader,
+)
+
+
+class SharePointLoader(O365BaseLoader, BaseLoader):
+ """Load from `SharePoint`."""
+
+ document_library_id: str = Field(...)
+ """ The ID of the SharePoint document library to load data from."""
+ folder_path: Optional[str] = None
+ """ The path to the folder to load data from."""
+ object_ids: Optional[List[str]] = None
+ """ The IDs of the objects to load data from."""
+ folder_id: Optional[str] = None
+ """ The ID of the folder to load data from."""
+ load_auth: Optional[bool] = False
+ """ Whether to load authorization identities."""
+ token_path: Path = Path.home() / ".credentials" / "o365_token.txt"
+ """ The path to the token to make api calls"""
+ load_extended_metadata: Optional[bool] = False
+ """ Whether to load extended metadata. Size, Owner and full_path."""
+
+ @property
+ def _scopes(self) -> List[str]:
+ """Return required scopes.
+ Returns:
+ List[str]: A list of required scopes.
+ """
+ return ["sharepoint", "basic"]
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Load documents lazily. Use this when working at a large scale.
+ Yields:
+ Document: A document object representing the parsed blob.
+ """
+ try:
+ from O365.drive import Drive, Folder
+ except ImportError:
+ raise ImportError(
+ "O365 package not found, please install it with `pip install o365`"
+ )
+ drive = self._auth().storage().get_drive(self.document_library_id)
+ if not isinstance(drive, Drive):
+ raise ValueError(f"There isn't a Drive with id {self.document_library_id}.")
+ if self.folder_path:
+ target_folder = drive.get_item_by_path(self.folder_path)
+ if not isinstance(target_folder, Folder):
+ raise ValueError(f"There isn't a folder with path {self.folder_path}.")
+ for blob in self._load_from_folder(target_folder):
+ file_id = str(blob.metadata.get("id"))
+ if self.load_auth is True:
+ auth_identities = self.authorized_identities(file_id)
+ if self.load_extended_metadata is True:
+ extended_metadata = self.get_extended_metadata(file_id)
+ extended_metadata.update({"source_full_url": target_folder.web_url})
+ for parsed_blob in self._blob_parser.lazy_parse(blob):
+ if self.load_auth is True:
+ parsed_blob.metadata["authorized_identities"] = auth_identities
+ if self.load_extended_metadata is True:
+ parsed_blob.metadata.update(extended_metadata)
+ yield parsed_blob
+ if self.folder_id:
+ target_folder = drive.get_item(self.folder_id)
+ if not isinstance(target_folder, Folder):
+ raise ValueError(f"There isn't a folder with path {self.folder_path}.")
+ for blob in self._load_from_folder(target_folder):
+ file_id = str(blob.metadata.get("id"))
+ if self.load_auth is True:
+ auth_identities = self.authorized_identities(file_id)
+ if self.load_extended_metadata is True:
+ extended_metadata = self.get_extended_metadata(file_id)
+ extended_metadata.update({"source_full_url": target_folder.web_url})
+ for parsed_blob in self._blob_parser.lazy_parse(blob):
+ if self.load_auth is True:
+ parsed_blob.metadata["authorized_identities"] = auth_identities
+ if self.load_extended_metadata is True:
+ parsed_blob.metadata.update(extended_metadata)
+ yield parsed_blob
+ if self.object_ids:
+ for blob in self._load_from_object_ids(drive, self.object_ids):
+ file_id = str(blob.metadata.get("id"))
+ if self.load_auth is True:
+ auth_identities = self.authorized_identities(file_id)
+ if self.load_extended_metadata is True:
+ extended_metadata = self.get_extended_metadata(file_id)
+ for parsed_blob in self._blob_parser.lazy_parse(blob):
+ if self.load_auth is True:
+ parsed_blob.metadata["authorized_identities"] = auth_identities
+ if self.load_extended_metadata is True:
+ parsed_blob.metadata.update(extended_metadata)
+ yield parsed_blob
+
+ if not (self.folder_path or self.folder_id or self.object_ids):
+ target_folder = drive.get_root_folder()
+ if not isinstance(target_folder, Folder):
+ raise ValueError("Unable to fetch root folder")
+ for blob in self._load_from_folder(target_folder):
+ file_id = str(blob.metadata.get("id"))
+ if self.load_auth is True:
+ auth_identities = self.authorized_identities(file_id)
+ if self.load_extended_metadata is True:
+ extended_metadata = self.get_extended_metadata(file_id)
+ for blob_part in self._blob_parser.lazy_parse(blob):
+ blob_part.metadata.update(blob.metadata)
+ if self.load_auth is True:
+ blob_part.metadata["authorized_identities"] = auth_identities
+ if self.load_extended_metadata is True:
+ blob_part.metadata.update(extended_metadata)
+ blob_part.metadata.update(
+ {"source_full_url": target_folder.web_url}
+ )
+ yield blob_part
+
+ def authorized_identities(self, file_id: str) -> List:
+ """
+ Retrieve the access identities (user/group emails) for a given file.
+ Args:
+ file_id (str): The ID of the file.
+ Returns:
+ List: A list of group names (email addresses) that have
+ access to the file.
+ """
+ data = self._fetch_access_token()
+ access_token = data.get("access_token")
+ url = (
+ "https://graph.microsoft.com/v1.0/drives"
+ f"/{self.document_library_id}/items/{file_id}/permissions"
+ )
+ headers = {"Authorization": f"Bearer {access_token}"}
+ response = requests.request("GET", url, headers=headers)
+ access_list = response.json()
+
+ group_names = []
+
+ for access_data in access_list.get("value"):
+ if access_data.get("grantedToV2"):
+ site_data = (
+ (access_data.get("grantedToV2").get("siteUser"))
+ or (access_data.get("grantedToV2").get("user"))
+ or (access_data.get("grantedToV2").get("group"))
+ )
+ if site_data:
+ email = site_data.get("email")
+ if email:
+ group_names.append(email)
+ return group_names
+
+ def _fetch_access_token(self) -> Any:
+ """
+ Fetch the access token from the token file.
+ Returns:
+ The access token as a dictionary.
+ """
+ with open(self.token_path, encoding="utf-8") as f:
+ s = f.read()
+ data = json.loads(s)
+ return data
+
+ def get_extended_metadata(self, file_id: str) -> Dict:
+ """
+ Retrieve extended metadata for a file in SharePoint.
+ As of today, following fields are supported in the extended metadata:
+ - size: size of the source file.
+ - owner: display name of the owner of the source file.
+ - full_path: pretty human readable path of the source file.
+ Args:
+ file_id (str): The ID of the file.
+ Returns:
+ `dict` containing the extended metadata of the file, including size, owner,
+ and full path.
+ """
+ data = self._fetch_access_token()
+ access_token = data.get("access_token")
+ url = (
+ "https://graph.microsoft.com/v1.0/drives/"
+ f"{self.document_library_id}/items/{file_id}"
+ "?$select=size,createdBy,parentReference,name"
+ )
+ headers = {"Authorization": f"Bearer {access_token}"}
+ response = requests.request("GET", url, headers=headers)
+ metadata = response.json()
+ staged_metadata = {
+ "size": metadata.get("size", 0),
+ "owner": metadata.get("createdBy", {})
+ .get("user", {})
+ .get("displayName", ""),
+ "full_path": metadata.get("parentReference", {})
+ .get("path", "")
+ .split(":")[-1]
+ + "/"
+ + metadata.get("name", ""),
+ }
+ return staged_metadata
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sitemap.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sitemap.py
new file mode 100644
index 0000000000000000000000000000000000000000..50ecddac6019c01ec8b3d30930c8b84f08e70e3e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sitemap.py
@@ -0,0 +1,236 @@
+import itertools
+import re
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Generator,
+ Iterable,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+)
+from urllib.parse import urlparse
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+def _default_parsing_function(content: Any) -> str:
+ return str(content.get_text())
+
+
+def _default_meta_function(meta: dict, _content: Any) -> dict:
+ return {"source": meta["loc"], **meta}
+
+
+def _batch_block(iterable: Iterable, size: int) -> Generator[List[dict], None, None]:
+ it = iter(iterable)
+ while item := list(itertools.islice(it, size)):
+ yield item
+
+
+def _extract_scheme_and_domain(url: str) -> Tuple[str, str]:
+ """Extract the scheme + domain from a given URL.
+
+ Args:
+ url (str): The input URL.
+
+ Returns:
+ return a 2-tuple of scheme and domain
+ """
+ parsed_uri = urlparse(url)
+ return parsed_uri.scheme, parsed_uri.netloc
+
+
+class SitemapLoader(WebBaseLoader):
+ """Load a sitemap and its URLs.
+
+ **Security Note**: This loader can be used to load all URLs specified in a sitemap.
+ If a malicious actor gets access to the sitemap, they could force
+ the server to load URLs from other domains by modifying the sitemap.
+ This could lead to server-side request forgery (SSRF) attacks; e.g.,
+ with the attacker forcing the server to load URLs from internal
+ service endpoints that are not publicly accessible. While the attacker
+ may not immediately gain access to this data, this data could leak
+ into downstream systems (e.g., data loader is used to load data for indexing).
+
+ This loader is a crawler and web crawlers should generally NOT be deployed
+ with network access to any internal servers.
+
+ Control access to who can submit crawling requests and what network access
+ the crawler has.
+
+ By default, the loader will only load URLs from the same domain as the sitemap
+ if the site map is not a local file. This can be disabled by setting
+ restrict_to_same_domain to False (not recommended).
+
+ If the site map is a local file, no such risk mitigation is applied by default.
+
+ Use the filter URLs argument to limit which URLs can be loaded.
+
+ See https://python.langchain.com/docs/security
+ """
+
+ def __init__(
+ self,
+ web_path: str,
+ filter_urls: Optional[List[str]] = None,
+ parsing_function: Optional[Callable] = None,
+ blocksize: Optional[int] = None,
+ blocknum: int = 0,
+ meta_function: Optional[Callable] = None,
+ is_local: bool = False,
+ continue_on_failure: bool = False,
+ restrict_to_same_domain: bool = True,
+ max_depth: int = 10,
+ **kwargs: Any,
+ ):
+ """Initialize with webpage path and optional filter URLs.
+
+ Args:
+ web_path: url of the sitemap. can also be a local path
+ filter_urls: a list of regexes. If specified, only
+ URLS that match one of the filter URLs will be loaded.
+ *WARNING* The filter URLs are interpreted as regular expressions.
+ Remember to escape special characters if you do not want them to be
+ interpreted as regular expression syntax. For example, `.` appears
+ frequently in URLs and should be escaped if you want to match a literal
+ `.` rather than any character.
+ restrict_to_same_domain takes precedence over filter_urls when
+ restrict_to_same_domain is True and the sitemap is not a local file.
+ parsing_function: Function to parse bs4.Soup output
+ blocksize: number of sitemap locations per block
+ blocknum: the number of the block that should be loaded - zero indexed.
+ Default: 0
+ meta_function: Function to parse bs4.Soup output for metadata
+ remember when setting this method to also copy metadata["loc"]
+ to metadata["source"] if you are using this field
+ is_local: whether the sitemap is a local file. Default: False
+ continue_on_failure: whether to continue loading the sitemap if an error
+ occurs loading a url, emitting a warning instead of raising an
+ exception. Setting this to True makes the loader more robust, but also
+ may result in missing data. Default: False
+ restrict_to_same_domain: whether to restrict loading to URLs to the same
+ domain as the sitemap. Attention: This is only applied if the sitemap
+ is not a local file!
+ max_depth: maximum depth to follow sitemap links. Default: 10
+ """
+
+ if blocksize is not None and blocksize < 1:
+ raise ValueError("Sitemap blocksize should be at least 1")
+
+ if blocknum < 0:
+ raise ValueError("Sitemap blocknum can not be lower then 0")
+
+ try:
+ import lxml # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "lxml package not found, please install it with `pip install lxml`"
+ )
+
+ super().__init__(web_paths=[web_path], **kwargs)
+
+ # Define a list of URL patterns (interpreted as regular expressions) that
+ # will be allowed to be loaded.
+ # restrict_to_same_domain takes precedence over filter_urls when
+ # restrict_to_same_domain is True and the sitemap is not a local file.
+ self.allow_url_patterns = filter_urls
+ self.restrict_to_same_domain = restrict_to_same_domain
+ self.parsing_function = parsing_function or _default_parsing_function
+ self.meta_function = meta_function or _default_meta_function
+ self.blocksize = blocksize
+ self.blocknum = blocknum
+ self.is_local = is_local
+ self.continue_on_failure = continue_on_failure
+ self.max_depth = max_depth
+
+ def parse_sitemap(self, soup: Any, *, depth: int = 0) -> List[dict]:
+ """Parse sitemap xml and load into a list of dicts.
+
+ Args:
+ soup: BeautifulSoup object.
+ depth: current depth of the sitemap. Default: 0
+
+ Returns:
+ List of dicts.
+ """
+ if depth >= self.max_depth:
+ return []
+
+ els: List[Dict] = []
+
+ for url in soup.find_all("url"):
+ loc = url.find("loc")
+ if not loc:
+ continue
+
+ # Strip leading and trailing whitespace and newlines
+ loc_text = loc.text.strip()
+
+ if self.restrict_to_same_domain and not self.is_local:
+ if _extract_scheme_and_domain(loc_text) != _extract_scheme_and_domain(
+ self.web_path
+ ):
+ continue
+
+ if self.allow_url_patterns and not any(
+ re.match(regexp_pattern, loc_text)
+ for regexp_pattern in self.allow_url_patterns
+ ):
+ continue
+
+ els.append(
+ {
+ tag: prop.text.strip()
+ for tag in ["loc", "lastmod", "changefreq", "priority"]
+ if (prop := url.find(tag))
+ }
+ )
+
+ for sitemap in soup.find_all("sitemap"):
+ loc = sitemap.find("loc")
+ if not loc:
+ continue
+
+ soup_child = self.scrape_all([loc.text], "xml")[0]
+ els.extend(self.parse_sitemap(soup_child, depth=depth + 1))
+ return els
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load sitemap."""
+ if self.is_local:
+ try:
+ import bs4
+ except ImportError:
+ raise ImportError(
+ "beautifulsoup4 package not found, please install it"
+ " with `pip install beautifulsoup4`"
+ )
+ fp = open(self.web_path)
+ soup = bs4.BeautifulSoup(fp, "xml")
+ else:
+ soup = self._scrape(self.web_path, parser="xml")
+
+ els = self.parse_sitemap(soup)
+
+ if self.blocksize is not None:
+ elblocks = list(_batch_block(els, self.blocksize))
+ blockcount = len(elblocks)
+ if blockcount - 1 < self.blocknum:
+ raise ValueError(
+ "Selected sitemap does not contain enough blocks for given blocknum"
+ )
+ else:
+ els = elblocks[self.blocknum]
+
+ results = self.scrape_all([el["loc"].strip() for el in els if "loc" in el])
+
+ for i, result in enumerate(results):
+ yield Document(
+ page_content=self.parsing_function(result),
+ metadata=self.meta_function(els[i], result),
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/slack_directory.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/slack_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdce62033a28184e6ff7cf9756a6656f8f4968a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/slack_directory.py
@@ -0,0 +1,107 @@
+import json
+import zipfile
+from pathlib import Path
+from typing import Dict, Iterator, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class SlackDirectoryLoader(BaseLoader):
+ """Load from a `Slack` directory dump."""
+
+ def __init__(self, zip_path: Union[str, Path], workspace_url: Optional[str] = None):
+ """Initialize the SlackDirectoryLoader.
+
+ Args:
+ zip_path (str): The path to the Slack directory dump zip file.
+ workspace_url (Optional[str]): The Slack workspace URL.
+ Including the URL will turn
+ sources into links. Defaults to None.
+ """
+ self.zip_path = Path(zip_path)
+ self.workspace_url = workspace_url
+ self.channel_id_map = self._get_channel_id_map(self.zip_path)
+
+ @staticmethod
+ def _get_channel_id_map(zip_path: Path) -> Dict[str, str]:
+ """Get a dictionary mapping channel names to their respective IDs."""
+ with zipfile.ZipFile(zip_path, "r") as zip_file:
+ try:
+ with zip_file.open("channels.json", "r") as f:
+ channels = json.load(f)
+ return {channel["name"]: channel["id"] for channel in channels}
+ except KeyError:
+ return {}
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load and return documents from the Slack directory dump."""
+ with zipfile.ZipFile(self.zip_path, "r") as zip_file:
+ for channel_path in zip_file.namelist():
+ channel_name = Path(channel_path).parent.name
+ if not channel_name:
+ continue
+ if channel_path.endswith(".json"):
+ messages = self._read_json(zip_file, channel_path)
+ for message in messages:
+ yield self._convert_message_to_document(message, channel_name)
+
+ def _read_json(self, zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:
+ """Read JSON data from a zip subfile."""
+ with zip_file.open(file_path, "r") as f:
+ data = json.load(f)
+ return data
+
+ def _convert_message_to_document(
+ self, message: dict, channel_name: str
+ ) -> Document:
+ """
+ Convert a message to a Document object.
+
+ Args:
+ message (dict): A message in the form of a dictionary.
+ channel_name (str): The name of the channel the message belongs to.
+
+ Returns:
+ Document: A Document object representing the message.
+ """
+ text = message.get("text", "")
+ metadata = self._get_message_metadata(message, channel_name)
+ return Document(
+ page_content=text,
+ metadata=metadata,
+ )
+
+ def _get_message_metadata(self, message: dict, channel_name: str) -> dict:
+ """Create and return metadata for a given message and channel."""
+ timestamp = message.get("ts", "")
+ user = message.get("user", "")
+ source = self._get_message_source(channel_name, user, timestamp)
+ return {
+ "source": source,
+ "channel": channel_name,
+ "timestamp": timestamp,
+ "user": user,
+ }
+
+ def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str:
+ """
+ Get the message source as a string.
+
+ Args:
+ channel_name (str): The name of the channel the message belongs to.
+ user (str): The user ID who sent the message.
+ timestamp (str): The timestamp of the message.
+
+ Returns:
+ str: The message source.
+ """
+ if self.workspace_url:
+ channel_id = self.channel_id_map.get(channel_name, "")
+ return (
+ f"{self.workspace_url}/archives/{channel_id}"
+ + f"/p{timestamp.replace('.', '')}"
+ )
+ else:
+ return f"{channel_name} - {user} - {timestamp}"
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/snowflake_loader.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/snowflake_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..3081a7b7166b2388a9916958c40240ff976f0236
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/snowflake_loader.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+from typing import Any, Dict, Iterator, List, Optional, Tuple
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class SnowflakeLoader(BaseLoader):
+ """Load from `Snowflake` API.
+
+ Each document represents one row of the result. The `page_content_columns`
+ are written into the `page_content` of the document. The `metadata_columns`
+ are written into the `metadata` of the document. By default, all columns
+ are written into the `page_content` and none into the `metadata`.
+
+ """
+
+ def __init__(
+ self,
+ query: str,
+ user: str,
+ password: str,
+ account: str,
+ warehouse: str,
+ role: str,
+ database: str,
+ schema: str,
+ parameters: Optional[Dict[str, Any]] = None,
+ page_content_columns: Optional[List[str]] = None,
+ metadata_columns: Optional[List[str]] = None,
+ ):
+ """Initialize Snowflake document loader.
+
+ Args:
+ query: The query to run in Snowflake.
+ user: Snowflake user.
+ password: Snowflake password.
+ account: Snowflake account.
+ warehouse: Snowflake warehouse.
+ role: Snowflake role.
+ database: Snowflake database
+ schema: Snowflake schema
+ parameters: Optional. Parameters to pass to the query.
+ page_content_columns: Optional. Columns written to Document `page_content`.
+ metadata_columns: Optional. Columns written to Document `metadata`.
+ """
+ self.query = query
+ self.user = user
+ self.password = password
+ self.account = account
+ self.warehouse = warehouse
+ self.role = role
+ self.database = database
+ self.schema = schema
+ self.parameters = parameters
+ self.page_content_columns = (
+ page_content_columns if page_content_columns is not None else ["*"]
+ )
+ self.metadata_columns = metadata_columns if metadata_columns is not None else []
+
+ def _execute_query(self) -> List[Dict[str, Any]]:
+ try:
+ import snowflake.connector
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import snowflake-connector-python package. "
+ "Please install it with `pip install snowflake-connector-python`."
+ ) from ex
+
+ conn = snowflake.connector.connect(
+ user=self.user,
+ password=self.password,
+ account=self.account,
+ warehouse=self.warehouse,
+ role=self.role,
+ database=self.database,
+ schema=self.schema,
+ parameters=self.parameters,
+ )
+ try:
+ cur = conn.cursor()
+ cur.execute("USE DATABASE " + self.database)
+ cur.execute("USE SCHEMA " + self.schema)
+ cur.execute(self.query, self.parameters)
+ query_result = cur.fetchall()
+ column_names = [column[0] for column in cur.description]
+ query_result = [dict(zip(column_names, row)) for row in query_result]
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ query_result = []
+ finally:
+ cur.close()
+ return query_result
+
+ def _get_columns(
+ self, query_result: List[Dict[str, Any]]
+ ) -> Tuple[List[str], List[str]]:
+ page_content_columns = (
+ self.page_content_columns if self.page_content_columns else []
+ )
+ metadata_columns = self.metadata_columns if self.metadata_columns else []
+ if page_content_columns is None and query_result:
+ page_content_columns = list(query_result[0].keys())
+ if metadata_columns is None:
+ metadata_columns = []
+ return page_content_columns or [], metadata_columns
+
+ def lazy_load(self) -> Iterator[Document]:
+ query_result = self._execute_query()
+ if isinstance(query_result, Exception):
+ print(f"An error occurred during the query: {query_result}") # noqa: T201
+ return []
+ page_content_columns, metadata_columns = self._get_columns(query_result)
+ if "*" in page_content_columns:
+ page_content_columns = list(query_result[0].keys())
+ for row in query_result:
+ page_content = "\n".join(
+ f"{k}: {v}" for k, v in row.items() if k in page_content_columns
+ )
+ metadata = {k: v for k, v in row.items() if k in metadata_columns}
+ doc = Document(page_content=page_content, metadata=metadata)
+ yield doc
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spider.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spider.py
new file mode 100644
index 0000000000000000000000000000000000000000..5737162d17f3741d313e77c9b1271d0526608521
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spider.py
@@ -0,0 +1,94 @@
+from typing import Iterator, Literal, Optional
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+
+class SpiderLoader(BaseLoader):
+ """Load web pages as Documents using Spider AI.
+
+ Must have the Python package `spider-client` installed and a Spider API key.
+ See https://spider.cloud for more.
+ """
+
+ def __init__(
+ self,
+ url: str,
+ *,
+ api_key: Optional[str] = None,
+ mode: Literal["scrape", "crawl"] = "scrape",
+ params: Optional[dict] = None,
+ ):
+ """Initialize with API key and URL.
+
+ Args:
+ url: The URL to be processed.
+ api_key: The Spider API key. If not specified, will be read from env
+ var `SPIDER_API_KEY`.
+ mode: The mode to run the loader in. Default is "scrape".
+ Options include "scrape" (single page) and "crawl" (with deeper
+ crawling following subpages).
+ params: Additional parameters for the Spider API.
+ """
+ if params is None:
+ params = {
+ "return_format": "markdown",
+ "metadata": True,
+ } # Using the metadata param slightly slows down the output
+
+ try:
+ from spider import Spider
+ except ImportError:
+ raise ImportError(
+ "`spider` package not found, please run `pip install spider-client`"
+ )
+ if mode not in ("scrape", "crawl"):
+ raise ValueError(
+ f"Unrecognized mode '{mode}'. Expected one of 'scrape', 'crawl'."
+ )
+
+ # Use the environment variable if the API key isn't provided
+ api_key = api_key or get_from_env("api_key", "SPIDER_API_KEY")
+ self.spider = Spider(api_key=api_key)
+ self.url = url
+ self.mode = mode
+ self.params = params
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents based on the specified mode."""
+ spider_docs = []
+
+ if self.mode == "scrape":
+ # Scrape a single page
+ response = self.spider.scrape_url(self.url, params=self.params)
+ if response:
+ spider_docs.append(response)
+ elif self.mode == "crawl":
+ # Crawl multiple pages
+ response = self.spider.crawl_url(self.url, params=self.params)
+ if response:
+ spider_docs.extend(response)
+
+ for doc in spider_docs:
+ if self.mode == "scrape":
+ # Ensure page_content is also not None
+ page_content = doc[0].get("content", "")
+
+ # Ensure metadata is also not None
+ metadata = doc[0].get("metadata", {})
+
+ if page_content is not None:
+ yield Document(page_content=page_content, metadata=metadata)
+ if self.mode == "crawl":
+ # Ensure page_content is also not None
+ page_content = doc.get("content", "")
+
+ # Ensure metadata is also not None
+ metadata = doc.get("metadata", {})
+
+ if page_content is not None:
+ yield Document(
+ page_content=page_content,
+ metadata=metadata,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spreedly.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spreedly.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5af492255cf8d4fd7477466f846b8311c6591db
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/spreedly.py
@@ -0,0 +1,55 @@
+import json
+import urllib.request
+from typing import List
+
+from langchain_core.documents import Document
+from langchain_core.utils import stringify_dict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+SPREEDLY_ENDPOINTS = {
+ "gateways_options": "https://core.spreedly.com/v1/gateways_options.json",
+ "gateways": "https://core.spreedly.com/v1/gateways.json",
+ "receivers_options": "https://core.spreedly.com/v1/receivers_options.json",
+ "receivers": "https://core.spreedly.com/v1/receivers.json",
+ "payment_methods": "https://core.spreedly.com/v1/payment_methods.json",
+ "certificates": "https://core.spreedly.com/v1/certificates.json",
+ "transactions": "https://core.spreedly.com/v1/transactions.json",
+ "environments": "https://core.spreedly.com/v1/environments.json",
+}
+
+
+class SpreedlyLoader(BaseLoader):
+ """Load from `Spreedly` API."""
+
+ def __init__(self, access_token: str, resource: str) -> None:
+ """Initialize with an access token and a resource.
+
+ Args:
+ access_token: The access token.
+ resource: The resource.
+ """
+ self.access_token = access_token
+ self.resource = resource
+ self.headers = {
+ "Authorization": f"Bearer {self.access_token}",
+ "Accept": "application/json",
+ }
+
+ def _make_request(self, url: str) -> List[Document]:
+ request = urllib.request.Request(url, headers=self.headers)
+
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ text = stringify_dict(json_data)
+ metadata = {"source": url}
+ return [Document(page_content=text, metadata=metadata)]
+
+ def _get_resource(self) -> List[Document]:
+ endpoint = SPREEDLY_ENDPOINTS.get(self.resource)
+ if endpoint is None:
+ return []
+ return self._make_request(endpoint)
+
+ def load(self) -> List[Document]:
+ return self._get_resource()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sql_database.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sql_database.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8d03a0db15ebc2ba8d85554cb9aff0f0a6b848a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/sql_database.py
@@ -0,0 +1,137 @@
+from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Union
+
+from sqlalchemy.engine import RowMapping
+from sqlalchemy.sql.expression import Select
+
+from langchain_community.docstore.document import Document
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.sql_database import SQLDatabase
+
+
+class SQLDatabaseLoader(BaseLoader):
+ """
+ Load documents by querying database tables supported by SQLAlchemy.
+
+ For talking to the database, the document loader uses the `SQLDatabase`
+ utility from the LangChain integration toolkit.
+
+ Each document represents one row of the result.
+ """
+
+ def __init__(
+ self,
+ query: Union[str, Select],
+ db: SQLDatabase,
+ *,
+ parameters: Optional[Dict[str, Any]] = None,
+ page_content_mapper: Optional[Callable[..., str]] = None,
+ metadata_mapper: Optional[Callable[..., Dict[str, Any]]] = None,
+ source_columns: Optional[Sequence[str]] = None,
+ include_rownum_into_metadata: bool = False,
+ include_query_into_metadata: bool = False,
+ ):
+ """
+ Args:
+ query: The query to execute.
+ db: A LangChain `SQLDatabase`, wrapping an SQLAlchemy engine.
+ sqlalchemy_kwargs: More keyword arguments for SQLAlchemy's `create_engine`.
+ parameters: Optional. Parameters to pass to the query.
+ page_content_mapper: Optional. Function to convert a row into a string
+ to use as the `page_content` of the document. By default, the loader
+ serializes the whole row into a string, including all columns.
+ metadata_mapper: Optional. Function to convert a row into a dictionary
+ to use as the `metadata` of the document. By default, no columns are
+ selected into the metadata dictionary.
+ source_columns: Optional. The names of the columns to use as the `source`
+ within the metadata dictionary.
+ include_rownum_into_metadata: Optional. Whether to include the row number
+ into the metadata dictionary. Default: False.
+ include_query_into_metadata: Optional. Whether to include the query
+ expression into the metadata dictionary. Default: False.
+ """
+ self.query = query
+ self.db: SQLDatabase = db
+ self.parameters = parameters or {}
+ self.page_content_mapper = (
+ page_content_mapper or self.page_content_default_mapper
+ )
+ self.metadata_mapper = metadata_mapper or self.metadata_default_mapper
+ self.source_columns = source_columns
+ self.include_rownum_into_metadata = include_rownum_into_metadata
+ self.include_query_into_metadata = include_query_into_metadata
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ import sqlalchemy as sa
+ except ImportError:
+ raise ImportError(
+ "Could not import sqlalchemy python package. "
+ "Please install it with `pip install sqlalchemy`."
+ )
+
+ # Querying in `cursor` fetch mode will return an SQLAlchemy `Result` instance.
+ result: sa.Result[Any]
+
+ # Invoke the database query.
+ if isinstance(self.query, sa.SelectBase):
+ result = self.db._execute( # type: ignore[assignment]
+ self.query, fetch="cursor", parameters=self.parameters
+ )
+ query_sql = str(self.query.compile(bind=self.db._engine))
+ elif isinstance(self.query, str):
+ result = self.db._execute( # type: ignore[assignment]
+ sa.text(self.query), fetch="cursor", parameters=self.parameters
+ )
+ query_sql = self.query
+ else:
+ raise TypeError(f"Unable to process query of unknown type: {self.query}")
+
+ # Iterate database result rows and generate list of documents.
+ for i, row in enumerate(result.mappings()):
+ page_content = self.page_content_mapper(row)
+ metadata = self.metadata_mapper(row)
+
+ if self.include_rownum_into_metadata:
+ metadata["row"] = i
+ if self.include_query_into_metadata:
+ metadata["query"] = query_sql
+
+ source_values = []
+ for column, value in row.items():
+ if self.source_columns and column in self.source_columns:
+ source_values.append(value)
+ if source_values:
+ metadata["source"] = ",".join(source_values)
+
+ yield Document(page_content=page_content, metadata=metadata)
+
+ @staticmethod
+ def page_content_default_mapper(
+ row: RowMapping, column_names: Optional[List[str]] = None
+ ) -> str:
+ """
+ A reasonable default function to convert a record into a "page content" string.
+ """
+ if column_names is None:
+ column_names = list(row.keys())
+ return "\n".join(
+ f"{column}: {value}"
+ for column, value in row.items()
+ if column in column_names
+ )
+
+ @staticmethod
+ def metadata_default_mapper(
+ row: RowMapping, column_names: Optional[List[str]] = None
+ ) -> Dict[str, Any]:
+ """
+ A reasonable default function to convert a record into a "metadata" dictionary.
+ """
+ if column_names is None:
+ return {}
+
+ metadata: Dict[str, Any] = {}
+ for column, value in row.items():
+ if column in column_names:
+ metadata[column] = value
+ return metadata
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/srt.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/srt.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a6f49937076abf8a1a74d6d923bd80b87174be5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/srt.py
@@ -0,0 +1,29 @@
+from pathlib import Path
+from typing import List, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class SRTLoader(BaseLoader):
+ """Load `.srt` (subtitle) files."""
+
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with a file path."""
+ try:
+ import pysrt # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "package `pysrt` not found, please install it with `pip install pysrt`"
+ )
+ self.file_path = str(file_path)
+
+ def load(self) -> List[Document]:
+ """Load using pysrt file."""
+ import pysrt
+
+ parsed_info = pysrt.open(self.file_path)
+ text = " ".join([t.text for t in parsed_info])
+ metadata = {"source": self.file_path}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/stripe.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/stripe.py
new file mode 100644
index 0000000000000000000000000000000000000000..51bd04962ed022025ac707d84f461da5c5733355
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/stripe.py
@@ -0,0 +1,52 @@
+import json
+import urllib.request
+from typing import List, Optional
+
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env, stringify_dict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+STRIPE_ENDPOINTS = {
+ "balance_transactions": "https://api.stripe.com/v1/balance_transactions",
+ "charges": "https://api.stripe.com/v1/charges",
+ "customers": "https://api.stripe.com/v1/customers",
+ "events": "https://api.stripe.com/v1/events",
+ "refunds": "https://api.stripe.com/v1/refunds",
+ "disputes": "https://api.stripe.com/v1/disputes",
+}
+
+
+class StripeLoader(BaseLoader):
+ """Load from `Stripe` API."""
+
+ def __init__(self, resource: str, access_token: Optional[str] = None) -> None:
+ """Initialize with a resource and an access token.
+
+ Args:
+ resource: The resource.
+ access_token: The access token.
+ """
+ self.resource = resource
+ access_token = access_token or get_from_env(
+ "access_token", "STRIPE_ACCESS_TOKEN"
+ )
+ self.headers = {"Authorization": f"Bearer {access_token}"}
+
+ def _make_request(self, url: str) -> List[Document]:
+ request = urllib.request.Request(url, headers=self.headers)
+
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ text = stringify_dict(json_data)
+ metadata = {"source": url}
+ return [Document(page_content=text, metadata=metadata)]
+
+ def _get_resource(self) -> List[Document]:
+ endpoint = STRIPE_ENDPOINTS.get(self.resource)
+ if endpoint is None:
+ return []
+ return self._make_request(endpoint)
+
+ def load(self) -> List[Document]:
+ return self._get_resource()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/surrealdb.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/surrealdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a96a14a1adbff92ec3e660d9e09799a44a5cbec
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/surrealdb.py
@@ -0,0 +1,95 @@
+import asyncio
+import json
+import logging
+from typing import Any, Dict, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class SurrealDBLoader(BaseLoader):
+ """Load SurrealDB documents."""
+
+ def __init__(
+ self,
+ filter_criteria: Optional[Dict] = None,
+ **kwargs: Any,
+ ) -> None:
+ try:
+ from surrealdb import Surreal
+ except ImportError as e:
+ raise ImportError(
+ """Cannot import from surrealdb.
+ please install with `pip install surrealdb`."""
+ ) from e
+
+ self.dburl = kwargs.pop("dburl", "ws://localhost:8000/rpc")
+
+ if self.dburl[0:2] == "ws":
+ self.sdb = Surreal(self.dburl)
+ else:
+ raise ValueError("Only websocket connections are supported at this time.")
+
+ self.filter_criteria = filter_criteria or {}
+
+ if "table" in self.filter_criteria:
+ raise ValueError(
+ "key `table` is not a valid criteria for `filter_criteria` argument."
+ )
+
+ self.ns = kwargs.pop("ns", "langchain")
+ self.db = kwargs.pop("db", "database")
+ self.table = kwargs.pop("table", "documents")
+ self.sdb = Surreal(self.dburl)
+ self.kwargs = kwargs
+
+ async def initialize(self) -> None:
+ """
+ Initialize connection to surrealdb database
+ and authenticate if credentials are provided
+ """
+ await self.sdb.connect()
+ if "db_user" in self.kwargs and "db_pass" in self.kwargs:
+ user = self.kwargs.get("db_user")
+ password = self.kwargs.get("db_pass")
+ await self.sdb.signin({"user": user, "pass": password})
+
+ await self.sdb.use(self.ns, self.db)
+
+ def load(self) -> List[Document]:
+ async def _load() -> List[Document]:
+ await self.initialize()
+ return await self.aload()
+
+ return asyncio.run(_load())
+
+ async def aload(self) -> List[Document]:
+ """Load data into Document objects."""
+
+ query = "SELECT * FROM type::table($table)"
+ if self.filter_criteria is not None and len(self.filter_criteria) > 0:
+ query += " WHERE "
+ for idx, key in enumerate(self.filter_criteria):
+ query += f""" {"AND" if idx > 0 else ""} {key} = ${key}"""
+
+ metadata = {
+ "ns": self.ns,
+ "db": self.db,
+ "table": self.table,
+ }
+ results = await self.sdb.query(
+ query, {"table": self.table, **self.filter_criteria}
+ )
+
+ return [
+ (
+ Document(
+ page_content=json.dumps(result),
+ metadata={"id": result["id"], **result["metadata"], **metadata},
+ )
+ )
+ for result in results[0]["result"]
+ ]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/telegram.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/telegram.py
new file mode 100644
index 0000000000000000000000000000000000000000..f955b491c24b14aa7b3edad7198569c4fc13c8de
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/telegram.py
@@ -0,0 +1,268 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING, Dict, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import pandas as pd
+ from telethon.hints import EntityLike
+
+
+def concatenate_rows(row: dict) -> str:
+ """Combine message information in a readable format ready to be used."""
+ date = row["date"]
+ sender = row["from"]
+ text = row["text"]
+ return f"{sender} on {date}: {text}\n\n"
+
+
+class TelegramChatFileLoader(BaseLoader):
+ """Load from `Telegram chat` dump."""
+
+ def __init__(self, path: Union[str, Path]):
+ """Initialize with a path."""
+ self.file_path = path
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ p = Path(self.file_path)
+
+ with open(p, encoding="utf8") as f:
+ d = json.load(f)
+
+ text = "".join(
+ concatenate_rows(message)
+ for message in d["messages"]
+ if message["type"] == "message" and isinstance(message["text"], str)
+ )
+ metadata = {"source": str(p)}
+
+ return [Document(page_content=text, metadata=metadata)]
+
+
+def text_to_docs(text: Union[str, List[str]]) -> List[Document]:
+ """Convert a string or list of strings to a list of Documents with metadata."""
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
+
+ text_splitter = RecursiveCharacterTextSplitter(
+ chunk_size=800,
+ separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
+ chunk_overlap=20,
+ )
+
+ if isinstance(text, str):
+ # Take a single string as one page
+ text = [text]
+ page_docs = [Document(page_content=page) for page in text]
+
+ # Add page numbers as metadata
+ for i, doc in enumerate(page_docs):
+ doc.metadata["page"] = i + 1
+
+ # Split pages into chunks
+ doc_chunks = []
+
+ for doc in page_docs:
+ chunks = text_splitter.split_text(doc.page_content)
+ for i, chunk in enumerate(chunks):
+ doc = Document(
+ page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i}
+ )
+ # Add sources a metadata
+ doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
+ doc_chunks.append(doc)
+ return doc_chunks
+
+
+class TelegramChatApiLoader(BaseLoader):
+ """Load `Telegram` chat json directory dump."""
+
+ def __init__(
+ self,
+ chat_entity: Optional[EntityLike] = None,
+ api_id: Optional[int] = None,
+ api_hash: Optional[str] = None,
+ username: Optional[str] = None,
+ file_path: str = "telegram_data.json",
+ ):
+ """Initialize with API parameters.
+
+ Args:
+ chat_entity: The chat entity to fetch data from.
+ api_id: The API ID.
+ api_hash: The API hash.
+ username: The username.
+ file_path: The file path to save the data to. Defaults to
+ "telegram_data.json".
+ """
+ self.chat_entity = chat_entity
+ self.api_id = api_id
+ self.api_hash = api_hash
+ self.username = username
+ self.file_path = file_path
+
+ async def fetch_data_from_telegram(self) -> None:
+ """Fetch data from Telegram API and save it as a JSON file."""
+ from telethon.sync import TelegramClient
+
+ data = []
+ async with TelegramClient(self.username, self.api_id, self.api_hash) as client:
+ async for message in client.iter_messages(self.chat_entity):
+ is_reply = message.reply_to is not None
+ reply_to_id = message.reply_to.reply_to_msg_id if is_reply else None
+ data.append(
+ {
+ "sender_id": message.sender_id,
+ "text": message.text,
+ "date": message.date.isoformat(),
+ "message.id": message.id,
+ "is_reply": is_reply,
+ "reply_to_id": reply_to_id,
+ }
+ )
+
+ with open(self.file_path, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=4)
+
+ def _get_message_threads(self, data: pd.DataFrame) -> dict:
+ """Create a dictionary of message threads from the given data.
+
+ Args:
+ data (pd.DataFrame): A DataFrame containing the conversation \
+ data with columns:
+ - message.sender_id
+ - text
+ - date
+ - message.id
+ - is_reply
+ - reply_to_id
+
+ Returns:
+ dict: A dictionary where the key is the parent message ID and \
+ the value is a list of message IDs in ascending order.
+ """
+
+ def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]:
+ """
+ Recursively find all replies to a given parent message ID.
+
+ Args:
+ parent_id (int): The parent message ID.
+ reply_data (pd.DataFrame): A DataFrame containing reply messages.
+
+ Returns:
+ list: A list of message IDs that are replies to the parent message ID.
+ """
+ # Find direct replies to the parent message ID
+ direct_replies = reply_data[reply_data["reply_to_id"] == parent_id][
+ "message.id"
+ ].tolist()
+
+ # Recursively find replies to the direct replies
+ all_replies = []
+ for reply_id in direct_replies:
+ all_replies += [reply_id] + find_replies(reply_id, reply_data)
+
+ return all_replies
+
+ # Filter out parent messages
+ parent_messages = data[~data["is_reply"]]
+
+ # Filter out reply messages and drop rows with NaN in 'reply_to_id'
+ reply_messages = data[data["is_reply"]].dropna(subset=["reply_to_id"])
+
+ # Convert 'reply_to_id' to integer
+ reply_messages["reply_to_id"] = reply_messages["reply_to_id"].astype(int)
+
+ # Create a dictionary of message threads with parent message IDs as keys and \
+ # lists of reply message IDs as values
+ message_threads = {
+ parent_id: [parent_id] + find_replies(parent_id, reply_messages)
+ for parent_id in parent_messages["message.id"]
+ }
+
+ return message_threads
+
+ def _combine_message_texts(
+ self, message_threads: Dict[int, List[int]], data: pd.DataFrame
+ ) -> str:
+ """
+ Combine the message texts for each parent message ID based \
+ on the list of message threads.
+
+ Args:
+ message_threads (dict): A dictionary where the key is the parent message \
+ ID and the value is a list of message IDs in ascending order.
+ data (pd.DataFrame): A DataFrame containing the conversation data:
+ - message.sender_id
+ - text
+ - date
+ - message.id
+ - is_reply
+ - reply_to_id
+
+ Returns:
+ str: A combined string of message texts sorted by date.
+ """
+ combined_text = ""
+
+ # Iterate through sorted parent message IDs
+ for parent_id, message_ids in message_threads.items():
+ # Get the message texts for the message IDs and sort them by date
+ message_texts = (
+ data[data["message.id"].isin(message_ids)]
+ .sort_values(by="date")["text"]
+ .tolist()
+ )
+ message_texts = [str(elem) for elem in message_texts]
+
+ # Combine the message texts
+ combined_text += " ".join(message_texts) + ".\n"
+
+ return combined_text.strip()
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+
+ if self.chat_entity is not None:
+ try:
+ import nest_asyncio
+
+ nest_asyncio.apply()
+ asyncio.run(self.fetch_data_from_telegram())
+ except ImportError:
+ raise ImportError(
+ """`nest_asyncio` package not found.
+ please install with `pip install nest_asyncio`
+ """
+ )
+
+ p = Path(self.file_path)
+
+ with open(p, encoding="utf8") as f:
+ d = json.load(f)
+ try:
+ import pandas as pd
+ except ImportError:
+ raise ImportError(
+ """`pandas` package not found.
+ please install with `pip install pandas`
+ """
+ )
+ normalized_messages = pd.json_normalize(d)
+ df = pd.DataFrame(normalized_messages)
+
+ message_threads = self._get_message_threads(df)
+ combined_texts = self._combine_message_texts(message_threads, df)
+
+ return text_to_docs(combined_texts)
+
+
+# For backwards compatibility
+TelegramChatLoader = TelegramChatFileLoader
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_directory.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..e62bbbead28f1ffc8eeb0b1feba7d8996639fb53
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_directory.py
@@ -0,0 +1,47 @@
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.tencent_cos_file import TencentCOSFileLoader
+
+
+class TencentCOSDirectoryLoader(BaseLoader):
+ """Load from `Tencent Cloud COS` directory."""
+
+ def __init__(self, conf: Any, bucket: str, prefix: str = ""):
+ """Initialize with COS config, bucket and prefix.
+ :param conf(CosConfig): COS config.
+ :param bucket(str): COS bucket.
+ :param prefix(str): prefix.
+ """
+ self.conf = conf
+ self.bucket = bucket
+ self.prefix = prefix
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents."""
+ try:
+ from qcloud_cos import CosS3Client
+ except ImportError:
+ raise ImportError(
+ "Could not import cos-python-sdk-v5 python package. "
+ "Please install it with `pip install cos-python-sdk-v5`."
+ )
+ client = CosS3Client(self.conf)
+ contents = []
+ marker = ""
+ while True:
+ response = client.list_objects(
+ Bucket=self.bucket, Prefix=self.prefix, Marker=marker, MaxKeys=1000
+ )
+ if "Contents" in response:
+ contents.extend(response["Contents"])
+ if response["IsTruncated"] == "false":
+ break
+ marker = response["NextMarker"]
+ for content in contents:
+ if content["Key"].endswith("/"):
+ continue
+ loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"])
+ yield loader.load()[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_file.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ad71d2579dd2cc8a22b07619bfcf40bd801befa
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tencent_cos_file.py
@@ -0,0 +1,45 @@
+import os
+import tempfile
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+
+class TencentCOSFileLoader(BaseLoader):
+ """Load from `Tencent Cloud COS` file."""
+
+ def __init__(self, conf: Any, bucket: str, key: str):
+ """Initialize with COS config, bucket and key name.
+ :param conf(CosConfig): COS config.
+ :param bucket(str): COS bucket.
+ :param key(str): COS file key.
+ """
+ self.conf = conf
+ self.bucket = bucket
+ self.key = key
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents."""
+ try:
+ from qcloud_cos import CosS3Client
+ except ImportError:
+ raise ImportError(
+ "Could not import cos-python-sdk-v5 python package. "
+ "Please install it with `pip install cos-python-sdk-v5`."
+ )
+
+ # initialize a client
+ client = CosS3Client(self.conf)
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.bucket}/{self.key}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ # Download the file to a destination
+ client.download_file(
+ Bucket=self.bucket, Key=self.key, DestFilePath=file_path
+ )
+ loader = UnstructuredFileLoader(file_path)
+ # UnstructuredFileLoader not implement lazy_load yet
+ return iter(loader.load())
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tensorflow_datasets.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tensorflow_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bdd1d775ec944fccb08256cf6b09687e20b1347
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tensorflow_datasets.py
@@ -0,0 +1,77 @@
+from typing import Callable, Dict, Iterator, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.tensorflow_datasets import TensorflowDatasets
+
+
+class TensorflowDatasetLoader(BaseLoader):
+ """Load from `TensorFlow Dataset`.
+
+ Attributes:
+ dataset_name: the name of the dataset to load
+ split_name: the name of the split to load.
+ load_max_docs: a limit to the number of loaded documents. Defaults to 100.
+ sample_to_document_function: a function that converts a dataset sample
+ into a Document
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import TensorflowDatasetLoader
+
+ def mlqaen_example_to_document(example: dict) -> Document:
+ return Document(
+ page_content=decode_to_str(example["context"]),
+ metadata={
+ "id": decode_to_str(example["id"]),
+ "title": decode_to_str(example["title"]),
+ "question": decode_to_str(example["question"]),
+ "answer": decode_to_str(example["answers"]["text"][0]),
+ },
+ )
+
+ tsds_client = TensorflowDatasetLoader(
+ dataset_name="mlqa/en",
+ split_name="test",
+ load_max_docs=100,
+ sample_to_document_function=mlqaen_example_to_document,
+ )
+
+ """
+
+ def __init__(
+ self,
+ dataset_name: str,
+ split_name: str,
+ load_max_docs: Optional[int] = 100,
+ sample_to_document_function: Optional[Callable[[Dict], Document]] = None,
+ ):
+ """Initialize the TensorflowDatasetLoader.
+
+ Args:
+ dataset_name: the name of the dataset to load
+ split_name: the name of the split to load.
+ load_max_docs: a limit to the number of loaded documents. Defaults to 100.
+ sample_to_document_function: a function that converts a dataset sample
+ into a Document.
+ """
+ self.dataset_name: str = dataset_name
+ self.split_name: str = split_name
+ self.load_max_docs = load_max_docs
+ """The maximum number of documents to load."""
+ self.sample_to_document_function: Optional[Callable[[Dict], Document]] = (
+ sample_to_document_function
+ )
+ """Custom function that transform a dataset sample into a Document."""
+
+ self._tfds_client = TensorflowDatasets( # type: ignore[call-arg]
+ dataset_name=self.dataset_name,
+ split_name=self.split_name,
+ load_max_docs=self.load_max_docs, # type: ignore[arg-type]
+ sample_to_document_function=self.sample_to_document_function,
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ yield from self._tfds_client.lazy_load()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/text.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..a17216dfff28ef0312c175f0e6cf8b772dd54fe1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/text.py
@@ -0,0 +1,61 @@
+import logging
+from pathlib import Path
+from typing import Iterator, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.helpers import detect_file_encodings
+
+logger = logging.getLogger(__name__)
+
+
+class TextLoader(BaseLoader):
+ """Load text file.
+
+
+ Args:
+ file_path: Path to the file to load.
+
+ encoding: File encoding to use. If `None`, the file will be loaded
+ with the default system encoding.
+
+ autodetect_encoding: Whether to try to autodetect the file encoding
+ if the specified encoding fails.
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ encoding: Optional[str] = None,
+ autodetect_encoding: bool = False,
+ ):
+ """Initialize with file path."""
+ self.file_path = file_path
+ self.encoding = encoding
+ self.autodetect_encoding = autodetect_encoding
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load from file path."""
+ text = ""
+ try:
+ with open(self.file_path, encoding=self.encoding) as f:
+ text = f.read()
+ except UnicodeDecodeError as e:
+ if self.autodetect_encoding:
+ detected_encodings = detect_file_encodings(self.file_path)
+ for encoding in detected_encodings:
+ logger.debug(f"Trying encoding: {encoding.encoding}")
+ try:
+ with open(self.file_path, encoding=encoding.encoding) as f:
+ text = f.read()
+ break
+ except UnicodeDecodeError:
+ continue
+ else:
+ raise RuntimeError(f"Error loading {self.file_path}") from e
+ except Exception as e:
+ raise RuntimeError(f"Error loading {self.file_path}") from e
+
+ metadata = {"source": str(self.file_path)}
+ yield Document(page_content=text, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tidb.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tidb.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4e1ba39ba936adb24c2bf25b26b4aaa26013ffb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tidb.py
@@ -0,0 +1,67 @@
+from typing import Any, Dict, Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class TiDBLoader(BaseLoader):
+ """Load documents from TiDB."""
+
+ def __init__(
+ self,
+ connection_string: str,
+ query: str,
+ page_content_columns: Optional[List[str]] = None,
+ metadata_columns: Optional[List[str]] = None,
+ engine_args: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """Initialize TiDB document loader.
+
+ Args:
+ connection_string (str): The connection string for the TiDB database,
+ format: "mysql+pymysql://root@127.0.0.1:4000/test".
+ query: The query to run in TiDB.
+ page_content_columns: Optional. Columns written to Document `page_content`,
+ default(None) to all columns.
+ metadata_columns: Optional. Columns written to Document `metadata`,
+ default(None) to no columns.
+ engine_args: Optional. Additional arguments to pass to sqlalchemy engine.
+ """
+ self.connection_string = connection_string
+ self.query = query
+ self.page_content_columns = page_content_columns
+ self.metadata_columns = metadata_columns if metadata_columns is not None else []
+ self.engine_args = engine_args
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load TiDB data into document objects."""
+
+ from sqlalchemy import create_engine
+ from sqlalchemy.engine import Engine
+ from sqlalchemy.sql import text
+
+ # use sqlalchemy to create db connection
+ engine: Engine = create_engine(
+ self.connection_string, **(self.engine_args or {})
+ )
+
+ # execute query
+ with engine.connect() as conn:
+ result = conn.execute(text(self.query))
+
+ # convert result to Document objects
+ column_names = list(result.keys())
+ for row in result:
+ # convert row to dict{column:value}
+ row_data = {
+ column_names[index]: value for index, value in enumerate(row)
+ }
+ page_content = "\n".join(
+ f"{k}: {v}"
+ for k, v in row_data.items()
+ if self.page_content_columns is None
+ or k in self.page_content_columns
+ )
+ metadata = {col: row_data[col] for col in self.metadata_columns}
+ yield Document(page_content=page_content, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tomarkdown.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tomarkdown.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c30141dade4c001ea3041dbc97cde52dae54d36
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tomarkdown.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from typing import Iterator
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class ToMarkdownLoader(BaseLoader):
+ """Load `HTML` using `2markdown API`."""
+
+ def __init__(self, url: str, api_key: str):
+ """Initialize with url and api key."""
+ self.url = url
+ self.api_key = api_key
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazily load the file."""
+ response = requests.post(
+ "https://api.2markdown.com/v1/url2md",
+ headers={"X-Api-Key": self.api_key},
+ json={"url": self.url},
+ )
+ text = response.json()["article"]
+ metadata = {"source": self.url}
+ yield Document(page_content=text, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/toml.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/toml.py
new file mode 100644
index 0000000000000000000000000000000000000000..16cd5decb5db0712da74d5f8b0e5023e08729f81
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/toml.py
@@ -0,0 +1,43 @@
+import json
+from pathlib import Path
+from typing import Iterator, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class TomlLoader(BaseLoader):
+ """Load `TOML` files.
+
+ It can load a single source file or several files in a single
+ directory.
+ """
+
+ def __init__(self, source: Union[str, Path]):
+ """Initialize the TomlLoader with a source file or directory."""
+ self.source = Path(source)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazily load the TOML documents from the source file or directory."""
+ import tomli
+
+ if self.source.is_file() and self.source.suffix == ".toml":
+ files = [self.source]
+ elif self.source.is_dir():
+ files = list(self.source.glob("**/*.toml"))
+ else:
+ raise ValueError("Invalid source path or file type")
+
+ for file_path in files:
+ with file_path.open("r", encoding="utf-8") as file:
+ content = file.read()
+ try:
+ data = tomli.loads(content)
+ doc = Document(
+ page_content=json.dumps(data),
+ metadata={"source": str(file_path)},
+ )
+ yield doc
+ except tomli.TOMLDecodeError as e:
+ print(f"Error parsing TOML file {file_path}: {e}") # noqa: T201
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/trello.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/trello.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3db98cd93f40e2d91aa8421eca63db1f86b90b9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/trello.py
@@ -0,0 +1,169 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, Tuple
+
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ from trello import Board, Card, TrelloClient
+
+
+class TrelloLoader(BaseLoader):
+ """Load cards from a `Trello` board."""
+
+ def __init__(
+ self,
+ client: TrelloClient,
+ board_name: str,
+ *,
+ include_card_name: bool = True,
+ include_comments: bool = True,
+ include_checklist: bool = True,
+ card_filter: Literal["closed", "open", "all"] = "all",
+ extra_metadata: Tuple[str, ...] = ("due_date", "labels", "list", "closed"),
+ ):
+ """Initialize Trello loader.
+
+ Args:
+ client: Trello API client.
+ board_name: The name of the Trello board.
+ include_card_name: Whether to include the name of the card in the document.
+ include_comments: Whether to include the comments on the card in the
+ document.
+ include_checklist: Whether to include the checklist on the card in the
+ document.
+ card_filter: Filter on card status. Valid values are "closed", "open",
+ "all".
+ extra_metadata: List of additional metadata fields to include as document
+ metadata.Valid values are "due_date", "labels", "list", "closed".
+
+ """
+ self.client = client
+ self.board_name = board_name
+ self.include_card_name = include_card_name
+ self.include_comments = include_comments
+ self.include_checklist = include_checklist
+ self.extra_metadata = extra_metadata
+ self.card_filter = card_filter
+
+ @classmethod
+ def from_credentials(
+ cls,
+ board_name: str,
+ *,
+ api_key: Optional[str] = None,
+ token: Optional[str] = None,
+ **kwargs: Any,
+ ) -> TrelloLoader:
+ """Convenience constructor that builds TrelloClient init param for you.
+
+ Args:
+ board_name: The name of the Trello board.
+ api_key: Trello API key. Can also be specified as environment variable
+ TRELLO_API_KEY.
+ token: Trello token. Can also be specified as environment variable
+ TRELLO_TOKEN.
+ include_card_name: Whether to include the name of the card in the document.
+ include_comments: Whether to include the comments on the card in the
+ document.
+ include_checklist: Whether to include the checklist on the card in the
+ document.
+ card_filter: Filter on card status. Valid values are "closed", "open",
+ "all".
+ extra_metadata: List of additional metadata fields to include as document
+ metadata.Valid values are "due_date", "labels", "list", "closed".
+ """
+
+ try:
+ from trello import TrelloClient
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import trello python package. "
+ "Please install it with `pip install py-trello`."
+ ) from ex
+ api_key = api_key or get_from_env("api_key", "TRELLO_API_KEY")
+ token = token or get_from_env("token", "TRELLO_TOKEN")
+ client = TrelloClient(api_key=api_key, token=token)
+ return cls(client, board_name, **kwargs)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Loads all cards from the specified Trello board.
+
+ You can filter the cards, metadata and text included by using the optional
+ parameters.
+
+ Returns:
+ A list of documents, one for each card in the board.
+ """
+ try:
+ from bs4 import BeautifulSoup # noqa: F401
+ except ImportError as ex:
+ raise ImportError(
+ "`beautifulsoup4` package not found, please run"
+ " `pip install beautifulsoup4`"
+ ) from ex
+
+ board = self._get_board()
+ # Create a dictionary with the list IDs as keys and the list names as values
+ list_dict = {list_item.id: list_item.name for list_item in board.list_lists()}
+ # Get Cards on the board
+ cards = board.get_cards(card_filter=self.card_filter)
+ for card in cards:
+ yield self._card_to_doc(card, list_dict)
+
+ def _get_board(self) -> Board:
+ # Find the first board with a matching name
+ board = next(
+ (b for b in self.client.list_boards() if b.name == self.board_name), None
+ )
+ if not board:
+ raise ValueError(f"Board `{self.board_name}` not found.")
+ return board
+
+ def _card_to_doc(self, card: Card, list_dict: dict) -> Document:
+ from bs4 import BeautifulSoup
+
+ text_content = ""
+ if self.include_card_name:
+ text_content = card.name + "\n"
+ if card.description.strip():
+ text_content += BeautifulSoup(card.description, "lxml").get_text()
+ if self.include_checklist:
+ # Get all the checklist items on the card
+ for checklist in card.checklists:
+ if checklist.items:
+ items = [
+ f"{item['name']}:{item['state']}" for item in checklist.items
+ ]
+ text_content += f"\n{checklist.name}\n" + "\n".join(items)
+
+ if self.include_comments:
+ # Get all the comments on the card
+ comments = [
+ BeautifulSoup(comment["data"]["text"], "lxml").get_text()
+ for comment in card.comments
+ ]
+ text_content += "Comments:" + "\n".join(comments)
+
+ # Default metadata fields
+ metadata = {
+ "title": card.name,
+ "id": card.id,
+ "url": card.url,
+ }
+
+ # Extra metadata fields. Card object is not subscriptable.
+ if "labels" in self.extra_metadata:
+ metadata["labels"] = [label.name for label in card.labels]
+ if "list" in self.extra_metadata:
+ if card.list_id in list_dict:
+ metadata["list"] = list_dict[card.list_id]
+ if "closed" in self.extra_metadata:
+ metadata["closed"] = card.closed
+ if "due_date" in self.extra_metadata:
+ metadata["due_date"] = card.due_date
+
+ return Document(page_content=text_content, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tsv.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cb3645b495bdddb84fda681146591c70bd9a313
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/tsv.py
@@ -0,0 +1,42 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredTSVLoader(UnstructuredFileLoader):
+ """Load `TSV` files using `Unstructured`.
+
+ Like other
+ Unstructured loaders, UnstructuredTSVLoader can be used in both
+ "single" and "elements" mode. If you use the loader in "elements"
+ mode, the TSV file will be a single Unstructured Table element.
+ If you use the loader in "elements" mode, an HTML representation
+ of the table will be available in the "text_as_html" key in the
+ document metadata.
+
+ Examples
+ --------
+ from langchain_community.document_loaders.tsv import UnstructuredTSVLoader
+
+ loader = UnstructuredTSVLoader("stanley-cups.tsv", mode="elements")
+ docs = loader.load()
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.7.6")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.tsv import partition_tsv
+
+ return partition_tsv(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/twitter.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/twitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..85ab4e7e396b4cf2957248c3d23e11b14728689d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/twitter.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import tweepy
+ from tweepy import OAuth2BearerHandler, OAuthHandler
+
+
+def _dependable_tweepy_import() -> tweepy:
+ try:
+ import tweepy
+ except ImportError:
+ raise ImportError(
+ "tweepy package not found, please install it with `pip install tweepy`"
+ )
+ return tweepy
+
+
+class TwitterTweetLoader(BaseLoader):
+ """Load `Twitter` tweets.
+
+ Read tweets of the user's Twitter handle.
+
+ First you need to go to
+ `https://developer.twitter.com/en/docs/twitter-api
+ /getting-started/getting-access-to-the-twitter-api`
+ to get your token. And create a v2 version of the app.
+ """
+
+ def __init__(
+ self,
+ auth_handler: Union[OAuthHandler, OAuth2BearerHandler],
+ twitter_users: Sequence[str],
+ number_tweets: Optional[int] = 100,
+ ):
+ self.auth = auth_handler
+ self.twitter_users = twitter_users
+ self.number_tweets = number_tweets
+
+ def load(self) -> List[Document]:
+ """Load tweets."""
+ tweepy = _dependable_tweepy_import()
+ api = tweepy.API(self.auth, parser=tweepy.parsers.JSONParser())
+
+ results: List[Document] = []
+ for username in self.twitter_users:
+ tweets = api.user_timeline(screen_name=username, count=self.number_tweets)
+ user = api.get_user(screen_name=username)
+ docs = self._format_tweets(tweets, user)
+ results.extend(docs)
+ return results
+
+ def _format_tweets(
+ self, tweets: List[Dict[str, Any]], user_info: dict
+ ) -> Iterable[Document]:
+ """Format tweets into a string."""
+ for tweet in tweets:
+ metadata = {
+ "created_at": tweet["created_at"],
+ "user_info": user_info,
+ }
+ yield Document(
+ page_content=tweet["text"],
+ metadata=metadata,
+ )
+
+ @classmethod
+ def from_bearer_token(
+ cls,
+ oauth2_bearer_token: str,
+ twitter_users: Sequence[str],
+ number_tweets: Optional[int] = 100,
+ ) -> TwitterTweetLoader:
+ """Create a TwitterTweetLoader from OAuth2 bearer token."""
+ tweepy = _dependable_tweepy_import()
+ auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token)
+ return cls(
+ auth_handler=auth,
+ twitter_users=twitter_users,
+ number_tweets=number_tweets,
+ )
+
+ @classmethod
+ def from_secrets(
+ cls,
+ access_token: str,
+ access_token_secret: str,
+ consumer_key: str,
+ consumer_secret: str,
+ twitter_users: Sequence[str],
+ number_tweets: Optional[int] = 100,
+ ) -> TwitterTweetLoader:
+ """Create a TwitterTweetLoader from access tokens and secrets."""
+ tweepy = _dependable_tweepy_import()
+ auth = tweepy.OAuthHandler(
+ access_token=access_token,
+ access_token_secret=access_token_secret,
+ consumer_key=consumer_key,
+ consumer_secret=consumer_secret,
+ )
+ return cls(
+ auth_handler=auth,
+ twitter_users=twitter_users,
+ number_tweets=number_tweets,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/unstructured.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/unstructured.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e77e84f936ebd2b1666062ee5986f2cd02e7e03
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/unstructured.py
@@ -0,0 +1,509 @@
+"""Loader that uses unstructured to load files."""
+
+from __future__ import annotations
+
+import logging
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import IO, Any, Callable, Iterator, List, Optional, Sequence, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+from typing_extensions import TypeAlias
+
+from langchain_community.document_loaders.base import BaseLoader
+
+Element: TypeAlias = Any
+
+logger = logging.getLogger(__file__)
+
+
+def satisfies_min_unstructured_version(min_version: str) -> bool:
+ """Check if the installed `Unstructured` version exceeds the minimum version
+ for the feature in question."""
+ from unstructured.__version__ import __version__ as __unstructured_version__
+
+ min_version_tuple = tuple([int(x) for x in min_version.split(".")])
+
+ # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release
+ # versions of unstructured like 0.4.17-dev1
+ _unstructured_version = __unstructured_version__.split("-")[0]
+ unstructured_version_tuple = tuple(
+ [int(x) for x in _unstructured_version.split(".")]
+ )
+
+ return unstructured_version_tuple >= min_version_tuple
+
+
+def validate_unstructured_version(min_unstructured_version: str) -> None:
+ """Raise an error if the `Unstructured` version does not exceed the
+ specified minimum."""
+ if not satisfies_min_unstructured_version(min_unstructured_version):
+ raise ValueError(
+ f"unstructured>={min_unstructured_version} is required in this loader."
+ )
+
+
+class UnstructuredBaseLoader(BaseLoader, ABC):
+ """Base Loader that uses `Unstructured`."""
+
+ def __init__(
+ self,
+ mode: str = "single", # deprecated
+ post_processors: Optional[List[Callable[[str], str]]] = None,
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+ try:
+ import unstructured # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "unstructured package not found, please install it with "
+ "`pip install unstructured`"
+ )
+
+ # `single` - elements are combined into one (default)
+ # `elements` - maintain individual elements
+ # `paged` - elements are combined by page
+ _valid_modes = {"single", "elements", "paged"}
+ if mode not in _valid_modes:
+ raise ValueError(
+ f"Got {mode} for `mode`, but should be one of `{_valid_modes}`"
+ )
+
+ if not satisfies_min_unstructured_version("0.5.4"):
+ if "strategy" in unstructured_kwargs:
+ unstructured_kwargs.pop("strategy")
+
+ self._check_if_both_mode_and_chunking_strategy_are_by_page(
+ mode, unstructured_kwargs
+ )
+ self.mode = mode
+ self.unstructured_kwargs = unstructured_kwargs
+ self.post_processors = post_processors or []
+
+ @abstractmethod
+ def _get_elements(self) -> List[Element]:
+ """Get elements."""
+
+ @abstractmethod
+ def _get_metadata(self) -> dict[str, Any]:
+ """Get file_path metadata if available."""
+
+ def _post_process_elements(self, elements: List[Element]) -> List[Element]:
+ """Apply post processing functions to extracted unstructured elements.
+
+ Post processing functions are str -> str callables passed
+ in using the post_processors kwarg when the loader is instantiated.
+ """
+ for element in elements:
+ for post_processor in self.post_processors:
+ element.apply(post_processor)
+ return elements
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load file."""
+ elements = self._get_elements()
+ self._post_process_elements(elements)
+ if self.mode == "elements":
+ for element in elements:
+ metadata = self._get_metadata()
+ # NOTE(MthwRobinson) - the attribute check is for backward compatibility
+ # with unstructured<0.4.9. The metadata attributed was added in 0.4.9.
+ if hasattr(element, "metadata"):
+ metadata.update(element.metadata.to_dict())
+ if hasattr(element, "category"):
+ metadata["category"] = element.category
+ if element.to_dict().get("element_id"):
+ metadata["element_id"] = element.to_dict().get("element_id")
+ yield Document(page_content=str(element), metadata=metadata)
+ elif self.mode == "paged":
+ logger.warning(
+ "`mode='paged'` is deprecated in favor of the 'by_page' chunking"
+ " strategy. Learn more about chunking here:"
+ " https://docs.unstructured.io/open-source/core-functionality/chunking"
+ )
+ text_dict: dict[int, str] = {}
+ meta_dict: dict[int, dict[str, Any]] = {}
+
+ for element in elements:
+ metadata = self._get_metadata()
+ if hasattr(element, "metadata"):
+ metadata.update(element.metadata.to_dict())
+ page_number = metadata.get("page_number", 1)
+
+ # Check if this page_number already exists in text_dict
+ if page_number not in text_dict:
+ # If not, create new entry with initial text and metadata
+ text_dict[page_number] = str(element) + "\n\n"
+ meta_dict[page_number] = metadata
+ else:
+ # If exists, append to text and update the metadata
+ text_dict[page_number] += str(element) + "\n\n"
+ meta_dict[page_number].update(metadata)
+
+ # Convert the dict to a list of Document objects
+ for key in text_dict.keys():
+ yield Document(page_content=text_dict[key], metadata=meta_dict[key])
+ elif self.mode == "single":
+ metadata = self._get_metadata()
+ text = "\n\n".join([str(el) for el in elements])
+ yield Document(page_content=text, metadata=metadata)
+ else:
+ raise ValueError(f"mode of {self.mode} not supported.")
+
+ def _check_if_both_mode_and_chunking_strategy_are_by_page(
+ self, mode: str, unstructured_kwargs: dict[str, Any]
+ ) -> None:
+ if (
+ mode == "paged"
+ and unstructured_kwargs.get("chunking_strategy") == "by_page"
+ ):
+ raise ValueError(
+ "Only one of `chunking_strategy='by_page'` or `mode='paged'` may be"
+ " set. `chunking_strategy` is preferred."
+ )
+
+
+@deprecated(
+ since="0.2.8",
+ removal="1.0",
+ alternative_import="langchain_unstructured.UnstructuredLoader",
+)
+class UnstructuredFileLoader(UnstructuredBaseLoader):
+ """Load files using `Unstructured`.
+
+ The file loader uses the unstructured partition function and will automatically
+ detect the file type. You can run the loader in different modes: "single",
+ "elements", and "paged". The default "single" mode will return a single langchain
+ Document object. If you use "elements" mode, the unstructured library will split
+ the document into elements such as Title and NarrativeText and return those as
+ individual langchain Document objects. In addition to these post-processing modes
+ (which are specific to the LangChain Loaders), Unstructured has its own "chunking"
+ parameters for post-processing elements into more useful chunks for uses cases such
+ as Retrieval Augmented Generation (RAG). You can pass in additional unstructured
+ kwargs to configure different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredFileLoader
+
+ loader = UnstructuredFileLoader(
+ "example.pdf", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://docs.unstructured.io/open-source/core-functionality/partitioning
+ https://docs.unstructured.io/open-source/core-functionality/chunking
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, List[str], Path, List[Path]],
+ *,
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+ self.file_path = file_path
+
+ super().__init__(mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List[Element]:
+ from unstructured.partition.auto import partition
+
+ if isinstance(self.file_path, list):
+ elements: List[Element] = []
+ for file in self.file_path:
+ if isinstance(file, Path):
+ file = str(file)
+ elements.extend(partition(filename=file, **self.unstructured_kwargs))
+ return elements
+ else:
+ if isinstance(self.file_path, Path):
+ self.file_path = str(self.file_path)
+ return partition(filename=self.file_path, **self.unstructured_kwargs)
+
+ def _get_metadata(self) -> dict[str, Any]:
+ return {"source": self.file_path}
+
+
+def get_elements_from_api(
+ file_path: Union[str, List[str], Path, List[Path], None] = None,
+ file: Union[IO[bytes], Sequence[IO[bytes]], None] = None,
+ api_url: str = "https://api.unstructuredapp.io/general/v0/general",
+ api_key: str = "",
+ **unstructured_kwargs: Any,
+) -> List[Element]:
+ """Retrieve a list of elements from the `Unstructured API`."""
+ if is_list := isinstance(file_path, list):
+ file_path = [str(path) for path in file_path]
+ if isinstance(file, Sequence) or is_list:
+ from unstructured.partition.api import partition_multiple_via_api
+
+ _doc_elements = partition_multiple_via_api(
+ filenames=file_path,
+ files=file,
+ api_key=api_key,
+ api_url=api_url,
+ **unstructured_kwargs,
+ )
+ elements = []
+ for _elements in _doc_elements:
+ elements.extend(_elements)
+ return elements
+ else:
+ from unstructured.partition.api import partition_via_api
+
+ return partition_via_api(
+ filename=str(file_path) if file_path is not None else None,
+ file=file,
+ api_key=api_key,
+ api_url=api_url,
+ **unstructured_kwargs,
+ )
+
+
+@deprecated(
+ since="0.2.8",
+ removal="1.0",
+ alternative_import="langchain_unstructured.UnstructuredLoader",
+)
+class UnstructuredAPIFileLoader(UnstructuredBaseLoader):
+ """Load files using `Unstructured` API.
+
+ By default, the loader makes a call to the hosted Unstructured API. If you are
+ running the unstructured API locally, you can change the API rule by passing in the
+ url parameter when you initialize the loader. The hosted Unstructured API requires
+ an API key. See the links below to learn more about our API offerings and get an
+ API key.
+
+ You can run the loader in different modes: "single", "elements", and "paged". The
+ default "single" mode will return a single langchain Document object. If you use
+ "elements" mode, the unstructured library will split the document into elements such
+ as Title and NarrativeText and return those as individual langchain Document
+ objects. In addition to these post-processing modes (which are specific to the
+ LangChain Loaders), Unstructured has its own "chunking" parameters for
+ post-processing elements into more useful chunks for uses cases such as Retrieval
+ Augmented Generation (RAG). You can pass in additional unstructured kwargs to
+ configure different unstructured settings.
+
+ Examples
+ ```python
+ from langchain_community.document_loaders import UnstructuredAPIFileLoader
+
+ loader = UnstructuredAPIFileLoader(
+ "example.pdf", mode="elements", strategy="fast", api_key="MY_API_KEY",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://docs.unstructured.io/api-reference/api-services/sdk
+ https://docs.unstructured.io/api-reference/api-services/overview
+ https://docs.unstructured.io/open-source/core-functionality/partitioning
+ https://docs.unstructured.io/open-source/core-functionality/chunking
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, List[str]],
+ *,
+ mode: str = "single",
+ url: str = "https://api.unstructuredapp.io/general/v0/general",
+ api_key: str = "",
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+ validate_unstructured_version(min_unstructured_version="0.10.15")
+
+ self.file_path = file_path
+ self.url = url
+ self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key
+
+ super().__init__(mode=mode, **unstructured_kwargs)
+
+ def _get_metadata(self) -> dict[str, Any]:
+ return {"source": self.file_path}
+
+ def _get_elements(self) -> List[Element]:
+ return get_elements_from_api(
+ file_path=self.file_path,
+ api_key=self.api_key,
+ api_url=self.url,
+ **self.unstructured_kwargs,
+ )
+
+ def _post_process_elements(self, elements: List[Element]) -> List[Element]:
+ """Apply post processing functions to extracted unstructured elements.
+
+ Post processing functions are str -> str callables passed
+ in using the post_processors kwarg when the loader is instantiated.
+ """
+ for element in elements:
+ for post_processor in self.post_processors:
+ element.apply(post_processor)
+ return elements
+
+
+@deprecated(
+ since="0.2.8",
+ removal="1.0",
+ alternative_import="langchain_unstructured.UnstructuredLoader",
+)
+class UnstructuredFileIOLoader(UnstructuredBaseLoader):
+ """Load file-like objects opened in read mode using `Unstructured`.
+
+ The file loader uses the unstructured partition function and will automatically
+ detect the file type. You can run the loader in different modes: "single",
+ "elements", and "paged". The default "single" mode will return a single langchain
+ Document object. If you use "elements" mode, the unstructured library will split
+ the document into elements such as Title and NarrativeText and return those as
+ individual langchain Document objects. In addition to these post-processing modes
+ (which are specific to the LangChain Loaders), Unstructured has its own "chunking"
+ parameters for post-processing elements into more useful chunks for uses cases
+ such as Retrieval Augmented Generation (RAG). You can pass in additional
+ unstructured kwargs to configure different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredFileIOLoader
+
+ with open("example.pdf", "rb") as f:
+ loader = UnstructuredFileIOLoader(
+ f, mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+
+ References
+ ----------
+ https://docs.unstructured.io/open-source/core-functionality/partitioning
+ https://docs.unstructured.io/open-source/core-functionality/chunking
+ """
+
+ def __init__(
+ self,
+ file: IO[bytes],
+ *,
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+ self.file = file
+ super().__init__(mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List[Element]:
+ from unstructured.partition.auto import partition
+
+ return partition(file=self.file, **self.unstructured_kwargs)
+
+ def _get_metadata(self) -> dict[str, Any]:
+ return {}
+
+ def _post_process_elements(self, elements: List[Element]) -> List[Element]:
+ """Apply post processing functions to extracted unstructured elements.
+
+ Post processing functions are str -> str callables passed
+ in using the post_processors kwarg when the loader is instantiated.
+ """
+ for element in elements:
+ for post_processor in self.post_processors:
+ element.apply(post_processor)
+ return elements
+
+
+@deprecated(
+ since="0.2.8",
+ removal="1.0",
+ alternative_import="langchain_unstructured.UnstructuredLoader",
+)
+class UnstructuredAPIFileIOLoader(UnstructuredBaseLoader):
+ """Send file-like objects with `unstructured-client` sdk to the Unstructured API.
+
+ By default, the loader makes a call to the hosted Unstructured API. If you are
+ running the unstructured API locally, you can change the API rule by passing in the
+ url parameter when you initialize the loader. The hosted Unstructured API requires
+ an API key. See the links below to learn more about our API offerings and get an
+ API key.
+
+ You can run the loader in different modes: "single", "elements", and "paged". The
+ default "single" mode will return a single langchain Document object. If you use
+ "elements" mode, the unstructured library will split the document into elements
+ such as Title and NarrativeText and return those as individual langchain Document
+ objects. In addition to these post-processing modes (which are specific to the
+ LangChain Loaders), Unstructured has its own "chunking" parameters for
+ post-processing elements into more useful chunks for uses cases such as Retrieval
+ Augmented Generation (RAG). You can pass in additional unstructured kwargs to
+ configure different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredAPIFileLoader
+
+ with open("example.pdf", "rb") as f:
+ loader = UnstructuredAPIFileIOLoader(
+ f, mode="elements", strategy="fast", api_key="MY_API_KEY",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://docs.unstructured.io/api-reference/api-services/sdk
+ https://docs.unstructured.io/api-reference/api-services/overview
+ https://docs.unstructured.io/open-source/core-functionality/partitioning
+ https://docs.unstructured.io/open-source/core-functionality/chunking
+ """
+
+ def __init__(
+ self,
+ file: Union[IO[bytes], Sequence[IO[bytes]]],
+ *,
+ mode: str = "single",
+ url: str = "https://api.unstructuredapp.io/general/v0/general",
+ api_key: str = "",
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+
+ if isinstance(file, Sequence):
+ validate_unstructured_version(min_unstructured_version="0.6.3")
+ validate_unstructured_version(min_unstructured_version="0.6.2")
+
+ self.file = file
+ self.url = url
+ self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key
+
+ super().__init__(mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List[Element]:
+ if self.unstructured_kwargs.get("metadata_filename"):
+ return get_elements_from_api(
+ file=self.file,
+ file_path=self.unstructured_kwargs.pop("metadata_filename"),
+ api_key=self.api_key,
+ api_url=self.url,
+ **self.unstructured_kwargs,
+ )
+ else:
+ raise ValueError(
+ "If partitioning a file via api,"
+ " metadata_filename must be specified as well.",
+ )
+
+ def _get_metadata(self) -> dict[str, Any]:
+ return {}
+
+ def _post_process_elements(self, elements: List[Element]) -> List[Element]:
+ """Apply post processing functions to extracted unstructured elements.
+
+ Post processing functions are str -> str callables passed
+ in using the post_processors kwarg when the loader is instantiated.
+ """
+ for element in elements:
+ for post_processor in self.post_processors:
+ element.apply(post_processor)
+ return elements
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url.py
new file mode 100644
index 0000000000000000000000000000000000000000..434c0fabb1969925b09ab5537e441a4b60ba9812
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url.py
@@ -0,0 +1,161 @@
+"""Loader that uses unstructured to load HTML files."""
+
+import logging
+from typing import Any, List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class UnstructuredURLLoader(BaseLoader):
+ """Load files from remote URLs using `Unstructured`.
+
+ Use the unstructured partition function to detect the MIME type
+ and route the file to the appropriate partitioner.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredURLLoader
+
+ loader = UnstructuredURLLoader(
+ urls=["", ""], mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ continue_on_failure: bool = True,
+ mode: str = "single",
+ show_progress_bar: bool = False,
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize with file path."""
+ try:
+ import unstructured # noqa:F401
+ from unstructured.__version__ import __version__ as __unstructured_version__
+
+ self.__version = __unstructured_version__
+ except ImportError:
+ raise ImportError(
+ "unstructured package not found, please install it with "
+ "`pip install unstructured`"
+ )
+
+ self._validate_mode(mode)
+ self.mode = mode
+
+ headers = unstructured_kwargs.pop("headers", {})
+ if len(headers.keys()) != 0:
+ warn_about_headers = False
+ if self.__is_non_html_available():
+ warn_about_headers = not self.__is_headers_available_for_non_html()
+ else:
+ warn_about_headers = not self.__is_headers_available_for_html()
+
+ if warn_about_headers:
+ logger.warning(
+ "You are using an old version of unstructured. "
+ "The headers parameter is ignored"
+ )
+
+ self.urls = urls
+ self.continue_on_failure = continue_on_failure
+ self.headers = headers
+ self.unstructured_kwargs = unstructured_kwargs
+ self.show_progress_bar = show_progress_bar
+
+ def _validate_mode(self, mode: str) -> None:
+ _valid_modes = {"single", "elements"}
+ if mode not in _valid_modes:
+ raise ValueError(
+ f"Got {mode} for `mode`, but should be one of `{_valid_modes}`"
+ )
+
+ def __is_headers_available_for_html(self) -> bool:
+ _unstructured_version = self.__version.split("-")[0]
+ unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
+
+ return unstructured_version >= (0, 5, 7)
+
+ def __is_headers_available_for_non_html(self) -> bool:
+ _unstructured_version = self.__version.split("-")[0]
+ unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
+
+ return unstructured_version >= (0, 5, 13)
+
+ def __is_non_html_available(self) -> bool:
+ _unstructured_version = self.__version.split("-")[0]
+ unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
+
+ return unstructured_version >= (0, 5, 12)
+
+ def load(self) -> List[Document]:
+ """Load file."""
+ from unstructured.partition.auto import partition
+ from unstructured.partition.html import partition_html
+
+ docs: List[Document] = list()
+ if self.show_progress_bar:
+ try:
+ from tqdm import tqdm
+ except ImportError as e:
+ raise ImportError(
+ "Package tqdm must be installed if show_progress_bar=True. "
+ "Please install with 'pip install tqdm' or set "
+ "show_progress_bar=False."
+ ) from e
+
+ urls = tqdm(self.urls)
+ else:
+ urls = self.urls
+
+ for url in urls:
+ try:
+ if self.__is_non_html_available():
+ if self.__is_headers_available_for_non_html():
+ elements = partition(
+ url=url, headers=self.headers, **self.unstructured_kwargs
+ )
+ else:
+ elements = partition(url=url, **self.unstructured_kwargs)
+ else:
+ if self.__is_headers_available_for_html():
+ elements = partition_html(
+ url=url, headers=self.headers, **self.unstructured_kwargs
+ )
+ else:
+ elements = partition_html(url=url, **self.unstructured_kwargs)
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching or processing {url}, exception: {e}")
+ continue
+ else:
+ raise e
+
+ if self.mode == "single":
+ text = "\n\n".join([str(el) for el in elements])
+ metadata = {"source": url}
+ docs.append(Document(page_content=text, metadata=metadata))
+ elif self.mode == "elements":
+ for element in elements:
+ metadata = element.metadata.to_dict()
+ metadata["category"] = element.category
+ docs.append(Document(page_content=str(element), metadata=metadata))
+
+ return docs
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_playwright.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_playwright.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a5aa87ae8b627e307f11c153bf1e947d69da472
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_playwright.py
@@ -0,0 +1,264 @@
+"""Loader that uses Playwright to load a page, then uses unstructured to parse html."""
+
+import logging
+import os
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, AsyncIterator, Dict, Iterator, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ from playwright.async_api import Browser as AsyncBrowser
+ from playwright.async_api import Page as AsyncPage
+ from playwright.async_api import Response as AsyncResponse
+ from playwright.sync_api import Browser, Page, Response
+
+
+logger = logging.getLogger(__name__)
+
+
+class PlaywrightEvaluator(ABC):
+ """Abstract base class for all evaluators.
+
+ Each evaluator should take a page, a browser instance, and a response
+ object, process the page as necessary, and return the resulting text.
+ """
+
+ @abstractmethod
+ def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str:
+ """Synchronously process the page and return the resulting text.
+
+ Args:
+ page: The page to process.
+ browser: The browser instance.
+ response: The response from page.goto().
+
+ Returns:
+ text: The text content of the page.
+ """
+ pass
+
+ @abstractmethod
+ async def evaluate_async(
+ self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse"
+ ) -> str:
+ """Asynchronously process the page and return the resulting text.
+
+ Args:
+ page: The page to process.
+ browser: The browser instance.
+ response: The response from page.goto().
+
+ Returns:
+ text: The text content of the page.
+ """
+ pass
+
+
+class UnstructuredHtmlEvaluator(PlaywrightEvaluator):
+ """Evaluate the page HTML content using the `unstructured` library."""
+
+ def __init__(self, remove_selectors: Optional[List[str]] = None):
+ """Initialize UnstructuredHtmlEvaluator."""
+ try:
+ import unstructured # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "unstructured package not found, please install it with "
+ "`pip install unstructured`"
+ )
+
+ self.remove_selectors = remove_selectors
+
+ def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str:
+ """Synchronously process the HTML content of the page."""
+ from unstructured.partition.html import partition_html
+
+ for selector in self.remove_selectors or []:
+ elements = page.locator(selector).all()
+ for element in elements:
+ if element.is_visible():
+ element.evaluate("element => element.remove()")
+
+ page_source = page.content()
+ elements = partition_html(text=page_source)
+ return "\n\n".join([str(el) for el in elements])
+
+ async def evaluate_async(
+ self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse"
+ ) -> str:
+ """Asynchronously process the HTML content of the page."""
+ from unstructured.partition.html import partition_html
+
+ for selector in self.remove_selectors or []:
+ elements = await page.locator(selector).all()
+ for element in elements:
+ if await element.is_visible():
+ await element.evaluate("element => element.remove()")
+
+ page_source = await page.content()
+ elements = partition_html(text=page_source)
+ return "\n\n".join([str(el) for el in elements])
+
+
+class PlaywrightURLLoader(BaseLoader):
+ """Load `HTML` pages with `Playwright` and parse with `Unstructured`.
+
+ This is useful for loading pages that require javascript to render.
+
+ Attributes:
+ urls (List[str]): List of URLs to load.
+ continue_on_failure (bool): If True, continue loading other URLs on failure.
+ headless (bool): If True, the browser will run in headless mode.
+ proxy (Optional[Dict[str, str]]): If set, the browser will access URLs
+ through the specified proxy.
+ browser_session (Optional[Union[str, os.PathLike[str]]]): Path to a file with
+ browser session data that can be used to restore the browser session.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PlaywrightURLLoader
+
+ urls = ["https://api.ipify.org/?format=json",]
+ proxy={
+ "server": "https://xx.xx.xx:15818", # https://:
+ "username": "username",
+ "password": "password"
+ }
+ loader = PlaywrightURLLoader(urls, proxy=proxy)
+ data = loader.load()
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ continue_on_failure: bool = True,
+ headless: bool = True,
+ remove_selectors: Optional[List[str]] = None,
+ evaluator: Optional[PlaywrightEvaluator] = None,
+ proxy: Optional[Dict[str, str]] = None,
+ browser_session: Optional[Union[str, os.PathLike[str]]] = None,
+ ):
+ """Load a list of URLs using Playwright."""
+ try:
+ import playwright # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "playwright package not found, please install it with "
+ "`pip install playwright`"
+ )
+
+ self.urls = urls
+ self.continue_on_failure = continue_on_failure
+ self.headless = headless
+ self.proxy = proxy
+ self.browser_session = browser_session
+
+ if remove_selectors and evaluator:
+ raise ValueError(
+ "`remove_selectors` and `evaluator` cannot be both not None"
+ )
+
+ # Use the provided evaluator, if any, otherwise, use the default.
+ self.evaluator = evaluator or UnstructuredHtmlEvaluator(remove_selectors)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load the specified URLs using Playwright and create Document instances.
+
+ Returns:
+ A list of Document instances with loaded content.
+ """
+ from playwright.sync_api import sync_playwright
+
+ with sync_playwright() as p:
+ browser = p.chromium.launch(headless=self.headless, proxy=self.proxy)
+ context = None
+
+ if self.browser_session:
+ if os.path.exists(self.browser_session):
+ context = browser.new_context(storage_state=self.browser_session)
+ else:
+ logger.warning(f"Session file not found: {self.browser_session}")
+
+ if context is None:
+ context = browser.new_context()
+
+ for url in self.urls:
+ try:
+ page = context.new_page()
+ response = page.goto(url)
+ if response is None:
+ raise ValueError(f"page.goto() returned None for url {url}")
+
+ page.wait_for_load_state("load")
+
+ text = self.evaluator.evaluate(page, browser, response)
+ page.close()
+ metadata = {"source": url}
+ yield Document(page_content=text, metadata=metadata)
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(
+ f"Error fetching or processing {url}, exception: {e}"
+ )
+ else:
+ raise e
+ browser.close()
+
+ async def aload(self) -> List[Document]:
+ """Load the specified URLs with Playwright and create Documents asynchronously.
+ Use this function when in a jupyter notebook environment.
+
+ Returns:
+ A list of Document instances with loaded content.
+ """
+ return [doc async for doc in self.alazy_load()]
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Load the specified URLs with Playwright and create Documents asynchronously.
+ Use this function when in a jupyter notebook environment.
+
+ Returns:
+ A list of Document instances with loaded content.
+ """
+ from playwright.async_api import async_playwright
+
+ async with async_playwright() as p:
+ browser = await p.chromium.launch(headless=self.headless, proxy=self.proxy)
+ context = None
+
+ if self.browser_session:
+ if os.path.exists(self.browser_session):
+ context = await browser.new_context(
+ storage_state=self.browser_session
+ )
+ else:
+ logger.warning(f"Session file not found: {self.browser_session}")
+
+ if context is None:
+ context = await browser.new_context()
+
+ for url in self.urls:
+ try:
+ page = await context.new_page()
+ response = await page.goto(url)
+ if response is None:
+ raise ValueError(f"page.goto() returned None for url {url}")
+
+ await page.wait_for_load_state("load")
+
+ text = await self.evaluator.evaluate_async(page, browser, response)
+ await page.close()
+ metadata = {"source": url}
+ yield Document(page_content=text, metadata=metadata)
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(
+ f"Error fetching or processing {url}, exception: {e}"
+ )
+ else:
+ raise e
+ await browser.close()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_selenium.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_selenium.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdc36cdacc7d264a8ebdd4b1681fced074dcf663
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/url_selenium.py
@@ -0,0 +1,176 @@
+"""Loader that uses Selenium to load a page, then uses unstructured to load the html."""
+
+import logging
+from typing import TYPE_CHECKING, List, Literal, Optional, Union
+
+if TYPE_CHECKING:
+ from selenium.webdriver import Chrome, Firefox
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class SeleniumURLLoader(BaseLoader):
+ """Load `HTML` pages with `Selenium` and parse with `Unstructured`.
+
+ This is useful for loading pages that require javascript to render.
+
+ Attributes:
+ urls (List[str]): List of URLs to load.
+ continue_on_failure (bool): If True, continue loading other URLs on failure.
+ browser (str): The browser to use, either 'chrome' or 'firefox'.
+ binary_location (Optional[str]): The location of the browser binary.
+ executable_path (Optional[str]): The path to the browser executable.
+ headless (bool): If True, the browser will run in headless mode.
+ arguments [List[str]]: List of arguments to pass to the browser.
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ continue_on_failure: bool = True,
+ browser: Literal["chrome", "firefox"] = "chrome",
+ binary_location: Optional[str] = None,
+ executable_path: Optional[str] = None,
+ headless: bool = True,
+ arguments: List[str] = [],
+ ):
+ """Load a list of URLs using Selenium and unstructured."""
+ try:
+ import selenium # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "selenium package not found, please install it with "
+ "`pip install selenium`"
+ )
+
+ try:
+ import unstructured # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "unstructured package not found, please install it with "
+ "`pip install unstructured`"
+ )
+
+ self.urls = urls
+ self.continue_on_failure = continue_on_failure
+ self.browser = browser
+ self.binary_location = binary_location
+ self.executable_path = executable_path
+ self.headless = headless
+ self.arguments = arguments
+
+ def _get_driver(self) -> Union["Chrome", "Firefox"]:
+ """Create and return a WebDriver instance based on the specified browser.
+
+ Raises:
+ ValueError: If an invalid browser is specified.
+
+ Returns:
+ Union[Chrome, Firefox]: A WebDriver instance for the specified browser.
+ """
+ if self.browser.lower() == "chrome":
+ from selenium.webdriver import Chrome
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
+ from selenium.webdriver.chrome.service import Service
+
+ chrome_options = ChromeOptions()
+
+ for arg in self.arguments:
+ chrome_options.add_argument(arg)
+
+ if self.headless:
+ chrome_options.add_argument("--headless")
+ chrome_options.add_argument("--no-sandbox")
+ if self.binary_location is not None:
+ chrome_options.binary_location = self.binary_location
+ if self.executable_path is None:
+ return Chrome(options=chrome_options)
+ return Chrome(
+ options=chrome_options,
+ service=Service(executable_path=self.executable_path),
+ )
+ elif self.browser.lower() == "firefox":
+ from selenium.webdriver import Firefox
+ from selenium.webdriver.firefox.options import Options as FirefoxOptions
+ from selenium.webdriver.firefox.service import Service
+
+ firefox_options = FirefoxOptions()
+
+ for arg in self.arguments:
+ firefox_options.add_argument(arg)
+
+ if self.headless:
+ firefox_options.add_argument("--headless")
+ if self.binary_location is not None:
+ firefox_options.binary_location = self.binary_location
+ if self.executable_path is None:
+ return Firefox(options=firefox_options)
+ return Firefox(
+ options=firefox_options,
+ service=Service(executable_path=self.executable_path),
+ )
+ else:
+ raise ValueError("Invalid browser specified. Use 'chrome' or 'firefox'.")
+
+ def _build_metadata(self, url: str, driver: Union["Chrome", "Firefox"]) -> dict:
+ from selenium.common.exceptions import NoSuchElementException
+ from selenium.webdriver.common.by import By
+
+ """Build metadata based on the contents of the webpage"""
+ metadata = {
+ "source": url,
+ "title": "No title found.",
+ "description": "No description found.",
+ "language": "No language found.",
+ }
+ if title := driver.title:
+ metadata["title"] = title
+ try:
+ if description := driver.find_element(
+ By.XPATH, '//meta[@name="description"]'
+ ):
+ metadata["description"] = (
+ description.get_attribute("content") or "No description found."
+ )
+ except NoSuchElementException:
+ pass
+ try:
+ if html_tag := driver.find_element(By.TAG_NAME, "html"):
+ metadata["language"] = (
+ html_tag.get_attribute("lang") or "No language found."
+ )
+ except NoSuchElementException:
+ pass
+ return metadata
+
+ def load(self) -> List[Document]:
+ """Load the specified URLs using Selenium and create Document instances.
+
+ Returns:
+ List[Document]: A list of Document instances with loaded content.
+ """
+ from unstructured.partition.html import partition_html
+
+ docs: List[Document] = list()
+ driver = self._get_driver()
+
+ for url in self.urls:
+ try:
+ driver.get(url)
+ page_content = driver.page_source
+ elements = partition_html(text=page_content)
+ text = "\n\n".join([str(el) for el in elements])
+ metadata = self._build_metadata(url, driver)
+ docs.append(Document(page_content=text, metadata=metadata))
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching or processing {url}, exception: {e}")
+ else:
+ raise e
+
+ driver.quit()
+ return docs
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/vsdx.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/vsdx.py
new file mode 100644
index 0000000000000000000000000000000000000000..5546d5db4d6f67ec71af63af44771aadbb952be9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/vsdx.py
@@ -0,0 +1,54 @@
+import os
+import tempfile
+from abc import ABC
+from pathlib import Path
+from typing import List, Union
+from urllib.parse import urlparse
+
+import requests
+
+from langchain_community.docstore.document import Document
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.blob_loaders import Blob
+from langchain_community.document_loaders.parsers import VsdxParser
+
+
+class VsdxLoader(BaseLoader, ABC):
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with file path."""
+ self.file_path = str(file_path)
+ if "~" in self.file_path:
+ self.file_path = os.path.expanduser(self.file_path)
+
+ # If the file is a web path, download it to a temporary file, and use that
+ if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
+ r = requests.get(self.file_path)
+
+ if r.status_code != 200:
+ raise ValueError(
+ "Check the url of your file; returned status code %s"
+ % r.status_code
+ )
+
+ self.web_path = self.file_path
+ self.temp_file = tempfile.NamedTemporaryFile()
+ self.temp_file.write(r.content)
+ self.file_path = self.temp_file.name
+ elif not os.path.isfile(self.file_path):
+ raise ValueError("File path %s is not a valid file or url" % self.file_path)
+
+ self.parser = VsdxParser()
+
+ def __del__(self) -> None:
+ if hasattr(self, "temp_file"):
+ self.temp_file.close()
+
+ @staticmethod
+ def _is_valid_url(url: str) -> bool:
+ """Check if the url is valid."""
+ parsed = urlparse(url)
+ return bool(parsed.netloc) and bool(parsed.scheme)
+
+ def load(self) -> List[Document]:
+ blob = Blob.from_path(self.file_path)
+ return list(self.parser.parse(blob))
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/weather.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/weather.py
new file mode 100644
index 0000000000000000000000000000000000000000..a051f9ccf47d926100794e4d6326d01ecd8eb256
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/weather.py
@@ -0,0 +1,46 @@
+"""Simple reader that reads weather data from OpenWeatherMap API"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Iterator, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper
+
+
+class WeatherDataLoader(BaseLoader):
+ """Load weather data with `Open Weather Map` API.
+
+ Reads the forecast & current weather of any location using OpenWeatherMap's free
+ API. Checkout 'https://openweathermap.org/appid' for more on how to generate a free
+ OpenWeatherMap API.
+ """
+
+ def __init__(
+ self,
+ client: OpenWeatherMapAPIWrapper,
+ places: Sequence[str],
+ ) -> None:
+ """Initialize with parameters."""
+ super().__init__()
+ self.client = client
+ self.places = places
+
+ @classmethod
+ def from_params(
+ cls, places: Sequence[str], *, openweathermap_api_key: Optional[str] = None
+ ) -> WeatherDataLoader:
+ client = OpenWeatherMapAPIWrapper(openweathermap_api_key=openweathermap_api_key)
+ return cls(client, places)
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazily load weather data for the given locations."""
+ for place in self.places:
+ metadata = {"queried_at": datetime.now()}
+ content = self.client.run(place)
+ yield Document(page_content=content, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/web_base.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/web_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e227d0c46160d85e49ef46e58722525c63e60c4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/web_base.py
@@ -0,0 +1,406 @@
+"""Web base loader class."""
+
+import asyncio
+import logging
+import warnings
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Union
+
+import aiohttp
+import requests
+from langchain_core._api import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utils.user_agent import get_user_agent
+
+logger = logging.getLogger(__name__)
+
+default_header_template = {
+ "User-Agent": get_user_agent(),
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*"
+ ";q=0.8",
+ "Accept-Language": "en-US,en;q=0.5",
+ "Referer": "https://www.google.com/",
+ "DNT": "1",
+ "Connection": "keep-alive",
+ "Upgrade-Insecure-Requests": "1",
+}
+
+
+def _build_metadata(soup: Any, url: str) -> dict:
+ """Build metadata from BeautifulSoup output."""
+ metadata = {"source": url}
+ if title := soup.find("title"):
+ metadata["title"] = title.get_text()
+ if description := soup.find("meta", attrs={"name": "description"}):
+ metadata["description"] = description.get("content", "No description found.")
+ if html := soup.find("html"):
+ metadata["language"] = html.get("lang", "No language found.")
+ return metadata
+
+
+class WebBaseLoader(BaseLoader):
+ """
+ WebBaseLoader document loader integration
+
+ Setup:
+ Install ``langchain_community``.
+
+ .. code-block:: bash
+
+ pip install -U langchain_community
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import WebBaseLoader
+
+ loader = WebBaseLoader(
+ web_path = "https://www.espn.com/"
+ # header_template = None,
+ # verify_ssl = True,
+ # proxies = None,
+ # continue_on_failure = False,
+ # autoset_encoding = True,
+ # encoding = None,
+ # web_paths = (),
+ # requests_per_second = 2,
+ # default_parser = "html.parser",
+ # requests_kwargs = None,
+ # raise_for_status = False,
+ # bs_get_text_kwargs = None,
+ # bs_kwargs = None,
+ # session = None,
+ # show_progress = True,
+ # trust_env = False,
+ )
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ for doc in loader.lazy_load():
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ ESPN - Serving Sports Fans. Anytime. Anywhere.
+
+ {'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'}
+
+
+ Async load:
+ .. code-block:: python
+
+ docs = []
+ async for doc in loader.alazy_load():
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ ESPN - Serving Sports Fans. Anytime. Anywhere.
+
+ {'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'}
+
+ .. versionchanged:: 0.3.14
+
+ Deprecated ``aload`` (which was not async) and implemented a native async
+ ``alazy_load``. Expand below for more details.
+
+ .. dropdown:: How to update ``aload``
+
+ Instead of using ``aload``, you can use ``load`` for synchronous loading or
+ ``alazy_load`` for asynchronous lazy loading.
+
+ Example using ``load`` (synchronous):
+
+ .. code-block:: python
+
+ docs: List[Document] = loader.load()
+
+ Example using ``alazy_load`` (asynchronous):
+
+ .. code-block:: python
+
+ docs: List[Document] = []
+ async for doc in loader.alazy_load():
+ docs.append(doc)
+
+ This is in preparation for accommodating an asynchronous ``aload`` in the
+ future:
+
+ .. code-block:: python
+
+ docs: List[Document] = await loader.aload()
+
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ web_path: Union[str, Sequence[str]] = "",
+ header_template: Optional[dict] = None,
+ verify_ssl: bool = True,
+ proxies: Optional[dict] = None,
+ continue_on_failure: bool = False,
+ autoset_encoding: bool = True,
+ encoding: Optional[str] = None,
+ web_paths: Sequence[str] = (),
+ requests_per_second: int = 2,
+ default_parser: str = "html.parser",
+ requests_kwargs: Optional[Dict[str, Any]] = None,
+ raise_for_status: bool = False,
+ bs_get_text_kwargs: Optional[Dict[str, Any]] = None,
+ bs_kwargs: Optional[Dict[str, Any]] = None,
+ session: Any = None,
+ *,
+ show_progress: bool = True,
+ trust_env: bool = False,
+ ) -> None:
+ """Initialize loader.
+
+ Args:
+ web_paths: Web paths to load from.
+ requests_per_second: Max number of concurrent requests to make.
+ default_parser: Default parser to use for BeautifulSoup.
+ requests_kwargs: kwargs for requests
+ raise_for_status: Raise an exception if http status code denotes an error.
+ bs_get_text_kwargs: kwargs for beatifulsoup4 get_text
+ bs_kwargs: kwargs for beatifulsoup4 web page parsing
+ show_progress: Show progress bar when loading pages.
+ trust_env: set to True if using proxy to make web requests, for example
+ using http(s)_proxy environment variables. Defaults to False.
+ """
+ # web_path kept for backwards-compatibility.
+ if web_path and web_paths:
+ raise ValueError(
+ "Received web_path and web_paths. Only one can be specified. "
+ "web_path is deprecated, web_paths should be used."
+ )
+ if web_paths:
+ self.web_paths = list(web_paths)
+ elif isinstance(web_path, str):
+ self.web_paths = [web_path]
+ elif isinstance(web_path, Sequence):
+ self.web_paths = list(web_path)
+ else:
+ raise TypeError(
+ f"web_path must be str or Sequence[str] got ({type(web_path)}) or"
+ f" web_paths must be Sequence[str] got ({type(web_paths)})"
+ )
+ self.requests_per_second = requests_per_second
+ self.default_parser = default_parser
+ self.requests_kwargs = requests_kwargs or {}
+ self.raise_for_status = raise_for_status
+ self.show_progress = show_progress
+ self.bs_get_text_kwargs = bs_get_text_kwargs or {}
+ self.bs_kwargs = bs_kwargs or {}
+ if session:
+ self.session = session
+ else:
+ session = requests.Session()
+ header_template = header_template or default_header_template.copy()
+ if not header_template.get("User-Agent"):
+ try:
+ from fake_useragent import UserAgent
+
+ header_template["User-Agent"] = UserAgent().random
+ except ImportError:
+ logger.info(
+ "fake_useragent not found, using default user agent."
+ "To get a realistic header for requests, "
+ "`pip install fake_useragent`."
+ )
+ session.headers = dict(header_template)
+ session.verify = verify_ssl
+ if proxies:
+ session.proxies.update(proxies)
+ self.session = session
+ self.continue_on_failure = continue_on_failure
+ self.autoset_encoding = autoset_encoding
+ self.encoding = encoding
+ self.trust_env = trust_env
+
+ @property
+ def web_path(self) -> str:
+ if len(self.web_paths) > 1:
+ raise ValueError("Multiple webpaths found.")
+ return self.web_paths[0]
+
+ async def _fetch(
+ self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
+ ) -> str:
+ async with aiohttp.ClientSession(trust_env=self.trust_env) as session:
+ for i in range(retries):
+ try:
+ kwargs: Dict = dict(
+ headers=self.session.headers,
+ cookies=self.session.cookies.get_dict(),
+ )
+ if not self.session.verify:
+ kwargs["ssl"] = False
+
+ async with session.get(
+ url, **(self.requests_kwargs | kwargs)
+ ) as response:
+ if self.raise_for_status:
+ response.raise_for_status()
+ return await response.text()
+ except aiohttp.ClientConnectionError as e:
+ if i == retries - 1:
+ raise
+ else:
+ logger.warning(
+ f"Error fetching {url} with attempt "
+ f"{i + 1}/{retries}: {e}. Retrying..."
+ )
+ await asyncio.sleep(cooldown * backoff**i)
+ raise ValueError("retry count exceeded")
+
+ async def _fetch_with_rate_limit(
+ self, url: str, semaphore: asyncio.Semaphore
+ ) -> str:
+ async with semaphore:
+ try:
+ return await self._fetch(url)
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.warning(
+ f"Error fetching {url}, skipping due to"
+ f" continue_on_failure=True"
+ )
+ return ""
+ logger.exception(
+ f"Error fetching {url} and aborting, use continue_on_failure=True "
+ "to continue loading urls after encountering an error."
+ )
+ raise e
+
+ async def fetch_all(self, urls: List[str]) -> Any:
+ """Fetch all urls concurrently with rate limiting."""
+ semaphore = asyncio.Semaphore(self.requests_per_second)
+ tasks = []
+ for url in urls:
+ task = asyncio.ensure_future(self._fetch_with_rate_limit(url, semaphore))
+ tasks.append(task)
+ try:
+ if self.show_progress:
+ from tqdm.asyncio import tqdm_asyncio
+
+ return await tqdm_asyncio.gather(
+ *tasks, desc="Fetching pages", ascii=True, mininterval=1
+ )
+ else:
+ return await asyncio.gather(*tasks)
+ except ImportError:
+ warnings.warn("For better logging of progress, `pip install tqdm`")
+ return await asyncio.gather(*tasks)
+
+ @staticmethod
+ def _check_parser(parser: str) -> None:
+ """Check that parser is valid for bs4."""
+ valid_parsers = ["html.parser", "lxml", "xml", "lxml-xml", "html5lib"]
+ if parser not in valid_parsers:
+ raise ValueError(
+ "`parser` must be one of " + ", ".join(valid_parsers) + "."
+ )
+
+ def _unpack_fetch_results(
+ self, results: Any, urls: List[str], parser: Union[str, None] = None
+ ) -> List[Any]:
+ """Unpack fetch results into BeautifulSoup objects."""
+ from bs4 import BeautifulSoup
+
+ final_results = []
+ for i, result in enumerate(results):
+ url = urls[i]
+ if parser is None:
+ if url.endswith(".xml"):
+ parser = "xml"
+ else:
+ parser = self.default_parser
+ self._check_parser(parser)
+ final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs))
+ return final_results
+
+ def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]:
+ """Fetch all urls, then return soups for all results."""
+ results = asyncio.run(self.fetch_all(urls))
+ return self._unpack_fetch_results(results, urls, parser=parser)
+
+ async def ascrape_all(
+ self, urls: List[str], parser: Union[str, None] = None
+ ) -> List[Any]:
+ """Async fetch all urls, then return soups for all results."""
+ results = await self.fetch_all(urls)
+ return self._unpack_fetch_results(results, urls, parser=parser)
+
+ def _scrape(
+ self,
+ url: str,
+ parser: Union[str, None] = None,
+ bs_kwargs: Optional[dict] = None,
+ ) -> Any:
+ from bs4 import BeautifulSoup
+
+ if parser is None:
+ if url.endswith(".xml"):
+ parser = "xml"
+ else:
+ parser = self.default_parser
+
+ self._check_parser(parser)
+
+ html_doc = self.session.get(url, **self.requests_kwargs)
+ if self.raise_for_status:
+ html_doc.raise_for_status()
+
+ if self.encoding is not None:
+ html_doc.encoding = self.encoding
+ elif self.autoset_encoding:
+ html_doc.encoding = html_doc.apparent_encoding
+ return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {}))
+
+ def scrape(self, parser: Union[str, None] = None) -> Any:
+ """Scrape data from webpage and return it in BeautifulSoup format."""
+
+ return self._scrape(self.web_path, parser=parser, bs_kwargs=self.bs_kwargs)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load text from the url(s) in web_path."""
+ for path in self.web_paths:
+ soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
+ text = soup.get_text(**self.bs_get_text_kwargs)
+ metadata = _build_metadata(soup, path)
+ yield Document(page_content=text, metadata=metadata)
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Async lazy load text from the url(s) in web_path."""
+ results = await self.ascrape_all(self.web_paths)
+ for path, soup in zip(self.web_paths, results):
+ text = soup.get_text(**self.bs_get_text_kwargs)
+ metadata = _build_metadata(soup, path)
+ yield Document(page_content=text, metadata=metadata)
+
+ @deprecated(
+ since="0.3.14",
+ removal="1.0",
+ message=(
+ "See API reference for updated usage: "
+ "https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.web_base.WebBaseLoader.html" # noqa: E501
+ ),
+ )
+ def aload(self) -> List[Document]: # type: ignore[override]
+ """Load text from the urls in web_path async into Documents."""
+
+ results = self.scrape_all(self.web_paths)
+ docs = []
+ for path, soup in zip(self.web_paths, results):
+ text = soup.get_text(**self.bs_get_text_kwargs)
+ metadata = _build_metadata(soup, path)
+ docs.append(Document(page_content=text, metadata=metadata))
+
+ return docs
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/whatsapp_chat.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/whatsapp_chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..decda7f3ff910d1f0d637c015bd95662230b1a8a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/whatsapp_chat.py
@@ -0,0 +1,64 @@
+import re
+from pathlib import Path
+from typing import Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+def concatenate_rows(date: str, sender: str, text: str) -> str:
+ """Combine message information in a readable format ready to be used."""
+ return f"{sender} on {date}: {text}\n\n"
+
+
+class WhatsAppChatLoader(BaseLoader):
+ """Load `WhatsApp` messages text file."""
+
+ def __init__(self, path: str):
+ """Initialize with path."""
+ self.file_path = path
+
+ def lazy_load(self) -> Iterator[Document]:
+ p = Path(self.file_path)
+ text_content = ""
+
+ with open(p, encoding="utf8") as f:
+ lines = f.readlines()
+
+ message_line_regex = r"""
+ \[?
+ (
+ \d{1,4}
+ [\/.]
+ \d{1,2}
+ [\/.]
+ \d{1,4}
+ ,\s
+ \d{1,2}
+ :\d{2}
+ (?:
+ :\d{2}
+ )?
+ (?:[\s_](?:AM|PM))?
+ )
+ \]?
+ [\s-]*
+ ([~\w\s]+)
+ [:]+
+ \s
+ (.+)
+ """
+ ignore_lines = ["This message was deleted", ""]
+ for line in lines:
+ result = re.match(
+ message_line_regex, line.strip(), flags=re.VERBOSE | re.IGNORECASE
+ )
+ if result:
+ date, sender, text = result.groups()
+ if text not in ignore_lines:
+ text_content += concatenate_rows(date, sender, text)
+
+ metadata = {"source": str(p)}
+
+ yield Document(page_content=text_content, metadata=metadata)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/wikipedia.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/wikipedia.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae9c38d7635bbf0790a70c8864b6e67cbb0fd2d4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/wikipedia.py
@@ -0,0 +1,59 @@
+from typing import Iterator, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
+
+
+class WikipediaLoader(BaseLoader):
+ """Load from `Wikipedia`.
+
+ The hard limit on the length of the query is 300 for now.
+
+ Each wiki page represents one Document.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ lang: str = "en",
+ load_max_docs: Optional[int] = 25,
+ load_all_available_meta: Optional[bool] = False,
+ doc_content_chars_max: Optional[int] = 4000,
+ ):
+ """
+ Initializes a new instance of the WikipediaLoader class.
+
+ Args:
+ query (str): The query string to search on Wikipedia.
+ lang (str, optional): The language code for the Wikipedia language edition.
+ Defaults to "en".
+ load_max_docs (int, optional): The maximum number of documents to load.
+ Defaults to 100.
+ load_all_available_meta (bool, optional): Indicates whether to load all
+ available metadata for each document. Defaults to False.
+ doc_content_chars_max (int, optional): The maximum number of characters
+ for the document content. Defaults to 4000.
+ """
+ self.query = query
+ self.lang = lang
+ self.load_max_docs = load_max_docs
+ self.load_all_available_meta = load_all_available_meta
+ self.doc_content_chars_max = doc_content_chars_max
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Loads the query result from Wikipedia into a list of `Document` objects.
+
+ Returns:
+ A list of `Document` objects representing the loaded
+ Wikipedia pages.
+ """
+ client = WikipediaAPIWrapper( # type: ignore[call-arg]
+ lang=self.lang,
+ top_k_results=self.load_max_docs, # type: ignore[arg-type]
+ load_all_available_meta=self.load_all_available_meta, # type: ignore[arg-type]
+ doc_content_chars_max=self.doc_content_chars_max, # type: ignore[arg-type]
+ )
+ yield from client.load(self.query)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/word_document.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/word_document.py
new file mode 100644
index 0000000000000000000000000000000000000000..957eefe7bcca14de48580f5d3751b11db4a7b5fd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/word_document.py
@@ -0,0 +1,139 @@
+"""Loads word documents."""
+
+import os
+import tempfile
+from abc import ABC
+from pathlib import Path
+from typing import Any, List, Union
+from urllib.parse import urlparse
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class Docx2txtLoader(BaseLoader, ABC):
+ """Load `DOCX` file using `docx2txt` and chunks at character level.
+
+ Defaults to check for local file, but if the file is a web path, it will download it
+ to a temporary file, and use that, then clean up the temporary file after completion
+ """
+
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with file path."""
+ self.file_path = str(file_path)
+ self.original_file_path = self.file_path
+ if "~" in self.file_path:
+ self.file_path = os.path.expanduser(self.file_path)
+
+ # If the file is a web path, download it to a temporary file, and use that
+ if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
+ r = requests.get(self.file_path)
+
+ if r.status_code != 200:
+ raise ValueError(
+ "Check the url of your file; returned status code %s"
+ % r.status_code
+ )
+
+ self.web_path = self.file_path
+ self.temp_file = tempfile.NamedTemporaryFile()
+ self.temp_file.write(r.content)
+ self.file_path = self.temp_file.name
+ elif not os.path.isfile(self.file_path):
+ raise ValueError("File path %s is not a valid file or url" % self.file_path)
+
+ def __del__(self) -> None:
+ if hasattr(self, "temp_file"):
+ self.temp_file.close()
+
+ def load(self) -> List[Document]:
+ """Load given path as single page."""
+ import docx2txt
+
+ return [
+ Document(
+ page_content=docx2txt.process(self.file_path),
+ metadata={"source": self.original_file_path},
+ )
+ ]
+
+ @staticmethod
+ def _is_valid_url(url: str) -> bool:
+ """Check if the url is valid."""
+ parsed = urlparse(url)
+ return bool(parsed.netloc) and bool(parsed.scheme)
+
+
+class UnstructuredWordDocumentLoader(UnstructuredFileLoader):
+ """Load `Microsoft Word` file using `Unstructured`.
+
+ Works with both .docx and .doc files.
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredWordDocumentLoader
+
+ loader = UnstructuredWordDocumentLoader(
+ "example.docx", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-docx
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the Word file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.file_utils.filetype import FileType, detect_filetype
+
+ # NOTE(MthwRobinson) - magic will raise an import error if the libmagic
+ # system dependency isn't installed. If it's not installed, we'll just
+ # check the file extension
+ try:
+ import magic # noqa: F401
+
+ is_doc = detect_filetype(self.file_path) == FileType.DOC
+ except ImportError:
+ _, extension = os.path.splitext(str(self.file_path))
+ is_doc = extension == ".doc"
+
+ if is_doc:
+ validate_unstructured_version("0.4.11")
+
+ if is_doc:
+ from unstructured.partition.doc import partition_doc
+
+ return partition_doc(filename=self.file_path, **self.unstructured_kwargs)
+ else:
+ from unstructured.partition.docx import partition_docx
+
+ return partition_docx(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xml.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xml.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4757f222b884eb452531abef85d6761ab83b1c8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xml.py
@@ -0,0 +1,49 @@
+"""Loads Microsoft Excel files."""
+
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredXMLLoader(UnstructuredFileLoader):
+ """Load `XML` file using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredXMLLoader
+
+ loader = UnstructuredXMLLoader(
+ "example.xml", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-xml
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.6.7")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.xml import partition_xml
+
+ return partition_xml(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xorbits.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xorbits.py
new file mode 100644
index 0000000000000000000000000000000000000000..67c87e80bff2c0af19f74bbd843c7e90b42196ab
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/xorbits.py
@@ -0,0 +1,32 @@
+from typing import Any
+
+from langchain_community.document_loaders.dataframe import BaseDataFrameLoader
+
+
+class XorbitsLoader(BaseDataFrameLoader):
+ """Load `Xorbits` DataFrame."""
+
+ def __init__(self, data_frame: Any, page_content_column: str = "text"):
+ """Initialize with dataframe object.
+
+ Requirements:
+ Must have xorbits installed. You can install with `pip install xorbits`.
+
+ Args:
+ data_frame: Xorbits DataFrame object.
+ page_content_column: Name of the column containing the page content.
+ Defaults to "text".
+ """
+ try:
+ import xorbits.pandas as pd
+ except ImportError as e:
+ raise ImportError(
+ "Cannot import xorbits, please install with 'pip install xorbits'."
+ ) from e
+
+ if not isinstance(data_frame, pd.DataFrame):
+ raise ValueError(
+ f"Expected data_frame to be a xorbits.pandas.DataFrame, \
+ got {type(data_frame)}"
+ )
+ super().__init__(data_frame, page_content_column=page_content_column)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/youtube.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/youtube.py
new file mode 100644
index 0000000000000000000000000000000000000000..a52c37f6f1432f5deb6fdecae1bb085d3c00f8cd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/youtube.py
@@ -0,0 +1,529 @@
+"""Loads YouTube transcript."""
+
+from __future__ import annotations
+
+import logging
+from enum import Enum
+from pathlib import Path
+from typing import Any, Dict, Generator, List, Optional, Sequence, Union
+from urllib.parse import parse_qs, urlparse
+from xml.etree.ElementTree import ParseError # OK: trusted-source
+
+from langchain_core.documents import Document
+from pydantic import model_validator
+from pydantic.dataclasses import dataclass
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
+
+
+@dataclass
+class GoogleApiClient:
+ """Generic Google API Client.
+
+ To use, you should have the ``google_auth_oauthlib,youtube_transcript_api,google``
+ python package installed.
+ As the google api expects credentials you need to set up a google account and
+ register your Service. "https://developers.google.com/docs/api/quickstart/python"
+
+ *Security Note*: Note that parsing of the transcripts relies on the standard
+ xml library but the input is viewed as trusted in this case.
+
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import GoogleApiClient
+ google_api_client = GoogleApiClient(
+ service_account_path=Path("path_to_your_sec_file.json")
+ )
+
+ """
+
+ credentials_path: Path = Path.home() / ".credentials" / "credentials.json"
+ service_account_path: Path = Path.home() / ".credentials" / "credentials.json"
+ token_path: Path = Path.home() / ".credentials" / "token.json"
+
+ def __post_init__(self) -> None:
+ self.creds = self._load_credentials()
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_channel_or_videoIds_is_set(cls, values: Any) -> Any:
+ """Validate that either folder_id or document_ids is set, but not both."""
+
+ if not values.kwargs.get("credentials_path") and not values.kwargs.get(
+ "service_account_path"
+ ):
+ raise ValueError("Must specify either channel_name or video_ids")
+ return values.kwargs
+
+ def _load_credentials(self) -> Any:
+ """Load credentials."""
+ # Adapted from https://developers.google.com/drive/api/v3/quickstart/python
+ try:
+ from google.auth.transport.requests import Request
+ from google.oauth2 import service_account
+ from google.oauth2.credentials import Credentials
+ from google_auth_oauthlib.flow import InstalledAppFlow
+ from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "You must run"
+ "`pip install --upgrade "
+ "google-api-python-client google-auth-httplib2 "
+ "google-auth-oauthlib "
+ "youtube-transcript-api` "
+ "to use the Google Drive loader"
+ )
+
+ creds = None
+ if self.service_account_path.exists():
+ return service_account.Credentials.from_service_account_file(
+ str(self.service_account_path)
+ )
+ if self.token_path.exists():
+ creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)
+
+ if not creds or not creds.valid:
+ if creds and creds.expired and creds.refresh_token:
+ creds.refresh(Request())
+ else:
+ flow = InstalledAppFlow.from_client_secrets_file(
+ str(self.credentials_path), SCOPES
+ )
+ creds = flow.run_local_server(port=0)
+ with open(self.token_path, "w") as token:
+ token.write(creds.to_json())
+
+ return creds
+
+
+ALLOWED_SCHEMES = {"http", "https"}
+ALLOWED_NETLOCS = {
+ "youtu.be",
+ "m.youtube.com",
+ "youtube.com",
+ "www.youtube.com",
+ "www.youtube-nocookie.com",
+ "vid.plus",
+}
+
+
+def _parse_video_id(url: str) -> Optional[str]:
+ """Parse a YouTube URL and return the video ID if valid, otherwise None."""
+ parsed_url = urlparse(url)
+
+ if parsed_url.scheme not in ALLOWED_SCHEMES:
+ return None
+
+ if parsed_url.netloc not in ALLOWED_NETLOCS:
+ return None
+
+ path = parsed_url.path
+
+ if path.endswith("/watch"):
+ query = parsed_url.query
+ parsed_query = parse_qs(query)
+ if "v" in parsed_query:
+ ids = parsed_query["v"]
+ video_id = ids if isinstance(ids, str) else ids[0]
+ else:
+ return None
+ else:
+ path = parsed_url.path.lstrip("/")
+ video_id = path.split("/")[-1]
+
+ if len(video_id) != 11: # Video IDs are 11 characters long
+ return None
+
+ return video_id
+
+
+class TranscriptFormat(Enum):
+ """Output formats of transcripts from `YoutubeLoader`."""
+
+ TEXT = "text"
+ LINES = "lines"
+ CHUNKS = "chunks"
+
+
+class YoutubeLoader(BaseLoader):
+ """Load `YouTube` video transcripts."""
+
+ def __init__(
+ self,
+ video_id: str,
+ add_video_info: bool = False,
+ language: Union[str, Sequence[str]] = "en",
+ translation: Optional[str] = None,
+ transcript_format: TranscriptFormat = TranscriptFormat.TEXT,
+ continue_on_failure: bool = False,
+ chunk_size_seconds: int = 120,
+ ):
+ """Initialize with YouTube video ID."""
+ self.video_id = video_id
+ self._metadata = {"source": video_id}
+ self.add_video_info = add_video_info
+ self.language = language
+ if isinstance(language, str):
+ self.language = [language]
+ else:
+ self.language = language
+ self.translation = translation
+ self.transcript_format = transcript_format
+ self.continue_on_failure = continue_on_failure
+ self.chunk_size_seconds = chunk_size_seconds
+
+ @staticmethod
+ def extract_video_id(youtube_url: str) -> str:
+ """Extract video ID from common YouTube URLs."""
+ video_id = _parse_video_id(youtube_url)
+ if not video_id:
+ raise ValueError(
+ f'Could not determine the video ID for the URL "{youtube_url}".'
+ )
+ return video_id
+
+ @classmethod
+ def from_youtube_url(cls, youtube_url: str, **kwargs: Any) -> YoutubeLoader:
+ """Given a YouTube URL, construct a loader.
+ See `YoutubeLoader()` constructor for a list of keyword arguments.
+ """
+ video_id = cls.extract_video_id(youtube_url)
+ return cls(video_id, **kwargs)
+
+ def _make_chunk_document(
+ self, chunk_pieces: List[Dict], chunk_start_seconds: int
+ ) -> Document:
+ """Create Document from chunk of transcript pieces."""
+ m, s = divmod(chunk_start_seconds, 60)
+ h, m = divmod(m, 60)
+ return Document(
+ page_content=" ".join(
+ map(lambda chunk_piece: chunk_piece["text"].strip(" "), chunk_pieces)
+ ),
+ metadata={
+ **self._metadata,
+ "start_seconds": chunk_start_seconds,
+ "start_timestamp": f"{h:02d}:{m:02d}:{s:02d}",
+ "source":
+ # replace video ID with URL to start time
+ f"https://www.youtube.com/watch?v={self.video_id}"
+ f"&t={chunk_start_seconds}s",
+ },
+ )
+
+ def _get_transcript_chunks(
+ self, transcript_pieces: List[Dict]
+ ) -> Generator[Document, None, None]:
+ chunk_pieces: List[Dict[str, Any]] = []
+ chunk_start_seconds = 0
+ chunk_time_limit = self.chunk_size_seconds
+ for transcript_piece in transcript_pieces:
+ piece_end = transcript_piece["start"] + transcript_piece["duration"]
+ if piece_end > chunk_time_limit:
+ if chunk_pieces:
+ yield self._make_chunk_document(chunk_pieces, chunk_start_seconds)
+ chunk_pieces = []
+ chunk_start_seconds = chunk_time_limit
+ chunk_time_limit += self.chunk_size_seconds
+
+ chunk_pieces.append(transcript_piece)
+
+ if len(chunk_pieces) > 0:
+ yield self._make_chunk_document(chunk_pieces, chunk_start_seconds)
+
+ def load(self) -> List[Document]:
+ """Load YouTube transcripts into `Document` objects."""
+ try:
+ from youtube_transcript_api import (
+ FetchedTranscript,
+ NoTranscriptFound,
+ TranscriptsDisabled,
+ YouTubeTranscriptApi,
+ )
+ except ImportError:
+ raise ImportError(
+ 'Could not import "youtube_transcript_api" Python package. '
+ "Please install it with `pip install youtube-transcript-api`."
+ )
+
+ if self.add_video_info:
+ # Get more video meta info
+ # Such as title, description, thumbnail url, publish_date
+ video_info = self._get_video_info()
+ self._metadata.update(video_info)
+
+ try:
+ ytt_api = YouTubeTranscriptApi()
+ transcript_list = ytt_api.list(self.video_id)
+ except TranscriptsDisabled:
+ return []
+
+ try:
+ transcript = transcript_list.find_transcript(self.language)
+ except NoTranscriptFound:
+ transcript = transcript_list.find_transcript(["en"])
+
+ if self.translation is not None:
+ transcript = transcript.translate(self.translation)
+ transcript_object = transcript.fetch()
+ if isinstance(transcript_object, FetchedTranscript):
+ transcript_pieces = [
+ {
+ "text": snippet.text,
+ "start": snippet.start,
+ "duration": snippet.duration,
+ }
+ for snippet in transcript_object.snippets
+ ]
+ else:
+ transcript_pieces: List[Dict[str, Any]] = transcript_object # type: ignore[no-redef]
+
+ if self.transcript_format == TranscriptFormat.TEXT:
+ transcript = " ".join(
+ map(
+ lambda transcript_piece: transcript_piece["text"].strip(" "),
+ transcript_pieces,
+ )
+ )
+ return [Document(page_content=transcript, metadata=self._metadata)]
+ elif self.transcript_format == TranscriptFormat.LINES:
+ return list(
+ map(
+ lambda transcript_piece: Document(
+ page_content=transcript_piece["text"].strip(" "),
+ metadata=dict(
+ filter(
+ lambda item: item[0] != "text", transcript_piece.items()
+ )
+ ),
+ ),
+ transcript_pieces,
+ )
+ )
+ elif self.transcript_format == TranscriptFormat.CHUNKS:
+ return list(self._get_transcript_chunks(transcript_pieces))
+
+ else:
+ raise ValueError("Unknown transcript format.")
+
+ def _get_video_info(self) -> Dict:
+ """Get important video information.
+
+ Components include:
+ - title
+ - description
+ - thumbnail URL,
+ - publish_date
+ - channel author
+ - and more.
+ """
+ try:
+ from pytube import YouTube
+
+ except ImportError:
+ raise ImportError(
+ 'Could not import "pytube" Python package. '
+ "Please install it with `pip install pytube`."
+ )
+ yt = YouTube(f"https://www.youtube.com/watch?v={self.video_id}")
+ video_info = {
+ "title": yt.title or "Unknown",
+ "description": yt.description or "Unknown",
+ "view_count": yt.views or 0,
+ "thumbnail_url": yt.thumbnail_url or "Unknown",
+ "publish_date": yt.publish_date.strftime("%Y-%m-%d %H:%M:%S")
+ if yt.publish_date
+ else "Unknown",
+ "length": yt.length or 0,
+ "author": yt.author or "Unknown",
+ }
+ return video_info
+
+
+@dataclass
+class GoogleApiYoutubeLoader(BaseLoader):
+ """Load all Videos from a `YouTube` Channel.
+
+ To use, you should have the ``googleapiclient,youtube_transcript_api``
+ python package installed.
+ As the service needs a google_api_client, you first have to initialize
+ the GoogleApiClient.
+
+ Additionally you have to either provide a channel name or a list of videoids
+ "https://developers.google.com/docs/api/quickstart/python"
+
+
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import GoogleApiClient
+ from langchain_community.document_loaders import GoogleApiYoutubeLoader
+ google_api_client = GoogleApiClient(
+ service_account_path=Path("path_to_your_sec_file.json")
+ )
+ loader = GoogleApiYoutubeLoader(
+ google_api_client=google_api_client,
+ channel_name = "CodeAesthetic"
+ )
+ load.load()
+
+ """
+
+ google_api_client: GoogleApiClient
+ channel_name: Optional[str] = None
+ video_ids: Optional[List[str]] = None
+ add_video_info: bool = True
+ captions_language: str = "en"
+ continue_on_failure: bool = False
+
+ def __post_init__(self) -> None:
+ self.youtube_client = self._build_youtube_client(self.google_api_client.creds)
+
+ def _build_youtube_client(self, creds: Any) -> Any:
+ try:
+ from googleapiclient.discovery import build
+ from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "You must run"
+ "`pip install --upgrade "
+ "google-api-python-client google-auth-httplib2 "
+ "google-auth-oauthlib "
+ "youtube-transcript-api` "
+ "to use the Google Drive loader"
+ )
+
+ return build("youtube", "v3", credentials=creds)
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_channel_or_videoIds_is_set(cls, values: Any) -> Any:
+ """Validate that either folder_id or document_ids is set, but not both."""
+ if not values.kwargs.get("channel_name") and not values.kwargs.get("video_ids"):
+ raise ValueError("Must specify either channel_name or video_ids")
+ return values.kwargs
+
+ def _get_transcripe_for_video_id(self, video_id: str) -> str:
+ from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi
+
+ ytt_api = YouTubeTranscriptApi()
+ transcript_list = ytt_api.list(video_id)
+ try:
+ transcript = transcript_list.find_transcript([self.captions_language])
+ except NoTranscriptFound:
+ for available_transcript in transcript_list:
+ transcript = available_transcript.translate(self.captions_language)
+ continue
+
+ transcript_pieces = transcript.fetch()
+ return " ".join([t["text"].strip(" ") for t in transcript_pieces])
+
+ def _get_document_for_video_id(self, video_id: str, **kwargs: Any) -> Document:
+ captions = self._get_transcripe_for_video_id(video_id)
+ video_response = (
+ self.youtube_client.videos()
+ .list(
+ part="id,snippet",
+ id=video_id,
+ )
+ .execute()
+ )
+ return Document(
+ page_content=captions,
+ metadata=video_response.get("items")[0],
+ )
+
+ def _get_channel_id(self, channel_name: str) -> str:
+ request = self.youtube_client.search().list(
+ part="id",
+ q=channel_name,
+ type="channel",
+ maxResults=1, # we only need one result since channel names are unique
+ )
+ response = request.execute()
+ channel_id = response["items"][0]["id"]["channelId"]
+ return channel_id
+
+ def _get_uploads_playlist_id(self, channel_id: str) -> str:
+ request = self.youtube_client.channels().list(
+ part="contentDetails",
+ id=channel_id,
+ )
+ response = request.execute()
+ return response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
+
+ def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]:
+ try:
+ from youtube_transcript_api import (
+ NoTranscriptFound,
+ TranscriptsDisabled,
+ )
+ except ImportError:
+ raise ImportError(
+ "You must run"
+ "`pip install --upgrade "
+ "youtube-transcript-api` "
+ "to use the youtube loader"
+ )
+
+ channel_id = self._get_channel_id(channel)
+ uploads_playlist_id = self._get_uploads_playlist_id(channel_id)
+ request = self.youtube_client.playlistItems().list(
+ part="id,snippet",
+ playlistId=uploads_playlist_id,
+ maxResults=50,
+ )
+ video_ids = []
+ while request is not None:
+ response = request.execute()
+
+ # Add each video ID to the list
+ for item in response["items"]:
+ video_id = item["snippet"]["resourceId"]["videoId"]
+ meta_data = {"videoId": video_id}
+ if self.add_video_info:
+ item["snippet"].pop("thumbnails")
+ meta_data.update(item["snippet"])
+ try:
+ page_content = self._get_transcripe_for_video_id(video_id)
+ video_ids.append(
+ Document(
+ page_content=page_content,
+ metadata=meta_data,
+ )
+ )
+ except (TranscriptsDisabled, NoTranscriptFound, ParseError) as e:
+ if self.continue_on_failure:
+ logger.error(
+ "Error fetching transscript "
+ + f" {item['id']['videoId']}, exception: {e}"
+ )
+ else:
+ raise e
+ pass
+ request = self.youtube_client.search().list_next(request, response)
+
+ return video_ids
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ document_list = []
+ if self.channel_name:
+ document_list.extend(self._get_document_for_channel(self.channel_name))
+ elif self.video_ids:
+ document_list.extend(
+ [
+ self._get_document_for_video_id(video_id)
+ for video_id in self.video_ids
+ ]
+ )
+ else:
+ raise ValueError("Must specify either channel_name or video_ids")
+ return document_list
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_loaders/yuque.py b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/yuque.py
new file mode 100644
index 0000000000000000000000000000000000000000..9947c948a1fbda93bb98a5f0b99818996e5af761
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_loaders/yuque.py
@@ -0,0 +1,92 @@
+import re
+from typing import Dict, Iterator, List
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class YuqueLoader(BaseLoader):
+ """Load documents from `Yuque`."""
+
+ def __init__(self, access_token: str, api_url: str = "https://www.yuque.com"):
+ """Initialize with Yuque access_token and api_url.
+
+ Args:
+ access_token: Personal access token - see https://www.yuque.com/settings/tokens.
+ api_url: Yuque API url.
+ """
+ self.access_token = access_token
+ self.api_url = api_url
+
+ @property
+ def headers(self) -> Dict[str, str]:
+ return {
+ "Content-Type": "application/json",
+ "X-Auth-Token": self.access_token,
+ }
+
+ def get_user_id(self) -> int:
+ url = f"{self.api_url}/api/v2/user"
+ response = self.http_get(url=url)
+
+ return response["data"]["id"]
+
+ def get_books(self, user_id: int) -> List[Dict]:
+ url = f"{self.api_url}/api/v2/users/{user_id}/repos"
+ response = self.http_get(url=url)
+
+ return response["data"]
+
+ def get_document_ids(self, book_id: int) -> List[int]:
+ url = f"{self.api_url}/api/v2/repos/{book_id}/docs"
+ response = self.http_get(url=url)
+
+ return [document["id"] for document in response["data"]]
+
+ def get_document(self, book_id: int, document_id: int) -> Dict:
+ url = f"{self.api_url}/api/v2/repos/{book_id}/docs/{document_id}"
+ response = self.http_get(url=url)
+
+ return response["data"]
+
+ def parse_document(self, document: Dict) -> Document:
+ content = self.parse_document_body(document["body"])
+ metadata = {
+ "title": document["title"],
+ "description": document["description"],
+ "created_at": document["created_at"],
+ "updated_at": document["updated_at"],
+ }
+
+ return Document(page_content=content, metadata=metadata)
+
+ @staticmethod
+ def parse_document_body(body: str) -> str:
+ result = re.sub(r'', "", body)
+ result = re.sub(r"
", "", result)
+
+ return result
+
+ def http_get(self, url: str) -> Dict:
+ response = requests.get(url, headers=self.headers)
+ response.raise_for_status()
+
+ return response.json()
+
+ def get_documents(self) -> Iterator[Document]:
+ user_id = self.get_user_id()
+ books = self.get_books(user_id)
+
+ for book in books:
+ book_id = book["id"]
+ document_ids = self.get_document_ids(book_id)
+ for document_id in document_ids:
+ document = self.get_document(book_id, document_id)
+ parsed_document = self.parse_document(document)
+ yield parsed_document
+
+ def load(self) -> List[Document]:
+ """Load documents from `Yuque`."""
+ return list(self.get_documents())
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..14aa448841e61551f6e2e55468caeb8b52009029
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py
@@ -0,0 +1,95 @@
+"""**Document Transformers** are classes to transform Documents.
+
+**Document Transformers** usually used to transform a lot of Documents in a single run.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseDocumentTransformer --> # Examples: DoctranQATransformer, DoctranTextTranslator
+
+**Main helpers:**
+
+.. code-block::
+
+ Document
+""" # noqa: E501
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.document_transformers.beautiful_soup_transformer import (
+ BeautifulSoupTransformer,
+ )
+ from langchain_community.document_transformers.doctran_text_extract import (
+ DoctranPropertyExtractor,
+ )
+ from langchain_community.document_transformers.doctran_text_qa import (
+ DoctranQATransformer,
+ )
+ from langchain_community.document_transformers.doctran_text_translate import (
+ DoctranTextTranslator,
+ )
+ from langchain_community.document_transformers.embeddings_redundant_filter import (
+ EmbeddingsClusteringFilter,
+ EmbeddingsRedundantFilter,
+ get_stateful_documents,
+ )
+ from langchain_community.document_transformers.google_translate import (
+ GoogleTranslateTransformer,
+ )
+ from langchain_community.document_transformers.html2text import (
+ Html2TextTransformer,
+ )
+ from langchain_community.document_transformers.long_context_reorder import (
+ LongContextReorder,
+ )
+ from langchain_community.document_transformers.markdownify import (
+ MarkdownifyTransformer,
+ )
+ from langchain_community.document_transformers.nuclia_text_transform import (
+ NucliaTextTransformer,
+ )
+ from langchain_community.document_transformers.openai_functions import (
+ OpenAIMetadataTagger,
+ )
+
+__all__ = [
+ "BeautifulSoupTransformer",
+ "DoctranPropertyExtractor",
+ "DoctranQATransformer",
+ "DoctranTextTranslator",
+ "EmbeddingsClusteringFilter",
+ "EmbeddingsRedundantFilter",
+ "GoogleTranslateTransformer",
+ "Html2TextTransformer",
+ "LongContextReorder",
+ "MarkdownifyTransformer",
+ "NucliaTextTransformer",
+ "OpenAIMetadataTagger",
+ "get_stateful_documents",
+]
+
+_module_lookup = {
+ "BeautifulSoupTransformer": "langchain_community.document_transformers.beautiful_soup_transformer", # noqa: E501
+ "DoctranPropertyExtractor": "langchain_community.document_transformers.doctran_text_extract", # noqa: E501
+ "DoctranQATransformer": "langchain_community.document_transformers.doctran_text_qa",
+ "DoctranTextTranslator": "langchain_community.document_transformers.doctran_text_translate", # noqa: E501
+ "EmbeddingsClusteringFilter": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501
+ "EmbeddingsRedundantFilter": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501
+ "GoogleTranslateTransformer": "langchain_community.document_transformers.google_translate", # noqa: E501
+ "Html2TextTransformer": "langchain_community.document_transformers.html2text",
+ "LongContextReorder": "langchain_community.document_transformers.long_context_reorder", # noqa: E501
+ "MarkdownifyTransformer": "langchain_community.document_transformers.markdownify",
+ "NucliaTextTransformer": "langchain_community.document_transformers.nuclia_text_transform", # noqa: E501
+ "OpenAIMetadataTagger": "langchain_community.document_transformers.openai_functions", # noqa: E501
+ "get_stateful_documents": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cdc78b27da56dfd61ebe0cf38e4bc7551465795
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py
@@ -0,0 +1,205 @@
+from typing import Any, Iterator, List, Sequence, Tuple, Union, cast
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+
+
+class BeautifulSoupTransformer(BaseDocumentTransformer):
+ """Transform HTML content by extracting specific tags and removing unwanted ones.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_transformers import BeautifulSoupTransformer
+
+ bs4_transformer = BeautifulSoupTransformer()
+ docs_transformed = bs4_transformer.transform_documents(docs)
+ """ # noqa: E501
+
+ def __init__(self) -> None:
+ """
+ Initialize the transformer.
+
+ This checks if the BeautifulSoup4 package is installed.
+ If not, it raises an ImportError.
+ """
+ try:
+ import bs4 # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "BeautifulSoup4 is required for BeautifulSoupTransformer. "
+ "Please install it with `pip install beautifulsoup4`."
+ )
+
+ def transform_documents(
+ self,
+ documents: Sequence[Document],
+ unwanted_tags: Union[List[str], Tuple[str, ...]] = ("script", "style"),
+ tags_to_extract: Union[List[str], Tuple[str, ...]] = ("p", "li", "div", "a"),
+ remove_lines: bool = True,
+ *,
+ unwanted_classnames: Union[Tuple[str, ...], List[str]] = (),
+ remove_comments: bool = False,
+ **kwargs: Any,
+ ) -> Sequence[Document]:
+ """
+ Transform a list of `Document` objects by cleaning their HTML content.
+
+ Args:
+ documents: A sequence of `Document` objects containing HTML content.
+ unwanted_tags: A list of tags to be removed from the HTML.
+ tags_to_extract: A list of tags whose content will be extracted.
+ remove_lines: If set to `True`, unnecessary lines will be removed.
+ unwanted_classnames: A list of class names to be removed from the HTML
+ remove_comments: If set to `True`, comments will be removed.
+
+ Returns:
+ A sequence of Document objects with transformed content.
+ """
+ for doc in documents:
+ cleaned_content = doc.page_content
+
+ cleaned_content = self.remove_unwanted_classnames(
+ cleaned_content, unwanted_classnames
+ )
+
+ cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags)
+
+ cleaned_content = self.extract_tags(
+ cleaned_content, tags_to_extract, remove_comments=remove_comments
+ )
+
+ if remove_lines:
+ cleaned_content = self.remove_unnecessary_lines(cleaned_content)
+
+ doc.page_content = cleaned_content
+
+ return documents
+
+ @staticmethod
+ def remove_unwanted_classnames(
+ html_content: str, unwanted_classnames: Union[List[str], Tuple[str, ...]]
+ ) -> str:
+ """
+ Remove unwanted classname from a given HTML content.
+
+ Args:
+ html_content: The original HTML content string.
+ unwanted_classnames: A list of classnames to be removed from the HTML.
+
+ Returns:
+ A cleaned HTML string with unwanted classnames removed.
+ """
+ from bs4 import BeautifulSoup
+
+ soup = BeautifulSoup(html_content, "html.parser")
+ for classname in unwanted_classnames:
+ for element in soup.find_all(class_=classname):
+ element.decompose()
+ return str(soup)
+
+ @staticmethod
+ def remove_unwanted_tags(
+ html_content: str, unwanted_tags: Union[List[str], Tuple[str, ...]]
+ ) -> str:
+ """
+ Remove unwanted tags from a given HTML content.
+
+ Args:
+ html_content: The original HTML content string.
+ unwanted_tags: A list of tags to be removed from the HTML.
+
+ Returns:
+ A cleaned HTML string with unwanted tags removed.
+ """
+ from bs4 import BeautifulSoup
+
+ soup = BeautifulSoup(html_content, "html.parser")
+ for tag in unwanted_tags:
+ for element in soup.find_all(tag):
+ element.decompose()
+ return str(soup)
+
+ @staticmethod
+ def extract_tags(
+ html_content: str,
+ tags: Union[List[str], Tuple[str, ...]],
+ *,
+ remove_comments: bool = False,
+ ) -> str:
+ """
+ Extract specific tags from a given HTML content.
+
+ Args:
+ html_content: The original HTML content string.
+ tags: A list of tags to be extracted from the HTML.
+ remove_comments: If set to True, the comments will be removed.
+
+ Returns:
+ A string combining the content of the extracted tags.
+ """
+ from bs4 import BeautifulSoup
+
+ soup = BeautifulSoup(html_content, "html.parser")
+ text_parts: List[str] = []
+ for element in soup.find_all():
+ if element.name in tags:
+ # Extract all navigable strings recursively from this element.
+ text_parts += get_navigable_strings(
+ element, remove_comments=remove_comments
+ )
+
+ # To avoid duplicate text, remove all descendants from the soup.
+ element.decompose()
+
+ return " ".join(text_parts)
+
+ @staticmethod
+ def remove_unnecessary_lines(content: str) -> str:
+ """
+ Clean up the content by removing unnecessary lines.
+
+ Args:
+ content: A string, which may contain unnecessary lines or spaces.
+
+ Returns:
+ A cleaned string with unnecessary lines removed.
+ """
+ lines = content.split("\n")
+ stripped_lines = [line.strip() for line in lines]
+ non_empty_lines = [line for line in stripped_lines if line]
+ cleaned_content = " ".join(non_empty_lines)
+ return cleaned_content
+
+ async def atransform_documents(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+
+
+def get_navigable_strings(
+ element: Any, *, remove_comments: bool = False
+) -> Iterator[str]:
+ """Get all navigable strings from a BeautifulSoup element.
+
+ Args:
+ element: A BeautifulSoup element.
+ remove_comments: If set to True, the comments will be removed.
+
+ Returns:
+ A generator of strings.
+ """
+
+ from bs4 import Comment, NavigableString, Tag
+
+ for child in cast(Tag, element).children:
+ if isinstance(child, Comment) and remove_comments:
+ continue
+ if isinstance(child, Tag):
+ yield from get_navigable_strings(child, remove_comments=remove_comments)
+ elif isinstance(child, NavigableString):
+ if (element.name == "a") and (href := element.get("href")):
+ yield f"{child.strip()} ({href})"
+ else:
+ yield child.strip()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_extract.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..e942eafdde85d47d2217128eb4a86ba527062db5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_extract.py
@@ -0,0 +1,114 @@
+from typing import Any, List, Optional, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+from langchain_core.utils import get_from_env
+
+
+class DoctranPropertyExtractor(BaseDocumentTransformer):
+ """Extract properties from text documents using doctran.
+
+ Arguments:
+ properties: A list of the properties to extract.
+ openai_api_key: OpenAI API key. Can also be specified via environment variable
+ ``OPENAI_API_KEY``.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_transformers import DoctranPropertyExtractor
+
+ properties = [
+ {
+ "name": "category",
+ "description": "What type of email this is.",
+ "type": "string",
+ "enum": ["update", "action_item", "customer_feedback", "announcement", "other"],
+ "required": True,
+ },
+ {
+ "name": "mentions",
+ "description": "A list of all people mentioned in this email.",
+ "type": "array",
+ "items": {
+ "name": "full_name",
+ "description": "The full name of the person mentioned.",
+ "type": "string",
+ },
+ "required": True,
+ },
+ {
+ "name": "eli5",
+ "description": "Explain this email to me like I'm 5 years old.",
+ "type": "string",
+ "required": True,
+ },
+ ]
+
+ # Pass in openai_api_key or set env var OPENAI_API_KEY
+ property_extractor = DoctranPropertyExtractor(properties)
+ transformed_document = await qa_transformer.atransform_documents(documents)
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ properties: List[dict],
+ openai_api_key: Optional[str] = None,
+ openai_api_model: Optional[str] = None,
+ ) -> None:
+ self.properties = properties
+ self.openai_api_key = openai_api_key or get_from_env(
+ "openai_api_key", "OPENAI_API_KEY"
+ )
+ self.openai_api_model = openai_api_model or get_from_env(
+ "openai_api_model", "OPENAI_API_MODEL"
+ )
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Extracts properties from text documents using doctran."""
+ try:
+ from doctran import Doctran, ExtractProperty
+
+ doctran = Doctran(
+ openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
+ )
+ except ImportError:
+ raise ImportError(
+ "Install doctran to use this parser. (pip install doctran)"
+ )
+ properties = [ExtractProperty(**property) for property in self.properties]
+ for d in documents:
+ doctran_doc = (
+ doctran.parse(content=d.page_content)
+ .extract(properties=properties)
+ .execute()
+ )
+
+ d.metadata["extracted_properties"] = doctran_doc.extracted_properties
+ return documents
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Extracts properties from text documents using doctran."""
+ try:
+ from doctran import Doctran, ExtractProperty
+
+ doctran = Doctran(
+ openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
+ )
+ except ImportError:
+ raise ImportError(
+ "Install doctran to use this parser. (pip install doctran)"
+ )
+ properties = [ExtractProperty(**property) for property in self.properties]
+ for d in documents:
+ doctran_doc = (
+ doctran.parse(content=d.page_content)
+ .extract(properties=properties)
+ .execute()
+ )
+
+ d.metadata["extracted_properties"] = doctran_doc.extracted_properties
+ return documents
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_qa.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_qa.py
new file mode 100644
index 0000000000000000000000000000000000000000..53f0c001671fc8a8dece9914a84e9c6a0b9717df
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_qa.py
@@ -0,0 +1,61 @@
+from typing import Any, Optional, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+from langchain_core.utils import get_from_env
+
+
+class DoctranQATransformer(BaseDocumentTransformer):
+ """Extract QA from text documents using doctran.
+
+ Arguments:
+ openai_api_key: OpenAI API key. Can also be specified via environment variable
+ ``OPENAI_API_KEY``.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_transformers import DoctranQATransformer
+
+ # Pass in openai_api_key or set env var OPENAI_API_KEY
+ qa_transformer = DoctranQATransformer()
+ transformed_document = await qa_transformer.atransform_documents(documents)
+ """
+
+ def __init__(
+ self,
+ openai_api_key: Optional[str] = None,
+ openai_api_model: Optional[str] = None,
+ ) -> None:
+ self.openai_api_key = openai_api_key or get_from_env(
+ "openai_api_key", "OPENAI_API_KEY"
+ )
+ self.openai_api_model = openai_api_model or get_from_env(
+ "openai_api_model", "OPENAI_API_MODEL"
+ )
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Extracts QA from text documents using doctran."""
+ try:
+ from doctran import Doctran
+
+ doctran = Doctran(
+ openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
+ )
+ except ImportError:
+ raise ImportError(
+ "Install doctran to use this parser. (pip install doctran)"
+ )
+ for d in documents:
+ doctran_doc = doctran.parse(content=d.page_content).interrogate().execute()
+ questions_and_answers = doctran_doc.extracted_properties.get(
+ "questions_and_answers"
+ )
+ d.metadata["questions_and_answers"] = questions_and_answers
+ return documents
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_translate.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_translate.py
new file mode 100644
index 0000000000000000000000000000000000000000..137edcec283494a609c08aadc43679481ea8a800
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/doctran_text_translate.py
@@ -0,0 +1,119 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Optional, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+from langchain_core.runnables.config import run_in_executor
+from langchain_core.utils import get_from_env
+
+
+class DoctranTextTranslator(BaseDocumentTransformer):
+ """Translate text documents using doctran.
+
+ Arguments:
+ openai_api_key: OpenAI API key. Can also be specified via environment variable
+ ``OPENAI_API_KEY``.
+ language: The language to translate *to*.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_transformers import DoctranTextTranslator
+
+ # Pass in openai_api_key or set env var OPENAI_API_KEY
+ qa_translator = DoctranTextTranslator(language="spanish")
+ translated_document = await qa_translator.atransform_documents(documents)
+ """
+
+ def __init__(
+ self,
+ openai_api_key: Optional[str] = None,
+ language: str = "english",
+ openai_api_model: Optional[str] = None,
+ ) -> None:
+ self.openai_api_key = openai_api_key or get_from_env(
+ "openai_api_key", "OPENAI_API_KEY"
+ )
+ self.openai_api_model = openai_api_model or get_from_env(
+ "openai_api_model", "OPENAI_API_MODEL"
+ )
+ self.language = language
+
+ async def _aparse_document(
+ self, doctran: Any, index: int, doc: Document
+ ) -> tuple[int, Any]:
+ parsed_doc = await run_in_executor(
+ None, doctran.parse, content=doc.page_content, metadata=doc.metadata
+ )
+ return index, parsed_doc
+
+ async def _atranslate_document(
+ self, index: int, doc: Any, language: str
+ ) -> tuple[int, Any]:
+ translated_doc = await run_in_executor(
+ None, lambda: doc.translate(language=language).execute()
+ )
+ return index, translated_doc
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Translates text documents using doctran."""
+ try:
+ from doctran import Doctran
+
+ doctran = Doctran(
+ openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
+ )
+ except ImportError:
+ raise ImportError(
+ "Install doctran to use this parser. (pip install doctran)"
+ )
+
+ parse_tasks = [
+ self._aparse_document(doctran, i, doc) for i, doc in enumerate(documents)
+ ]
+ parsed_results = await asyncio.gather(*parse_tasks)
+
+ parsed_results.sort(key=lambda x: x[0])
+ doctran_docs = [doc for _, doc in parsed_results]
+
+ translate_tasks = [
+ self._atranslate_document(i, doc, self.language)
+ for i, doc in enumerate(doctran_docs)
+ ]
+ translated_results = await asyncio.gather(*translate_tasks)
+
+ translated_results.sort(key=lambda x: x[0])
+ translated_docs = [doc for _, doc in translated_results]
+
+ return [
+ Document(page_content=doc.transformed_content, metadata=doc.metadata)
+ for doc in translated_docs
+ ]
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Translates text documents using doctran."""
+ try:
+ from doctran import Doctran
+
+ doctran = Doctran(
+ openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
+ )
+ except ImportError:
+ raise ImportError(
+ "Install doctran to use this parser. (pip install doctran)"
+ )
+ doctran_docs = [
+ doctran.parse(content=doc.page_content, metadata=doc.metadata)
+ for doc in documents
+ ]
+ for i, doc in enumerate(doctran_docs):
+ doctran_docs[i] = doc.translate(language=self.language).execute()
+ return [
+ Document(page_content=doc.transformed_content, metadata=doc.metadata)
+ for doc in doctran_docs
+ ]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..f46c55ae3656db65f6117882520e2fd215255bd8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py
@@ -0,0 +1,225 @@
+"""Transform documents"""
+
+from typing import Any, Callable, List, Sequence
+
+import numpy as np
+from langchain_core.documents import BaseDocumentTransformer, Document
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field
+
+from langchain_community.utils.math import cosine_similarity
+
+
+class _DocumentWithState(Document):
+ """Wrapper for a document that includes arbitrary state."""
+
+ state: dict = Field(default_factory=dict)
+ """State associated with the document."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return False
+
+ def to_document(self) -> Document:
+ """Convert the DocumentWithState to a Document."""
+ return Document(page_content=self.page_content, metadata=self.metadata)
+
+ @classmethod
+ def from_document(cls, doc: Document) -> "_DocumentWithState":
+ """Create a DocumentWithState from a Document."""
+ if isinstance(doc, cls):
+ return doc
+ return cls(page_content=doc.page_content, metadata=doc.metadata)
+
+
+def get_stateful_documents(
+ documents: Sequence[Document],
+) -> Sequence[_DocumentWithState]:
+ """Convert a list of documents to a list of documents with state.
+
+ Args:
+ documents: The documents to convert.
+
+ Returns:
+ A list of documents with state.
+ """
+ return [_DocumentWithState.from_document(doc) for doc in documents]
+
+
+def _filter_similar_embeddings(
+ embedded_documents: List[List[float]], similarity_fn: Callable, threshold: float
+) -> List[int]:
+ """Filter redundant documents based on the similarity of their embeddings."""
+ similarity = np.tril(similarity_fn(embedded_documents, embedded_documents), k=-1)
+ redundant = np.where(similarity > threshold)
+ redundant_stacked = np.column_stack(redundant)
+ redundant_sorted = np.argsort(similarity[redundant])[::-1]
+ included_idxs = set(range(len(embedded_documents)))
+ for first_idx, second_idx in redundant_stacked[redundant_sorted]:
+ if first_idx in included_idxs and second_idx in included_idxs:
+ # Default to dropping the second document of any highly similar pair.
+ included_idxs.remove(second_idx)
+ return list(sorted(included_idxs))
+
+
+def _get_embeddings_from_stateful_docs(
+ embeddings: Embeddings, documents: Sequence[_DocumentWithState]
+) -> List[List[float]]:
+ if len(documents) and "embedded_doc" in documents[0].state:
+ embedded_documents = [doc.state["embedded_doc"] for doc in documents]
+ else:
+ embedded_documents = embeddings.embed_documents(
+ [d.page_content for d in documents]
+ )
+ for doc, embedding in zip(documents, embedded_documents):
+ doc.state["embedded_doc"] = embedding
+ return embedded_documents
+
+
+async def _aget_embeddings_from_stateful_docs(
+ embeddings: Embeddings, documents: Sequence[_DocumentWithState]
+) -> List[List[float]]:
+ if len(documents) and "embedded_doc" in documents[0].state:
+ embedded_documents = [doc.state["embedded_doc"] for doc in documents]
+ else:
+ embedded_documents = await embeddings.aembed_documents(
+ [d.page_content for d in documents]
+ )
+ for doc, embedding in zip(documents, embedded_documents):
+ doc.state["embedded_doc"] = embedding
+ return embedded_documents
+
+
+def _filter_cluster_embeddings(
+ embedded_documents: List[List[float]],
+ num_clusters: int,
+ num_closest: int,
+ random_state: int,
+ remove_duplicates: bool,
+) -> List[int]:
+ """Filter documents based on proximity of their embeddings to clusters."""
+
+ try:
+ from sklearn.cluster import KMeans
+ except ImportError:
+ raise ImportError(
+ "sklearn package not found, please install it with "
+ "`pip install scikit-learn`"
+ )
+
+ kmeans = KMeans(n_clusters=num_clusters, random_state=random_state).fit(
+ embedded_documents
+ )
+ closest_indices = []
+
+ # Loop through the number of clusters you have
+ for i in range(num_clusters):
+ # Get the list of distances from that particular cluster center
+ distances = np.linalg.norm(
+ embedded_documents - kmeans.cluster_centers_[i], axis=1
+ )
+
+ # Find the indices of the two unique closest ones
+ # (using argsort to find the smallest 2 distances)
+ if remove_duplicates:
+ # Only add not duplicated vectors.
+ closest_indices_sorted = [
+ x
+ for x in np.argsort(distances)[:num_closest]
+ if x not in closest_indices
+ ]
+ else:
+ # Skip duplicates and add the next closest vector.
+ closest_indices_sorted = [
+ x for x in np.argsort(distances) if x not in closest_indices
+ ][:num_closest]
+
+ # Append that position closest indices list
+ closest_indices.extend(closest_indices_sorted)
+
+ return closest_indices
+
+
+class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):
+ """Filter that drops redundant documents by comparing their embeddings."""
+
+ embeddings: Embeddings
+ """Embeddings to use for embedding document contents."""
+ similarity_fn: Callable = cosine_similarity
+ """Similarity function for comparing documents. Function expected to take as input
+ two matrices (List[List[float]]) and return a matrix of scores where higher values
+ indicate greater similarity."""
+ similarity_threshold: float = 0.95
+ """Threshold for determining when two documents are similar enough
+ to be considered redundant."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Filter down documents."""
+ stateful_documents = get_stateful_documents(documents)
+ embedded_documents = _get_embeddings_from_stateful_docs(
+ self.embeddings, stateful_documents
+ )
+ included_idxs = _filter_similar_embeddings(
+ embedded_documents, self.similarity_fn, self.similarity_threshold
+ )
+ return [stateful_documents[i] for i in sorted(included_idxs)]
+
+
+class EmbeddingsClusteringFilter(BaseDocumentTransformer, BaseModel):
+ """Perform K-means clustering on document vectors.
+ Returns an arbitrary number of documents closest to center."""
+
+ embeddings: Embeddings
+ """Embeddings to use for embedding document contents."""
+
+ num_clusters: int = 5
+ """Number of clusters. Groups of documents with similar meaning."""
+
+ num_closest: int = 1
+ """The number of closest vectors to return for each cluster center."""
+
+ random_state: int = 42
+ """Controls the random number generator used to initialize the cluster centroids.
+ If you set the random_state parameter to None, the KMeans algorithm will use a
+ random number generator that is seeded with the current time. This means
+ that the results of the KMeans algorithm will be different each time you
+ run it."""
+
+ sorted: bool = False
+ """By default results are re-ordered "grouping" them by cluster, if sorted is true
+ result will be ordered by the original position from the retriever"""
+
+ remove_duplicates: bool = False
+ """ By default duplicated results are skipped and replaced by the next closest
+ vector in the cluster. If remove_duplicates is true no replacement will be done:
+ This could dramatically reduce results when there is a lot of overlap between
+ clusters.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Filter down documents."""
+ stateful_documents = get_stateful_documents(documents)
+ embedded_documents = _get_embeddings_from_stateful_docs(
+ self.embeddings, stateful_documents
+ )
+ included_idxs = _filter_cluster_embeddings(
+ embedded_documents,
+ self.num_clusters,
+ self.num_closest,
+ self.random_state,
+ self.remove_duplicates,
+ )
+ results = sorted(included_idxs) if self.sorted else included_idxs
+ return [stateful_documents[i] for i in results]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/google_translate.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/google_translate.py
new file mode 100644
index 0000000000000000000000000000000000000000..613ab0bdfc1ff34086a027fa6cd1ab25c6c7fc97
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/google_translate.py
@@ -0,0 +1,113 @@
+from typing import Any, Optional, Sequence
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import BaseDocumentTransformer, Document
+
+from langchain_community.utilities.vertexai import get_client_info
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.DocAIParser",
+)
+class GoogleTranslateTransformer(BaseDocumentTransformer):
+ """Translate text documents using Google Cloud Translation."""
+
+ def __init__(
+ self,
+ project_id: str,
+ *,
+ location: str = "global",
+ model_id: Optional[str] = None,
+ glossary_id: Optional[str] = None,
+ api_endpoint: Optional[str] = None,
+ ) -> None:
+ """
+ Arguments:
+ project_id: Google Cloud Project ID.
+ location: (Optional) Translate model location.
+ model_id: (Optional) Translate model ID to use.
+ glossary_id: (Optional) Translate glossary ID to use.
+ api_endpoint: (Optional) Regional endpoint to use.
+ """
+ try:
+ from google.api_core.client_options import ClientOptions
+ from google.cloud import translate
+ except ImportError as exc:
+ raise ImportError(
+ "Install Google Cloud Translate to use this parser."
+ "(pip install google-cloud-translate)"
+ ) from exc
+
+ self.project_id = project_id
+ self.location = location
+ self.model_id = model_id
+ self.glossary_id = glossary_id
+
+ self._client = translate.TranslationServiceClient(
+ client_info=get_client_info("translate"),
+ client_options=(
+ ClientOptions(api_endpoint=api_endpoint) if api_endpoint else None
+ ),
+ )
+ self._parent_path = self._client.common_location_path(project_id, location)
+ # For some reason, there's no `model_path()` method for the client.
+ self._model_path = (
+ f"{self._parent_path}/models/{model_id}" if model_id else None
+ )
+ self._glossary_path = (
+ self._client.glossary_path(project_id, location, glossary_id)
+ if glossary_id
+ else None
+ )
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Translate text documents using Google Translate.
+
+ Arguments:
+ source_language_code: ISO 639 language code of the input document.
+ target_language_code: ISO 639 language code of the output document.
+ For supported languages, refer to:
+ https://cloud.google.com/translate/docs/languages
+ mime_type: (Optional) Media Type of input text.
+ Options: `text/plain`, `text/html`
+ """
+ try:
+ from google.cloud import translate
+ except ImportError as exc:
+ raise ImportError(
+ "Install Google Cloud Translate to use this parser."
+ "(pip install google-cloud-translate)"
+ ) from exc
+
+ response = self._client.translate_text(
+ request=translate.TranslateTextRequest(
+ contents=[doc.page_content for doc in documents],
+ parent=self._parent_path,
+ model=self._model_path,
+ glossary_config=translate.TranslateTextGlossaryConfig(
+ glossary=self._glossary_path
+ ),
+ source_language_code=kwargs.get("source_language_code", None),
+ target_language_code=kwargs.get("target_language_code"),
+ mime_type=kwargs.get("mime_type", "text/plain"),
+ )
+ )
+
+ # If using a glossary, the translations will be in `glossary_translations`.
+ translations = response.glossary_translations or response.translations
+
+ return [
+ Document(
+ page_content=translation.translated_text,
+ metadata={
+ **doc.metadata,
+ "model": translation.model,
+ "detected_language_code": translation.detected_language_code,
+ },
+ )
+ for doc, translation in zip(documents, translations)
+ ]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/html2text.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/html2text.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbf7cf366e4358e988926278a9b31e780c4cf3f2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/html2text.py
@@ -0,0 +1,56 @@
+from typing import Any, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+
+
+class Html2TextTransformer(BaseDocumentTransformer):
+ """Replace occurrences of a particular search pattern with a replacement string
+
+ Arguments:
+ ignore_links: Whether links should be ignored; defaults to True.
+ ignore_images: Whether images should be ignored; defaults to True.
+
+ Example:
+ .. code-block:: python
+ from langchain_community.document_transformers import Html2TextTransformer
+ html2text = Html2TextTransformer()
+ docs_transform = html2text.transform_documents(docs)
+ """
+
+ def __init__(self, ignore_links: bool = True, ignore_images: bool = True) -> None:
+ self.ignore_links = ignore_links
+ self.ignore_images = ignore_images
+
+ def transform_documents(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> Sequence[Document]:
+ try:
+ import html2text
+ except ImportError:
+ raise ImportError(
+ """html2text package not found, please
+ install it with `pip install html2text`"""
+ )
+
+ # Create a html2text.HTML2Text object and override some properties
+ h = html2text.HTML2Text()
+ h.ignore_links = self.ignore_links
+ h.ignore_images = self.ignore_images
+
+ new_documents = []
+
+ for d in documents:
+ new_document = Document(
+ page_content=h.handle(d.page_content), metadata={**d.metadata}
+ )
+ new_documents.append(new_document)
+ return new_documents
+
+ async def atransform_documents(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> Sequence[Document]:
+ raise NotImplementedError
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/long_context_reorder.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/long_context_reorder.py
new file mode 100644
index 0000000000000000000000000000000000000000..2884b63f098cb2f6a45f7dc55bcc024cd030572b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/long_context_reorder.py
@@ -0,0 +1,45 @@
+"""Reorder documents"""
+
+from typing import Any, List, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+from pydantic import BaseModel, ConfigDict
+
+
+def _litm_reordering(documents: List[Document]) -> List[Document]:
+ """Lost in the middle reorder: the less relevant documents will be at the
+ middle of the list and more relevant elements at beginning / end.
+ See: https://arxiv.org/abs//2307.03172"""
+
+ documents.reverse()
+ reordered_result = []
+ for i, value in enumerate(documents):
+ if i % 2 == 1:
+ reordered_result.append(value)
+ else:
+ reordered_result.insert(0, value)
+ return reordered_result
+
+
+class LongContextReorder(BaseDocumentTransformer, BaseModel):
+ """Reorder long context.
+
+ Lost in the middle:
+ Performance degrades when models must access relevant information
+ in the middle of long contexts.
+ See: https://arxiv.org/abs//2307.03172"""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Reorders documents."""
+ return _litm_reordering(list(documents))
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ return _litm_reordering(list(documents))
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/markdownify.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/markdownify.py
new file mode 100644
index 0000000000000000000000000000000000000000..91c580e591de54f17947377aeccf23d21489c537
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/markdownify.py
@@ -0,0 +1,76 @@
+import re
+from typing import Any, List, Optional, Sequence, Union
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+
+
+class MarkdownifyTransformer(BaseDocumentTransformer):
+ """Converts HTML documents to Markdown format with customizable options for handling
+ links, images, other tags and heading styles using the markdownify library.
+
+ Arguments:
+ strip: A list of tags to strip. This option can't be used with the convert option.
+ convert: A list of tags to convert. This option can't be used with the strip option.
+ autolinks: A boolean indicating whether the "automatic link" style should be used when a a tag's contents match its href. Defaults to True.
+ heading_style: Defines how headings should be converted. Accepted values are ATX, ATX_CLOSED, SETEXT, and UNDERLINED (which is an alias for SETEXT). Defaults to ATX.
+ kwargs: Additional options to pass to markdownify.
+
+ Example:
+ .. code-block:: python
+ from langchain_community.document_transformers import MarkdownifyTransformer
+ markdownify = MarkdownifyTransformer()
+ docs_transform = markdownify.transform_documents(docs)
+
+ More configuration options can be found at the markdownify GitHub page:
+ https://github.com/matthewwithanm/python-markdownify
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ strip: Optional[Union[str, List[str]]] = None,
+ convert: Optional[Union[str, List[str]]] = None,
+ autolinks: bool = True,
+ heading_style: str = "ATX",
+ **kwargs: Any,
+ ) -> None:
+ self.strip = [strip] if isinstance(strip, str) else strip
+ self.convert = [convert] if isinstance(convert, str) else convert
+ self.autolinks = autolinks
+ self.heading_style = heading_style
+ self.additional_options = kwargs
+
+ def transform_documents(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> Sequence[Document]:
+ try:
+ from markdownify import markdownify
+ except ImportError:
+ raise ImportError(
+ """markdownify package not found, please
+ install it with `pip install markdownify`"""
+ )
+
+ converted_documents = []
+ for doc in documents:
+ markdown_content = (
+ markdownify(
+ html=doc.page_content,
+ strip=self.strip,
+ convert=self.convert,
+ autolinks=self.autolinks,
+ heading_style=self.heading_style,
+ **self.additional_options,
+ )
+ .replace("\xa0", " ")
+ .strip()
+ )
+
+ cleaned_markdown = re.sub(r"\n\s*\n", "\n\n", markdown_content)
+
+ converted_documents.append(
+ Document(cleaned_markdown, metadata=doc.metadata)
+ )
+
+ return converted_documents
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/nuclia_text_transform.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/nuclia_text_transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..47ef5709f6cd422b44fb75c03d37a1e9d87f5261
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/nuclia_text_transform.py
@@ -0,0 +1,49 @@
+import asyncio
+import json
+import uuid
+from typing import Any, Sequence
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+
+from langchain_community.tools.nuclia.tool import NucliaUnderstandingAPI
+
+
+class NucliaTextTransformer(BaseDocumentTransformer):
+ """Nuclia Text Transformer.
+
+ The Nuclia Understanding API splits into paragraphs and sentences,
+ identifies entities, provides a summary of the text and generates
+ embeddings for all sentences.
+ """
+
+ def __init__(self, nua: NucliaUnderstandingAPI):
+ self.nua = nua
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ tasks = [
+ self.nua.arun(
+ {
+ "action": "push",
+ "id": str(uuid.uuid4()),
+ "text": doc.page_content,
+ "path": None,
+ }
+ )
+ for doc in documents
+ ]
+ results = await asyncio.gather(*tasks)
+ for doc, result in zip(documents, results):
+ obj = json.loads(result)
+ metadata = {
+ "file": obj["file_extracted_data"][0],
+ "metadata": obj["field_metadata"][0],
+ }
+ doc.metadata["nuclia"] = metadata
+ return documents
diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/openai_functions.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/openai_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..88b57f20ea0b27014c0548a38ce5b16a659141cb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/openai_functions.py
@@ -0,0 +1,142 @@
+"""Document transformers that use OpenAI Functions models"""
+
+from typing import Any, Dict, Optional, Sequence, Type, Union
+
+from langchain_core.documents import BaseDocumentTransformer, Document
+from langchain_core.language_models import BaseLanguageModel
+from langchain_core.prompts import ChatPromptTemplate
+from pydantic import BaseModel
+
+
+class OpenAIMetadataTagger(BaseDocumentTransformer, BaseModel):
+ """Extract metadata tags from document contents using OpenAI functions.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOpenAI
+ from langchain_community.document_transformers import OpenAIMetadataTagger
+ from langchain_core.documents import Document
+
+ schema = {
+ "properties": {
+ "movie_title": { "type": "string" },
+ "critic": { "type": "string" },
+ "tone": {
+ "type": "string",
+ "enum": ["positive", "negative"]
+ },
+ "rating": {
+ "type": "integer",
+ "description": "The number of stars the critic rated the movie"
+ }
+ },
+ "required": ["movie_title", "critic", "tone"]
+ }
+
+ # Must be an OpenAI model that supports functions
+ llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
+ tagging_chain = create_tagging_chain(schema, llm)
+ document_transformer = OpenAIMetadataTagger(tagging_chain=tagging_chain)
+ original_documents = [
+ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."),
+ Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable": False}),
+ ]
+
+ enhanced_documents = document_transformer.transform_documents(original_documents)
+ """ # noqa: E501
+
+ tagging_chain: Any
+ """The chain used to extract metadata from each document."""
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Automatically extract and populate metadata
+ for each document according to the provided schema."""
+
+ new_documents = []
+
+ for document in documents:
+ extracted_metadata: Dict = self.tagging_chain.run(document.page_content)
+ new_document = Document(
+ page_content=document.page_content,
+ metadata={**extracted_metadata, **document.metadata},
+ )
+ new_documents.append(new_document)
+ return new_documents
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+
+
+def create_metadata_tagger(
+ metadata_schema: Union[Dict[str, Any], Type[BaseModel]],
+ llm: BaseLanguageModel,
+ prompt: Optional[ChatPromptTemplate] = None,
+ *,
+ tagging_chain_kwargs: Optional[Dict] = None,
+) -> OpenAIMetadataTagger:
+ """Create a DocumentTransformer that uses an OpenAI function chain to automatically
+ tag documents with metadata based on their content and an input schema.
+
+ Args:
+ metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
+ is passed in, it's assumed to already be a valid JsonSchema.
+ For best results, pydantic.BaseModels should have docstrings describing what
+ the schema represents and descriptions for the parameters.
+ llm: Language model to use, assumed to support the OpenAI function-calling API.
+ Defaults to use "gpt-3.5-turbo-0613"
+ prompt: BasePromptTemplate to pass to the model.
+
+ Returns:
+ An LLMChain that will pass the given function to the model.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOpenAI
+ from langchain_community.document_transformers import create_metadata_tagger
+ from langchain_core.documents import Document
+
+ schema = {
+ "properties": {
+ "movie_title": { "type": "string" },
+ "critic": { "type": "string" },
+ "tone": {
+ "type": "string",
+ "enum": ["positive", "negative"]
+ },
+ "rating": {
+ "type": "integer",
+ "description": "The number of stars the critic rated the movie"
+ }
+ },
+ "required": ["movie_title", "critic", "tone"]
+ }
+
+ # Must be an OpenAI model that supports functions
+ llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
+
+ document_transformer = create_metadata_tagger(schema, llm)
+ original_documents = [
+ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."),
+ Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable": False}),
+ ]
+
+ enhanced_documents = document_transformer.transform_documents(original_documents)
+ """ # noqa: E501
+ from langchain_classic.chains.openai_functions import create_tagging_chain
+
+ metadata_schema = (
+ metadata_schema
+ if isinstance(metadata_schema, dict)
+ else metadata_schema.schema()
+ )
+ _tagging_chain_kwargs = tagging_chain_kwargs or {}
+ tagging_chain = create_tagging_chain(
+ metadata_schema, llm, prompt=prompt, **_tagging_chain_kwargs
+ )
+ return OpenAIMetadataTagger(tagging_chain=tagging_chain)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/aleph_alpha.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/aleph_alpha.py
new file mode 100644
index 0000000000000000000000000000000000000000..96426fdac8a9189d855529a679e994eeb27f2ade
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/aleph_alpha.py
@@ -0,0 +1,256 @@
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, model_validator
+
+
+class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):
+ """Aleph Alpha's asymmetric semantic embedding.
+
+ AA provides you with an endpoint to embed a document and a query.
+ The models were optimized to make the embeddings of documents and
+ the query for a document as similar as possible.
+ To learn more, check out: https://docs.aleph-alpha.com/docs/tasks/semantic_embed/
+
+ Example:
+ .. code-block:: python
+ from aleph_alpha import AlephAlphaAsymmetricSemanticEmbedding
+
+ embeddings = AlephAlphaAsymmetricSemanticEmbedding(
+ normalize=True, compress_to_size=128
+ )
+
+ document = "This is a content of the document"
+ query = "What is the content of the document?"
+
+ doc_result = embeddings.embed_documents([document])
+ query_result = embeddings.embed_query(query)
+
+ """
+
+ client: Any #: :meta private:
+
+ # Embedding params
+ model: str = "luminous-base"
+ """Model name to use."""
+ compress_to_size: Optional[int] = None
+ """Should the returned embeddings come back as an original 5120-dim vector,
+ or should it be compressed to 128-dim."""
+ normalize: bool = False
+ """Should returned embeddings be normalized"""
+ contextual_control_threshold: Optional[int] = None
+ """Attention control parameters only apply to those tokens that have
+ explicitly been set in the request."""
+ control_log_additive: bool = True
+ """Apply controls on prompt items by adding the log(control_factor)
+ to attention scores."""
+
+ # Client params
+ aleph_alpha_api_key: Optional[str] = None
+ """API key for Aleph Alpha API."""
+ host: str = "https://api.aleph-alpha.com"
+ """The hostname of the API host.
+ The default one is "https://api.aleph-alpha.com")"""
+ hosting: Optional[str] = None
+ """Determines in which datacenters the request may be processed.
+ You can either set the parameter to "aleph-alpha" or omit it (defaulting to None).
+ Not setting this value, or setting it to None, gives us maximal flexibility
+ in processing your request in our
+ own datacenters and on servers hosted with other providers.
+ Choose this option for maximal availability.
+ Setting it to "aleph-alpha" allows us to only process the request
+ in our own datacenters.
+ Choose this option for maximal data privacy."""
+ request_timeout_seconds: int = 305
+ """Client timeout that will be set for HTTP requests in the
+ `requests` library's API calls.
+ Server will close all requests after 300 seconds with an internal server error."""
+ total_retries: int = 8
+ """The number of retries made in case requests fail with certain retryable
+ status codes. If the last
+ retry fails a corresponding exception is raised. Note, that between retries
+ an exponential backoff
+ is applied, starting with 0.5 s after the first retry and doubling for each
+ retry made. So with the
+ default setting of 8 retries a total wait time of 63.5 s is added between
+ the retries."""
+ nice: bool = False
+ """Setting this to True, will signal to the API that you intend to be
+ nice to other users
+ by de-prioritizing your request below concurrent ones."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ aleph_alpha_api_key = get_from_dict_or_env(
+ values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY"
+ )
+ try:
+ from aleph_alpha_client import Client
+
+ values["client"] = Client(
+ token=aleph_alpha_api_key,
+ host=values["host"],
+ hosting=values["hosting"],
+ request_timeout_seconds=values["request_timeout_seconds"],
+ total_retries=values["total_retries"],
+ nice=values["nice"],
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import aleph_alpha_client python package. "
+ "Please install it with `pip install aleph_alpha_client`."
+ )
+
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to Aleph Alpha's asymmetric Document endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ try:
+ from aleph_alpha_client import (
+ Prompt,
+ SemanticEmbeddingRequest,
+ SemanticRepresentation,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import aleph_alpha_client python package. "
+ "Please install it with `pip install aleph_alpha_client`."
+ )
+ document_embeddings = []
+
+ for text in texts:
+ document_params = {
+ "prompt": Prompt.from_text(text),
+ "representation": SemanticRepresentation.Document,
+ "compress_to_size": self.compress_to_size,
+ "normalize": self.normalize,
+ "contextual_control_threshold": self.contextual_control_threshold,
+ "control_log_additive": self.control_log_additive,
+ }
+
+ document_request = SemanticEmbeddingRequest(**document_params)
+ document_response = self.client.semantic_embed(
+ request=document_request, model=self.model
+ )
+
+ document_embeddings.append(document_response.embedding)
+
+ return document_embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Aleph Alpha's asymmetric, query embedding endpoint
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ try:
+ from aleph_alpha_client import (
+ Prompt,
+ SemanticEmbeddingRequest,
+ SemanticRepresentation,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import aleph_alpha_client python package. "
+ "Please install it with `pip install aleph_alpha_client`."
+ )
+ symmetric_params = {
+ "prompt": Prompt.from_text(text),
+ "representation": SemanticRepresentation.Query,
+ "compress_to_size": self.compress_to_size,
+ "normalize": self.normalize,
+ "contextual_control_threshold": self.contextual_control_threshold,
+ "control_log_additive": self.control_log_additive,
+ }
+
+ symmetric_request = SemanticEmbeddingRequest(**symmetric_params)
+ symmetric_response = self.client.semantic_embed(
+ request=symmetric_request, model=self.model
+ )
+
+ return symmetric_response.embedding
+
+
+class AlephAlphaSymmetricSemanticEmbedding(AlephAlphaAsymmetricSemanticEmbedding):
+ """Symmetric version of the Aleph Alpha's semantic embeddings.
+
+ The main difference is that here, both the documents and
+ queries are embedded with a SemanticRepresentation.Symmetric
+ Example:
+ .. code-block:: python
+
+ from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding
+
+ embeddings = AlephAlphaAsymmetricSemanticEmbedding(
+ normalize=True, compress_to_size=128
+ )
+ text = "This is a test text"
+
+ doc_result = embeddings.embed_documents([text])
+ query_result = embeddings.embed_query(text)
+ """
+
+ def _embed(self, text: str) -> List[float]:
+ try:
+ from aleph_alpha_client import (
+ Prompt,
+ SemanticEmbeddingRequest,
+ SemanticRepresentation,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import aleph_alpha_client python package. "
+ "Please install it with `pip install aleph_alpha_client`."
+ )
+ query_params = {
+ "prompt": Prompt.from_text(text),
+ "representation": SemanticRepresentation.Symmetric,
+ "compress_to_size": self.compress_to_size,
+ "normalize": self.normalize,
+ "contextual_control_threshold": self.contextual_control_threshold,
+ "control_log_additive": self.control_log_additive,
+ }
+
+ query_request = SemanticEmbeddingRequest(**query_params)
+ query_response = self.client.semantic_embed(
+ request=query_request, model=self.model
+ )
+
+ return query_response.embedding
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to Aleph Alpha's Document endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ document_embeddings = []
+
+ for text in texts:
+ document_embeddings.append(self._embed(text))
+ return document_embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Aleph Alpha's asymmetric, query embedding endpoint
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self._embed(text)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/anyscale.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/anyscale.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffa33fa497d5ca86dc6f5321bb41d15210620e72
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/anyscale.py
@@ -0,0 +1,76 @@
+"""Anyscale embeddings wrapper."""
+
+from __future__ import annotations
+
+from typing import Dict, Optional
+
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import Field, SecretStr
+
+from langchain_community.embeddings.openai import OpenAIEmbeddings
+from langchain_community.utils.openai import is_openai_v1
+
+DEFAULT_API_BASE = "https://api.endpoints.anyscale.com/v1"
+DEFAULT_MODEL = "thenlper/gte-large"
+
+
+class AnyscaleEmbeddings(OpenAIEmbeddings):
+ """`Anyscale` Embeddings API."""
+
+ anyscale_api_key: Optional[SecretStr] = Field(default=None)
+ """AnyScale Endpoints API keys."""
+ model: str = Field(default=DEFAULT_MODEL)
+ """Model name to use."""
+ anyscale_api_base: str = Field(default=DEFAULT_API_BASE)
+ """Base URL path for API requests."""
+ tiktoken_enabled: bool = False
+ """Set this to False for non-OpenAI implementations of the embeddings API"""
+ embedding_ctx_length: int = 500
+ """The maximum number of tokens to embed at once."""
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "anyscale_api_key": "ANYSCALE_API_KEY",
+ }
+
+ @pre_init
+ def validate_environment(cls, values: dict) -> dict:
+ """Validate that api key and python package exists in environment."""
+ values["anyscale_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "anyscale_api_key",
+ "ANYSCALE_API_KEY",
+ )
+ )
+ values["anyscale_api_base"] = get_from_dict_or_env(
+ values,
+ "anyscale_api_base",
+ "ANYSCALE_API_BASE",
+ default=DEFAULT_API_BASE,
+ )
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ if is_openai_v1():
+ # For backwards compatibility.
+ client_params = {
+ "api_key": values["anyscale_api_key"].get_secret_value(),
+ "base_url": values["anyscale_api_base"],
+ }
+ values["client"] = openai.OpenAI(**client_params).embeddings
+ else:
+ values["openai_api_base"] = values["anyscale_api_base"]
+ values["openai_api_key"] = values["anyscale_api_key"].get_secret_value()
+ values["client"] = openai.Embedding
+ return values
+
+ @property
+ def _llm_type(self) -> str:
+ return "anyscale-embedding"
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/ascend.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ascend.py
new file mode 100644
index 0000000000000000000000000000000000000000..940b84bbfc538a62d180ac46d35f0e024a2df7e1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ascend.py
@@ -0,0 +1,137 @@
+import os
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, model_validator
+
+
+class AscendEmbeddings(Embeddings, BaseModel):
+ """
+ Ascend NPU accelerate Embedding model
+
+ Please ensure that you have installed CANN and torch_npu.
+
+ Example:
+
+ from langchain_community.embeddings import AscendEmbeddings
+ model = AscendEmbeddings(model_path=,
+ device_id=0,
+ query_instruction="Represent this sentence for searching relevant passages: "
+ )
+ """
+
+ """model path"""
+ model_path: str
+ """Ascend NPU device id."""
+ device_id: int = 0
+ """Unstruntion to used for embedding query."""
+ query_instruction: str = ""
+ """Unstruntion to used for embedding document."""
+ document_instruction: str = ""
+ use_fp16: bool = True
+ pooling_method: Optional[str] = "cls"
+ batch_size: int = 32
+ model: Any
+ tokenizer: Any
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ try:
+ from transformers import AutoModel, AutoTokenizer
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import transformers, please install with "
+ "`pip install -U transformers`."
+ ) from e
+ try:
+ self.model = AutoModel.from_pretrained(self.model_path).npu().eval()
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
+ except Exception as e:
+ raise Exception(
+ f"Failed to load model [self.model_path], due to following error:{e}"
+ )
+
+ if self.use_fp16:
+ self.model.half()
+ self.encode([f"warmup {i} times" for i in range(10)])
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ if "model_path" not in values:
+ raise ValueError("model_path is required")
+ if not os.access(values["model_path"], os.F_OK):
+ raise FileNotFoundError(
+ f"Unable to find valid model path in [{values['model_path']}]"
+ )
+ try:
+ import torch_npu
+ except ImportError:
+ raise ModuleNotFoundError("torch_npu not found, please install torch_npu")
+ except Exception as e:
+ raise e
+ try:
+ torch_npu.npu.set_device(values["device_id"])
+ except Exception as e:
+ raise Exception(f"set device failed due to {e}")
+ return values
+
+ def encode(self, sentences: Any) -> Any:
+ inputs = self.tokenizer(
+ sentences,
+ padding=True,
+ truncation=True,
+ return_tensors="pt",
+ max_length=512,
+ )
+ try:
+ import torch
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import torch, please install with `pip install -U torch`."
+ ) from e
+ last_hidden_state = self.model(
+ inputs.input_ids.npu(), inputs.attention_mask.npu(), return_dict=True
+ ).last_hidden_state
+ tmp = self.pooling(last_hidden_state, inputs["attention_mask"].npu())
+ embeddings = torch.nn.functional.normalize(tmp, dim=-1)
+ return embeddings.cpu().detach().numpy()
+
+ def pooling(self, last_hidden_state: Any, attention_mask: Any = None) -> Any:
+ try:
+ import torch
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import torch, please install with `pip install -U torch`."
+ ) from e
+ if self.pooling_method == "cls":
+ return last_hidden_state[:, 0]
+ elif self.pooling_method == "mean":
+ s = torch.sum(
+ last_hidden_state * attention_mask.unsqueeze(-1).float(), dim=-1
+ )
+ d = attention_mask.sum(dim=1, keepdim=True).float()
+ return s / d
+ else:
+ raise NotImplementedError(
+ f"Pooling method [{self.pooling_method}] not implemented"
+ )
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ try:
+ import numpy as np
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import numpy, please install with `pip install -U numpy`."
+ ) from e
+ embedding_list = []
+ for i in range(0, len(texts), self.batch_size):
+ texts_ = texts[i : i + self.batch_size]
+ emb = self.encode([self.document_instruction + text for text in texts_])
+ embedding_list.append(emb)
+ return np.concatenate(embedding_list)
+
+ def embed_query(self, text: str) -> List[float]:
+ return self.encode([self.query_instruction + text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/awa.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/awa.py
new file mode 100644
index 0000000000000000000000000000000000000000..27cb422423fdeb5d71734664afd0e2b7cc8fe1ba
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/awa.py
@@ -0,0 +1,64 @@
+from typing import Any, Dict, List
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, model_validator
+
+
+class AwaEmbeddings(BaseModel, Embeddings):
+ """Embedding documents and queries with Awa DB.
+
+ Attributes:
+ client: The AwaEmbedding client.
+ model: The name of the model used for embedding.
+ Default is "all-mpnet-base-v2".
+ """
+
+ client: Any #: :meta private:
+ model: str = "all-mpnet-base-v2"
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that awadb library is installed."""
+
+ try:
+ from awadb import AwaEmbedding
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import awadb library. "
+ "Please install it with `pip install awadb`"
+ ) from exc
+ values["client"] = AwaEmbedding()
+ return values
+
+ def set_model(self, model_name: str) -> None:
+ """Set the model used for embedding.
+ The default model used is all-mpnet-base-v2
+
+ Args:
+ model_name: A string which represents the name of model.
+ """
+ self.model = model_name
+ self.client.model_name = model_name
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed a list of documents using AwaEmbedding.
+
+ Args:
+ texts: The list of texts need to be embedded
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ return self.client.EmbeddingBatch(texts)
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using AwaEmbedding.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.client.Embedding(text)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/azure_openai.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/azure_openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a2327d2cd768522a3afe1914524419127db752
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/azure_openai.py
@@ -0,0 +1,187 @@
+"""Azure OpenAI embeddings wrapper."""
+
+from __future__ import annotations
+
+import os
+import warnings
+from typing import Any, Awaitable, Callable, Dict, Optional, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import Field, model_validator
+from typing_extensions import Self
+
+from langchain_community.embeddings.openai import OpenAIEmbeddings
+from langchain_community.utils.openai import is_openai_v1
+
+
+@deprecated(
+ since="0.0.9",
+ removal="1.0",
+ alternative_import="langchain_openai.AzureOpenAIEmbeddings",
+)
+class AzureOpenAIEmbeddings(OpenAIEmbeddings):
+ """`Azure OpenAI` Embeddings API."""
+
+ azure_endpoint: Union[str, None] = None
+ """Your Azure endpoint, including the resource.
+
+ Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided.
+
+ Example: `https://example-resource.azure.openai.com/`
+ """
+ deployment: Optional[str] = Field(default=None, alias="azure_deployment")
+ """A model deployment.
+
+ If given sets the base client URL to include `/deployments/{azure_deployment}`.
+ Note: this means you won't be able to use non-deployment endpoints.
+ """
+ openai_api_key: Union[str, None] = Field(default=None, alias="api_key")
+ """Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided."""
+ azure_ad_token: Union[str, None] = None
+ """Your Azure Active Directory token.
+
+ Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided.
+
+ For more:
+ https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.
+ """
+ azure_ad_token_provider: Union[Callable[[], str], None] = None
+ """A function that returns an Azure Active Directory token.
+
+ Will be invoked on every sync request. For async requests,
+ will be invoked if `azure_ad_async_token_provider` is not provided.
+ """
+ azure_ad_async_token_provider: Union[Callable[[], Awaitable[str]], None] = None
+ """A function that returns an Azure Active Directory token.
+
+ Will be invoked on every async request.
+ """
+ openai_api_version: Optional[str] = Field(default=None, alias="api_version")
+ """Automatically inferred from env var `OPENAI_API_VERSION` if not provided."""
+ validate_base_url: bool = True
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ # Check OPENAI_KEY for backwards compatibility.
+ # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using
+ # other forms of azure credentials.
+ values["openai_api_key"] = (
+ values.get("openai_api_key")
+ or os.getenv("AZURE_OPENAI_API_KEY")
+ or os.getenv("OPENAI_API_KEY")
+ )
+ values["openai_api_base"] = values.get("openai_api_base") or os.getenv(
+ "OPENAI_API_BASE"
+ )
+ values["openai_api_version"] = values.get("openai_api_version") or os.getenv(
+ "OPENAI_API_VERSION", default="2023-05-15"
+ )
+ values["openai_api_type"] = get_from_dict_or_env(
+ values, "openai_api_type", "OPENAI_API_TYPE", default="azure"
+ )
+ values["openai_organization"] = (
+ values.get("openai_organization")
+ or os.getenv("OPENAI_ORG_ID")
+ or os.getenv("OPENAI_ORGANIZATION")
+ )
+ values["openai_proxy"] = get_from_dict_or_env(
+ values,
+ "openai_proxy",
+ "OPENAI_PROXY",
+ default="",
+ )
+ values["azure_endpoint"] = values.get("azure_endpoint") or os.getenv(
+ "AZURE_OPENAI_ENDPOINT"
+ )
+ values["azure_ad_token"] = values.get("azure_ad_token") or os.getenv(
+ "AZURE_OPENAI_AD_TOKEN"
+ )
+ # Azure OpenAI embedding models allow a maximum of 2048 texts
+ # at a time in each batch
+ # See: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings
+ values["chunk_size"] = min(values["chunk_size"], 2048)
+ try:
+ import openai # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ if is_openai_v1():
+ # For backwards compatibility. Before openai v1, no distinction was made
+ # between azure_endpoint and base_url (openai_api_base).
+ openai_api_base = values["openai_api_base"]
+ if openai_api_base and values["validate_base_url"]:
+ if "/openai" not in openai_api_base:
+ values["openai_api_base"] += "/openai"
+ warnings.warn(
+ "As of openai>=1.0.0, Azure endpoints should be specified via "
+ f"the `azure_endpoint` param not `openai_api_base` "
+ f"(or alias `base_url`). Updating `openai_api_base` from "
+ f"{openai_api_base} to {values['openai_api_base']}."
+ )
+ if values["deployment"]:
+ warnings.warn(
+ "As of openai>=1.0.0, if `deployment` (or alias "
+ "`azure_deployment`) is specified then "
+ "`openai_api_base` (or alias `base_url`) should not be. "
+ "Instead use `deployment` (or alias `azure_deployment`) "
+ "and `azure_endpoint`."
+ )
+ if values["deployment"] not in values["openai_api_base"]:
+ warnings.warn(
+ "As of openai>=1.0.0, if `openai_api_base` "
+ "(or alias `base_url`) is specified it is expected to be "
+ "of the form "
+ "https://example-resource.azure.openai.com/openai/deployments/example-deployment. " # noqa: E501
+ f"Updating {openai_api_base} to "
+ f"{values['openai_api_base']}."
+ )
+ values["openai_api_base"] += (
+ "/deployments/" + values["deployment"]
+ )
+ values["deployment"] = None
+ return values
+
+ @model_validator(mode="after")
+ def post_init_validator(self) -> Self:
+ """Validate that the base url is set."""
+ import openai
+
+ if is_openai_v1():
+ client_params = {
+ "api_version": self.openai_api_version,
+ "azure_endpoint": self.azure_endpoint,
+ "azure_deployment": self.deployment,
+ "api_key": self.openai_api_key,
+ "azure_ad_token": self.azure_ad_token,
+ "azure_ad_token_provider": self.azure_ad_token_provider,
+ "organization": self.openai_organization,
+ "base_url": self.openai_api_base,
+ "timeout": self.request_timeout,
+ "max_retries": self.max_retries,
+ "default_headers": {
+ **(self.default_headers or {}),
+ "User-Agent": "langchain-comm-python-azure-openai",
+ },
+ "default_query": self.default_query,
+ "http_client": self.http_client,
+ }
+ self.client = openai.AzureOpenAI(**client_params).embeddings
+
+ if self.azure_ad_async_token_provider:
+ client_params["azure_ad_token_provider"] = (
+ self.azure_ad_async_token_provider
+ )
+
+ self.async_client = openai.AsyncAzureOpenAI(**client_params).embeddings
+ else:
+ self.client = openai.Embedding
+ return self
+
+ @property
+ def _llm_type(self) -> str:
+ return "azure-openai-chat"
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/baichuan.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/baichuan.py
new file mode 100644
index 0000000000000000000000000000000000000000..c12aaa44f1c1d1928f834a42418098c2c65f65f4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/baichuan.py
@@ -0,0 +1,150 @@
+from typing import Any, List, Optional
+
+import requests
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import (
+ secret_from_env,
+)
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+ model_validator,
+)
+from requests import RequestException
+from typing_extensions import Self
+
+BAICHUAN_API_URL: str = "https://api.baichuan-ai.com/v1/embeddings"
+
+# BaichuanTextEmbeddings is an embedding model provided by Baichuan Inc. (https://www.baichuan-ai.com/home).
+# As of today (Jan 25th, 2024) BaichuanTextEmbeddings ranks #1 in C-MTEB
+# (Chinese Multi-Task Embedding Benchmark) leaderboard.
+# Leaderboard (Under Overall -> Chinese section): https://huggingface.co/spaces/mteb/leaderboard
+
+# Official Website: https://platform.baichuan-ai.com/docs/text-Embedding
+# An API-key is required to use this embedding model. You can get one by registering
+# at https://platform.baichuan-ai.com/docs/text-Embedding.
+# BaichuanTextEmbeddings support 512 token window and produces vectors with
+# 1024 dimensions.
+
+
+# NOTE!! BaichuanTextEmbeddings only supports Chinese text embedding.
+# Multi-language support is coming soon.
+class BaichuanTextEmbeddings(BaseModel, Embeddings):
+ """Baichuan Text Embedding models.
+
+ Setup:
+ To use, you should set the environment variable ``BAICHUAN_API_KEY`` to
+ your API key or pass it as a named parameter to the constructor.
+
+ .. code-block:: bash
+
+ export BAICHUAN_API_KEY="your-api-key"
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.embeddings import BaichuanTextEmbeddings
+
+ embeddings = BaichuanTextEmbeddings()
+
+ Embed:
+ .. code-block:: python
+
+ # embed the documents
+ vectors = embeddings.embed_documents([text1, text2, ...])
+
+ # embed the query
+ vectors = embeddings.embed_query(text)
+ """ # noqa: E501
+
+ session: Any = None #: :meta private:
+ model_name: str = Field(default="Baichuan-Text-Embedding", alias="model")
+ """The model used to embed the documents."""
+ baichuan_api_key: SecretStr = Field(
+ alias="api_key",
+ default_factory=secret_from_env(["BAICHUAN_API_KEY", "BAICHUAN_AUTH_TOKEN"]),
+ )
+ """Automatically inferred from env var `BAICHUAN_API_KEY` if not provided."""
+ chunk_size: int = 16
+ """Chunk size when multiple texts are input"""
+
+ model_config = ConfigDict(populate_by_name=True, protected_namespaces=())
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that auth token exists in environment."""
+ session = requests.Session()
+ session.headers.update(
+ {
+ "Authorization": f"Bearer {self.baichuan_api_key.get_secret_value()}",
+ "Accept-Encoding": "identity",
+ "Content-type": "application/json",
+ }
+ )
+ self.session = session
+ return self
+
+ def _embed(self, texts: List[str]) -> Optional[List[List[float]]]:
+ """Internal method to call Baichuan Embedding API and return embeddings.
+
+ Args:
+ texts: A list of texts to embed.
+
+ Returns:
+ A list of list of floats representing the embeddings, or None if an
+ error occurs.
+ """
+ chunk_texts = [
+ texts[i : i + self.chunk_size]
+ for i in range(0, len(texts), self.chunk_size)
+ ]
+ embed_results = []
+ for chunk in chunk_texts:
+ response = self.session.post(
+ BAICHUAN_API_URL, json={"input": chunk, "model": self.model_name}
+ )
+ # Raise exception if response status code from 400 to 600
+ response.raise_for_status()
+ # Check if the response status code indicates success
+ if response.status_code == 200:
+ resp = response.json()
+ embeddings = resp.get("data", [])
+ # Sort resulting embeddings by index
+ sorted_embeddings = sorted(embeddings, key=lambda e: e.get("index", 0))
+ # Return just the embeddings
+ embed_results.extend(
+ [result.get("embedding", []) for result in sorted_embeddings]
+ )
+ else:
+ # Log error or handle unsuccessful response appropriately
+ # Handle 100 <= status_code < 400, not include 200
+ raise RequestException(
+ f"Error: Received status code {response.status_code} from "
+ "`BaichuanEmbedding` API"
+ )
+ return embed_results
+
+ def embed_documents(self, texts: List[str]) -> Optional[List[List[float]]]: # type: ignore[override]
+ """Public method to get embeddings for a list of documents.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ A list of embeddings, one for each text, or None if an error occurs.
+ """
+ return self._embed(texts)
+
+ def embed_query(self, text: str) -> Optional[List[float]]: # type: ignore[override]
+ """Public method to get embedding for a single query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text, or None if an error occurs.
+ """
+ result = self._embed([text])
+ return result[0] if result is not None else None
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaba2f3487a4680989e623d6160eaa288f67f28b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py
@@ -0,0 +1,186 @@
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import BaseModel, ConfigDict, Field, SecretStr
+
+logger = logging.getLogger(__name__)
+
+
+class QianfanEmbeddingsEndpoint(BaseModel, Embeddings):
+ """Baidu Qianfan Embeddings embedding models.
+
+ Setup:
+ To use, you should have the ``qianfan`` python package installed, and set
+ environment variables ``QIANFAN_AK``, ``QIANFAN_SK``.
+
+ .. code-block:: bash
+
+ pip install qianfan
+ export QIANFAN_AK="your-api-key"
+ export QIANFAN_SK="your-secret_key"
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.embeddings import QianfanEmbeddingsEndpoint
+
+ embeddings = QianfanEmbeddingsEndpoint()
+
+ Embed:
+ .. code-block:: python
+
+ # embed the documents
+ vectors = embeddings.embed_documents([text1, text2, ...])
+
+ # embed the query
+ vectors = embeddings.embed_query(text)
+
+ # embed the documents with async
+ vectors = await embeddings.aembed_documents([text1, text2, ...])
+
+ # embed the query with async
+ vectors = await embeddings.aembed_query(text)
+ """ # noqa: E501
+
+ qianfan_ak: Optional[SecretStr] = Field(default=None, alias="api_key")
+ """Qianfan application apikey"""
+
+ qianfan_sk: Optional[SecretStr] = Field(default=None, alias="secret_key")
+ """Qianfan application secretkey"""
+
+ chunk_size: int = 16
+ """Chunk size when multiple texts are input"""
+
+ model: Optional[str] = Field(default=None)
+ """Model name
+ you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu
+
+ for now, we support Embedding-V1 and
+ - Embedding-V1 (默认模型)
+ - bge-large-en
+ - bge-large-zh
+
+ preset models are mapping to an endpoint.
+ `model` will be ignored if `endpoint` is set
+ """
+
+ endpoint: str = ""
+ """Endpoint of the Qianfan Embedding, required if custom model used."""
+
+ client: Any = None
+ """Qianfan client"""
+
+ init_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """init kwargs for qianfan client init, such as `query_per_second` which is
+ associated with qianfan resource object to limit QPS"""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """extra params for model invoke using with `do`."""
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """
+ Validate whether qianfan_ak and qianfan_sk in the environment variables or
+ configuration file are available or not.
+
+ init qianfan embedding client with `ak`, `sk`, `model`, `endpoint`
+
+ Args:
+
+ values: a dictionary containing configuration information, must include the
+ fields of qianfan_ak and qianfan_sk
+ Returns:
+
+ a dictionary containing configuration information. If qianfan_ak and
+ qianfan_sk are not provided in the environment variables or configuration
+ file,the original values will be returned; otherwise, values containing
+ qianfan_ak and qianfan_sk will be returned.
+ Raises:
+
+ ValueError: qianfan package not found, please install it with `pip install
+ qianfan`
+ """
+ values["qianfan_ak"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "qianfan_ak",
+ "QIANFAN_AK",
+ default="",
+ )
+ )
+ values["qianfan_sk"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "qianfan_sk",
+ "QIANFAN_SK",
+ default="",
+ )
+ )
+
+ try:
+ import qianfan
+
+ params = {
+ **values.get("init_kwargs", {}),
+ "model": values["model"],
+ }
+ if values["qianfan_ak"].get_secret_value() != "":
+ params["ak"] = values["qianfan_ak"].get_secret_value()
+ if values["qianfan_sk"].get_secret_value() != "":
+ params["sk"] = values["qianfan_sk"].get_secret_value()
+ if values["endpoint"] is not None and values["endpoint"] != "":
+ params["endpoint"] = values["endpoint"]
+ values["client"] = qianfan.Embedding(**params)
+ except ImportError:
+ raise ImportError(
+ "qianfan package not found, please install it with "
+ "`pip install qianfan`"
+ )
+ return values
+
+ def embed_query(self, text: str) -> List[float]:
+ resp = self.embed_documents([text])
+ return resp[0]
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """
+ Embeds a list of text documents using the AutoVOT algorithm.
+
+ Args:
+ texts (List[str]): A list of text documents to embed.
+
+ Returns:
+ List[List[float]]: A list of embeddings for each document in the input list.
+ Each embedding is represented as a list of float values.
+ """
+ text_in_chunks = [
+ texts[i : i + self.chunk_size]
+ for i in range(0, len(texts), self.chunk_size)
+ ]
+ lst = []
+ for chunk in text_in_chunks:
+ resp = self.client.do(texts=chunk, **self.model_kwargs)
+ lst.extend([res["embedding"] for res in resp["data"]])
+ return lst
+
+ async def aembed_query(self, text: str) -> List[float]:
+ embeddings = await self.aembed_documents([text])
+ return embeddings[0]
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ text_in_chunks = [
+ texts[i : i + self.chunk_size]
+ for i in range(0, len(texts), self.chunk_size)
+ ]
+ lst = []
+ for chunk in text_in_chunks:
+ resp = await self.client.ado(texts=chunk, **self.model_kwargs)
+ for res in resp["data"]:
+ lst.extend([res["embedding"]])
+ return lst
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/bedrock.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/bedrock.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcfe707b270fc2bfbd6f1719d613d470f18f90b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/bedrock.py
@@ -0,0 +1,222 @@
+import asyncio
+import json
+import os
+from typing import Any, Dict, List, Optional
+
+import numpy as np
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.runnables.config import run_in_executor
+from pydantic import BaseModel, ConfigDict, model_validator
+from typing_extensions import Self
+
+
+@deprecated(
+ since="0.2.11",
+ removal="1.0",
+ alternative_import="langchain_aws.BedrockEmbeddings",
+)
+class BedrockEmbeddings(BaseModel, Embeddings):
+ """Bedrock embedding models.
+
+ To authenticate, the AWS client uses the following methods to
+ automatically load credentials:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific credential profile should be used, you must pass
+ the name of the profile from the ~/.aws/credentials file that is to be used.
+
+ Make sure the credentials / roles used have the required policies to
+ access the Bedrock service.
+ """
+
+ """
+ Example:
+ .. code-block:: python
+
+ from langchain_community.bedrock_embeddings import BedrockEmbeddings
+
+ region_name ="us-east-1"
+ credentials_profile_name = "default"
+ model_id = "amazon.titan-embed-text-v1"
+
+ be = BedrockEmbeddings(
+ credentials_profile_name=credentials_profile_name,
+ region_name=region_name,
+ model_id=model_id
+ )
+ """
+
+ client: Any = None #: :meta private:
+ """Bedrock client."""
+ region_name: Optional[str] = None
+ """The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable
+ or region specified in ~/.aws/config in case it is not provided here.
+ """
+
+ credentials_profile_name: Optional[str] = None
+ """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
+ has either access keys or role information specified.
+ If not specified, the default credential profile or, if on an EC2 instance,
+ credentials from IMDS will be used.
+ See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+ """
+
+ model_id: str = "amazon.titan-embed-text-v1"
+ """Id of the model to call, e.g., amazon.titan-embed-text-v1, this is
+ equivalent to the modelId property in the list-foundation-models api"""
+
+ model_kwargs: Optional[Dict] = None
+ """Keyword arguments to pass to the model."""
+
+ endpoint_url: Optional[str] = None
+ """Needed if you don't want to default to us-east-1 endpoint"""
+
+ normalize: bool = False
+ """Whether the embeddings should be normalized to unit vectors"""
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that AWS credentials to and python package exists in environment."""
+
+ if self.client is not None:
+ return self
+
+ try:
+ import boto3
+
+ if self.credentials_profile_name is not None:
+ session = boto3.Session(profile_name=self.credentials_profile_name)
+ else:
+ # use default credentials
+ session = boto3.Session()
+
+ client_params = {}
+ if self.region_name:
+ client_params["region_name"] = self.region_name
+
+ if self.endpoint_url:
+ client_params["endpoint_url"] = self.endpoint_url
+
+ self.client = session.client("bedrock-runtime", **client_params)
+
+ except ImportError:
+ raise ImportError(
+ "Could not import boto3 python package. "
+ "Please install it with `pip install boto3`."
+ )
+ except Exception as e:
+ raise ValueError(
+ "Could not load credentials to authenticate with AWS client. "
+ "Please check that credentials in the specified "
+ f"profile name are valid. Bedrock error: {e}"
+ ) from e
+
+ return self
+
+ def _embedding_func(self, text: str) -> List[float]:
+ """Call out to Bedrock embedding endpoint."""
+ # replace newlines, which can negatively affect performance.
+ text = text.replace(os.linesep, " ")
+
+ # format input body for provider
+ provider = self.model_id.split(".")[0]
+ _model_kwargs = self.model_kwargs or {}
+ input_body = {**_model_kwargs}
+ if provider == "cohere":
+ if "input_type" not in input_body.keys():
+ input_body["input_type"] = "search_document"
+ input_body["texts"] = [text]
+ else:
+ # includes common provider == "amazon"
+ input_body["inputText"] = text
+ body = json.dumps(input_body)
+
+ try:
+ # invoke bedrock API
+ response = self.client.invoke_model(
+ body=body,
+ modelId=self.model_id,
+ accept="application/json",
+ contentType="application/json",
+ )
+
+ # format output based on provider
+ response_body = json.loads(response.get("body").read())
+ if provider == "cohere":
+ return response_body.get("embeddings")[0]
+ else:
+ # includes common provider == "amazon"
+ return response_body.get("embedding")
+ except Exception as e:
+ raise ValueError(f"Error raised by inference endpoint: {e}")
+
+ def _normalize_vector(self, embeddings: List[float]) -> List[float]:
+ """Normalize the embedding to a unit vector."""
+ emb = np.array(embeddings)
+ norm_emb = emb / np.linalg.norm(emb)
+ return norm_emb.tolist()
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using a Bedrock model.
+
+ Args:
+ texts: The list of texts to embed
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ results = []
+ for text in texts:
+ response = self._embedding_func(text)
+
+ if self.normalize:
+ response = self._normalize_vector(response)
+
+ results.append(response)
+
+ return results
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a Bedrock model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ embedding = self._embedding_func(text)
+
+ if self.normalize:
+ return self._normalize_vector(embedding)
+
+ return embedding
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Asynchronous compute query embeddings using a Bedrock model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+
+ return await run_in_executor(None, self.embed_query, text)
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Asynchronous compute doc embeddings using a Bedrock model.
+
+ Args:
+ texts: The list of texts to embed
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+
+ result = await asyncio.gather(*[self.aembed_query(text) for text in texts])
+
+ return list(result)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/bookend.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/bookend.py
new file mode 100644
index 0000000000000000000000000000000000000000..76aac46fd8ff95f7552ca5119a45fb4139fe004d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/bookend.py
@@ -0,0 +1,97 @@
+"""Wrapper around Bookend AI embedding models."""
+
+import json
+from typing import Any, List
+
+import requests
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field
+
+API_URL = "https://api.bookend.ai/"
+DEFAULT_TASK = "embeddings"
+PATH = "/models/predict"
+
+
+class BookendEmbeddings(BaseModel, Embeddings):
+ """Bookend AI sentence_transformers embedding models.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import BookendEmbeddings
+
+ bookend = BookendEmbeddings(
+ domain={domain}
+ api_token={api_token}
+ model_id={model_id}
+ )
+ bookend.embed_documents([
+ "Please put on these earmuffs because I can't you hear.",
+ "Baby wipes are made of chocolate stardust.",
+ ])
+ bookend.embed_query(
+ "She only paints with bold colors; she does not like pastels."
+ )
+ """
+
+ domain: str
+ """Request for a domain at https://bookend.ai/ to use this embeddings module."""
+ api_token: str
+ """Request for an API token at https://bookend.ai/ to use this embeddings module."""
+ model_id: str
+ """Embeddings model ID to use."""
+ auth_header: dict = Field(default_factory=dict)
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+ self.auth_header = {"Authorization": "Basic {}".format(self.api_token)}
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed documents using a Bookend deployed embeddings model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ result = []
+ headers = self.auth_header
+ headers["Content-Type"] = "application/json; charset=utf-8"
+ params = {
+ "model_id": self.model_id,
+ "task": DEFAULT_TASK,
+ }
+
+ for text in texts:
+ data = json.dumps(
+ {
+ "text": text,
+ "question": None,
+ "context": None,
+ "instruction": None,
+ }
+ )
+ r = requests.request(
+ "POST",
+ API_URL + self.domain + PATH,
+ headers=headers,
+ params=params,
+ data=data,
+ )
+ result.append(r.json()[0]["data"])
+
+ return result
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed a query using a Bookend deployed embeddings model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/clarifai.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/clarifai.py
new file mode 100644
index 0000000000000000000000000000000000000000..e460020bef16008cdb3b4378542f2f81ea6ffdaa
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/clarifai.py
@@ -0,0 +1,139 @@
+import logging
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+logger = logging.getLogger(__name__)
+
+
+class ClarifaiEmbeddings(BaseModel, Embeddings):
+ """Clarifai embedding models.
+
+ To use, you should have the ``clarifai`` python package installed, and the
+ environment variable ``CLARIFAI_PAT`` set with your personal access token or pass it
+ as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import ClarifaiEmbeddings
+ clarifai = ClarifaiEmbeddings(user_id=USER_ID,
+ app_id=APP_ID,
+ model_id=MODEL_ID)
+ (or)
+ Example_URL = "https://clarifai.com/clarifai/main/models/BAAI-bge-base-en-v15"
+ clarifai = ClarifaiEmbeddings(model_url=EXAMPLE_URL)
+ """
+
+ model_url: Optional[str] = None
+ """Model url to use."""
+ model_id: Optional[str] = None
+ """Model id to use."""
+ model_version_id: Optional[str] = None
+ """Model version id to use."""
+ app_id: Optional[str] = None
+ """Clarifai application id to use."""
+ user_id: Optional[str] = None
+ """Clarifai user id to use."""
+ pat: Optional[str] = Field(default=None, exclude=True)
+ """Clarifai personal access token to use."""
+ token: Optional[str] = Field(default=None, exclude=True)
+ """Clarifai session token to use."""
+ model: Any = Field(default=None, exclude=True) #: :meta private:
+ api_base: str = "https://api.clarifai.com"
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that we have all required info to access Clarifai
+ platform and python package exists in environment."""
+
+ try:
+ from clarifai.client.model import Model
+ except ImportError:
+ raise ImportError(
+ "Could not import clarifai python package. "
+ "Please install it with `pip install clarifai`."
+ )
+ user_id = values.get("user_id")
+ app_id = values.get("app_id")
+ model_id = values.get("model_id")
+ model_version_id = values.get("model_version_id")
+ model_url = values.get("model_url")
+ api_base = values.get("api_base")
+ pat = values.get("pat")
+ token = values.get("token")
+
+ values["model"] = Model(
+ url=model_url,
+ app_id=app_id,
+ user_id=user_id,
+ model_version=dict(id=model_version_id),
+ pat=pat,
+ token=token,
+ model_id=model_id,
+ base_url=api_base,
+ )
+
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to Clarifai's embedding models.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ from clarifai.client.input import Inputs
+
+ input_obj = Inputs.from_auth_helper(self.model.auth_helper)
+ batch_size = 32
+ embeddings = []
+
+ try:
+ for i in range(0, len(texts), batch_size):
+ batch = texts[i : i + batch_size]
+ input_batch = [
+ input_obj.get_text_input(input_id=str(id), raw_text=inp)
+ for id, inp in enumerate(batch)
+ ]
+ predict_response = self.model.predict(input_batch)
+ embeddings.extend(
+ [
+ list(output.data.embeddings[0].vector)
+ for output in predict_response.outputs
+ ]
+ )
+
+ except Exception as e:
+ logger.error(f"Predict failed, exception: {e}")
+
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Clarifai's embedding models.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+
+ try:
+ predict_response = self.model.predict_by_bytes(
+ bytes(text, "utf-8"), input_type="text"
+ )
+ embeddings = [
+ list(op.data.embeddings[0].vector) for op in predict_response.outputs
+ ]
+
+ except Exception as e:
+ logger.error(f"Predict failed, exception: {e}")
+
+ return embeddings[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/cloudflare_workersai.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/cloudflare_workersai.py
new file mode 100644
index 0000000000000000000000000000000000000000..39b443625fabf3e4b30e5b4baef76155a319e0db
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/cloudflare_workersai.py
@@ -0,0 +1,97 @@
+from typing import Any, Dict, List
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict
+
+DEFAULT_MODEL_NAME = "@cf/baai/bge-base-en-v1.5"
+
+
+@deprecated(
+ since="0.3.23",
+ removal="1.0",
+ alternative_import="langchain_cloudflare.CloudflareWorkersAIEmbeddings",
+)
+class CloudflareWorkersAIEmbeddings(BaseModel, Embeddings):
+ """Cloudflare Workers AI embedding model.
+
+ To use, you need to provide an API token and
+ account ID to access Cloudflare Workers AI.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import CloudflareWorkersAIEmbeddings
+
+ account_id = "my_account_id"
+ api_token = "my_secret_api_token"
+ model_name = "@cf/baai/bge-small-en-v1.5"
+
+ cf = CloudflareWorkersAIEmbeddings(
+ account_id=account_id,
+ api_token=api_token,
+ model_name=model_name
+ )
+ """
+
+ api_base_url: str = "https://api.cloudflare.com/client/v4/accounts"
+ account_id: str
+ api_token: str
+ model_name: str = DEFAULT_MODEL_NAME
+ batch_size: int = 50
+ strip_new_lines: bool = True
+ headers: Dict[str, str] = {"Authorization": "Bearer "}
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the Cloudflare Workers AI client."""
+ super().__init__(**kwargs)
+
+ self.headers = {"Authorization": f"Bearer {self.api_token}"}
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using Cloudflare Workers AI.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ if self.strip_new_lines:
+ texts = [text.replace("\n", " ") for text in texts]
+
+ batches = [
+ texts[i : i + self.batch_size]
+ for i in range(0, len(texts), self.batch_size)
+ ]
+ embeddings = []
+
+ for batch in batches:
+ response = requests.post(
+ f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}",
+ headers=self.headers,
+ json={"text": batch},
+ )
+ embeddings.extend(response.json()["result"]["data"])
+
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using Cloudflare Workers AI.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ text = text.replace("\n", " ") if self.strip_new_lines else text
+ response = requests.post(
+ f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}",
+ headers=self.headers,
+ json={"text": [text]},
+ )
+ return response.json()["result"]["data"][0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/clova.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/clova.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6d3d77b74d0b9ddd5678944882ef100a8471237
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/clova.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional, cast
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import BaseModel, ConfigDict, SecretStr, model_validator
+
+
+@deprecated(
+ since="0.3.4",
+ removal="1.0.0",
+ alternative_import="langchain_community.ClovaXEmbeddings",
+)
+class ClovaEmbeddings(BaseModel, Embeddings):
+ """
+ Clova's embedding service.
+
+ To use this service,
+
+ you should have the following environment variables
+ set with your API tokens and application ID,
+ or pass them as named parameters to the constructor:
+
+ - ``CLOVA_EMB_API_KEY``: API key for accessing Clova's embedding service.
+ - ``CLOVA_EMB_APIGW_API_KEY``: API gateway key for enhanced security.
+ - ``CLOVA_EMB_APP_ID``: Application ID for identifying your application.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import ClovaEmbeddings
+ embeddings = ClovaEmbeddings(
+ clova_emb_api_key='your_clova_emb_api_key',
+ clova_emb_apigw_api_key='your_clova_emb_apigw_api_key',
+ app_id='your_app_id'
+ )
+
+ query_text = "This is a test query."
+ query_result = embeddings.embed_query(query_text)
+
+ document_text = "This is a test document."
+ document_result = embeddings.embed_documents([document_text])
+
+ """
+
+ endpoint_url: str = (
+ "https://clovastudio.apigw.ntruss.com/testapp/v1/api-tools/embedding"
+ )
+ """Endpoint URL to use."""
+ model: str = "clir-emb-dolphin"
+ """Embedding model name to use."""
+ clova_emb_api_key: Optional[SecretStr] = None
+ """API key for accessing Clova's embedding service."""
+ clova_emb_apigw_api_key: Optional[SecretStr] = None
+ """API gateway key for enhanced security."""
+ app_id: Optional[SecretStr] = None
+ """Application ID for identifying your application."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate api key exists in environment."""
+ values["clova_emb_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "clova_emb_api_key", "CLOVA_EMB_API_KEY")
+ )
+ values["clova_emb_apigw_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values, "clova_emb_apigw_api_key", "CLOVA_EMB_APIGW_API_KEY"
+ )
+ )
+ values["app_id"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "app_id", "CLOVA_EMB_APP_ID")
+ )
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """
+ Embed a list of texts and return their embeddings.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ embeddings = []
+ for text in texts:
+ embeddings.append(self._embed_text(text))
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """
+ Embed a single query text and return its embedding.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self._embed_text(text)
+
+ def _embed_text(self, text: str) -> List[float]:
+ """
+ Internal method to call the embedding API and handle the response.
+ """
+ payload = {"text": text}
+
+ # HTTP headers for authorization
+ headers = {
+ "X-NCP-CLOVASTUDIO-API-KEY": cast(
+ SecretStr, self.clova_emb_api_key
+ ).get_secret_value(),
+ "X-NCP-APIGW-API-KEY": cast(
+ SecretStr, self.clova_emb_apigw_api_key
+ ).get_secret_value(),
+ "Content-Type": "application/json",
+ }
+
+ # send request
+ app_id = cast(SecretStr, self.app_id).get_secret_value()
+ response = requests.post(
+ f"{self.endpoint_url}/{self.model}/{app_id}",
+ headers=headers,
+ json=payload,
+ )
+
+ # check for errors
+ if response.status_code == 200:
+ response_data = response.json()
+ if "result" in response_data and "embedding" in response_data["result"]:
+ return response_data["result"]["embedding"]
+ raise ValueError(
+ f"API request failed with status {response.status_code}: {response.text}"
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/cohere.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/cohere.py
new file mode 100644
index 0000000000000000000000000000000000000000..504f688100f4791a829fcb8c383af6ef954aebee
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/cohere.py
@@ -0,0 +1,172 @@
+from typing import Any, Dict, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, ConfigDict, model_validator
+
+from langchain_community.llms.cohere import _create_retry_decorator
+
+
+@deprecated(
+ since="0.0.30",
+ removal="1.0",
+ alternative_import="langchain_cohere.CohereEmbeddings",
+)
+class CohereEmbeddings(BaseModel, Embeddings):
+ """Cohere embedding models.
+
+ To use, you should have the ``cohere`` python package installed, and the
+ environment variable ``COHERE_API_KEY`` set with your API key or pass it
+ as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import CohereEmbeddings
+ cohere = CohereEmbeddings(
+ model="embed-english-light-v3.0",
+ cohere_api_key="my-api-key"
+ )
+ """
+
+ client: Any = None #: :meta private:
+ """Cohere client."""
+ async_client: Any = None #: :meta private:
+ """Cohere async client."""
+ model: str = "embed-english-v2.0"
+ """Model name to use."""
+
+ truncate: Optional[str] = None
+ """Truncate embeddings that are too long from start or end ("NONE"|"START"|"END")"""
+
+ cohere_api_key: Optional[str] = None
+
+ max_retries: int = 3
+ """Maximum number of retries to make when generating."""
+ request_timeout: Optional[float] = None
+ """Timeout in seconds for the Cohere API request."""
+ user_agent: str = "langchain"
+ """Identifier for the application making the request."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ cohere_api_key = get_from_dict_or_env(
+ values, "cohere_api_key", "COHERE_API_KEY"
+ )
+ request_timeout = values.get("request_timeout")
+
+ try:
+ import cohere
+
+ client_name = values["user_agent"]
+ values["client"] = cohere.Client(
+ cohere_api_key,
+ timeout=request_timeout,
+ client_name=client_name,
+ )
+ values["async_client"] = cohere.AsyncClient(
+ cohere_api_key,
+ timeout=request_timeout,
+ client_name=client_name,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import cohere python package. "
+ "Please install it with `pip install cohere`."
+ )
+ return values
+
+ def embed_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the embed call."""
+ retry_decorator = _create_retry_decorator(self.max_retries)
+
+ @retry_decorator
+ def _embed_with_retry(**kwargs: Any) -> Any:
+ return self.client.embed(**kwargs)
+
+ return _embed_with_retry(**kwargs)
+
+ def aembed_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the embed call."""
+ retry_decorator = _create_retry_decorator(self.max_retries)
+
+ @retry_decorator
+ async def _embed_with_retry(**kwargs: Any) -> Any:
+ return await self.async_client.embed(**kwargs)
+
+ return _embed_with_retry(**kwargs)
+
+ def embed(
+ self, texts: List[str], *, input_type: Optional[str] = None
+ ) -> List[List[float]]:
+ embeddings = self.embed_with_retry(
+ model=self.model,
+ texts=texts,
+ input_type=input_type,
+ truncate=self.truncate,
+ ).embeddings
+ return [list(map(float, e)) for e in embeddings]
+
+ async def aembed(
+ self, texts: List[str], *, input_type: Optional[str] = None
+ ) -> List[List[float]]:
+ embeddings = (
+ await self.aembed_with_retry(
+ model=self.model,
+ texts=texts,
+ input_type=input_type,
+ truncate=self.truncate,
+ )
+ ).embeddings
+ return [list(map(float, e)) for e in embeddings]
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed a list of document texts.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ return self.embed(texts, input_type="search_document")
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Async call out to Cohere's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ return await self.aembed(texts, input_type="search_document")
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Cohere's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed([text], input_type="search_query")[0]
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Async call out to Cohere's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return (await self.aembed([text], input_type="search_query"))[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/dashscope.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/dashscope.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e30651c35d9ccb289078e06539cca751f5042d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/dashscope.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+import logging
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+)
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, ConfigDict, model_validator
+from requests.exceptions import HTTPError
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+logger = logging.getLogger(__name__)
+
+BATCH_SIZE = {
+ "text-embedding-v1": 25,
+ "text-embedding-v2": 25,
+ "text-embedding-v3": 10,
+ "text-embedding-v4": 10,
+}
+
+
+def _create_retry_decorator(embeddings: DashScopeEmbeddings) -> Callable[[Any], Any]:
+ multiplier = 1
+ min_seconds = 1
+ max_seconds = 4
+ # Wait 2^x * 1 second between each retry starting with
+ # 1 seconds, then up to 4 seconds, then 4 seconds afterwards
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(embeddings.max_retries),
+ wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds),
+ retry=(retry_if_exception_type(HTTPError)),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+def embed_with_retry(embeddings: DashScopeEmbeddings, **kwargs: Any) -> Any:
+ """Use tenacity to retry the embedding call."""
+ retry_decorator = _create_retry_decorator(embeddings)
+
+ @retry_decorator
+ def _embed_with_retry(**kwargs: Any) -> Any:
+ result = []
+ i = 0
+ input_data = kwargs["input"]
+ input_len = len(input_data) if isinstance(input_data, list) else 1
+ batch_size = BATCH_SIZE.get(kwargs["model"], 25)
+ while i < input_len:
+ kwargs["input"] = (
+ input_data[i : i + batch_size]
+ if isinstance(input_data, list)
+ else input_data
+ )
+ resp = embeddings.client.call(**kwargs)
+ if resp.status_code == 200:
+ result += resp.output["embeddings"]
+ elif resp.status_code in [400, 401]:
+ raise ValueError(
+ f"status_code: {resp.status_code} \n "
+ f"code: {resp.code} \n message: {resp.message}"
+ )
+ else:
+ raise HTTPError(
+ f"HTTP error occurred: status_code: {resp.status_code} \n "
+ f"code: {resp.code} \n message: {resp.message}",
+ response=resp,
+ )
+ i += batch_size
+ return result
+
+ return _embed_with_retry(**kwargs)
+
+
+class DashScopeEmbeddings(BaseModel, Embeddings):
+ """DashScope embedding models.
+
+ To use, you should have the ``dashscope`` python package installed, and the
+ environment variable ``DASHSCOPE_API_KEY`` set with your API key or pass it
+ as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import DashScopeEmbeddings
+ embeddings = DashScopeEmbeddings(dashscope_api_key="my-api-key")
+
+ Example:
+ .. code-block:: python
+
+ import os
+ os.environ["DASHSCOPE_API_KEY"] = "your DashScope API KEY"
+
+ from langchain_community.embeddings.dashscope import DashScopeEmbeddings
+ embeddings = DashScopeEmbeddings(
+ model="text-embedding-v1",
+ )
+ text = "This is a test query."
+ query_result = embeddings.embed_query(text)
+
+ """
+
+ client: Any = None #: :meta private:
+ """The DashScope client."""
+ model: str = "text-embedding-v1"
+ dashscope_api_key: Optional[str] = None
+ max_retries: int = 5
+ """Maximum number of retries to make when generating."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ import dashscope
+
+ """Validate that api key and python package exists in environment."""
+ values["dashscope_api_key"] = get_from_dict_or_env(
+ values, "dashscope_api_key", "DASHSCOPE_API_KEY"
+ )
+ dashscope.api_key = values["dashscope_api_key"]
+ try:
+ import dashscope
+
+ values["client"] = dashscope.TextEmbedding
+ except ImportError:
+ raise ImportError(
+ "Could not import dashscope python package. "
+ "Please install it with `pip install dashscope`."
+ )
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to DashScope's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ embeddings = embed_with_retry(
+ self, input=texts, text_type="document", model=self.model
+ )
+ embedding_list = [item["embedding"] for item in embeddings]
+ return embedding_list
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to DashScope's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embedding for the text.
+ """
+ embedding = embed_with_retry(
+ self, input=text, text_type="query", model=self.model
+ )[0]["embedding"]
+ return embedding
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/databricks.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/databricks.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bb68024b542fc521f742649dd5a0f636521e37e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/databricks.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+from typing import Iterator, List
+from urllib.parse import urlparse
+
+from langchain_core._api import deprecated
+
+from langchain_community.embeddings.mlflow import MlflowEmbeddings
+
+
+def _chunk(texts: List[str], size: int) -> Iterator[List[str]]:
+ for i in range(0, len(texts), size):
+ yield texts[i : i + size]
+
+
+@deprecated(
+ since="0.3.3",
+ removal="1.0",
+ alternative_import="databricks_langchain.DatabricksEmbeddings",
+)
+class DatabricksEmbeddings(MlflowEmbeddings):
+ """Databricks embeddings.
+
+ To use, you should have the ``mlflow`` python package installed.
+ For more information, see https://mlflow.org/docs/latest/llms/deployments.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import DatabricksEmbeddings
+
+ embeddings = DatabricksEmbeddings(
+ target_uri="databricks",
+ endpoint="embeddings",
+ )
+ """
+
+ target_uri: str = "databricks"
+ """The target URI to use. Defaults to ``databricks``."""
+
+ @property
+ def _mlflow_extras(self) -> str:
+ return ""
+
+ def _validate_uri(self) -> None:
+ if self.target_uri == "databricks":
+ return
+
+ if urlparse(self.target_uri).scheme != "databricks":
+ raise ValueError(
+ "Invalid target URI. The target URI must be a valid databricks URI."
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/deepinfra.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/deepinfra.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0d2c4760116e2faabf51e485334c90f3b5e0eab
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/deepinfra.py
@@ -0,0 +1,140 @@
+from typing import Any, Dict, List, Mapping, Optional
+
+import requests
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from pydantic import BaseModel, ConfigDict
+
+DEFAULT_MODEL_ID = "sentence-transformers/clip-ViT-B-32"
+MAX_BATCH_SIZE = 1024
+
+
+class DeepInfraEmbeddings(BaseModel, Embeddings):
+ """Deep Infra's embedding inference service.
+
+ To use, you should have the
+ environment variable ``DEEPINFRA_API_TOKEN`` set with your API token, or pass
+ it as a named parameter to the constructor.
+ There are multiple embeddings models available,
+ see https://deepinfra.com/models?type=embeddings.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import DeepInfraEmbeddings
+ deepinfra_emb = DeepInfraEmbeddings(
+ model_id="sentence-transformers/clip-ViT-B-32",
+ deepinfra_api_token="my-api-key"
+ )
+ r1 = deepinfra_emb.embed_documents(
+ [
+ "Alpha is the first letter of Greek alphabet",
+ "Beta is the second letter of Greek alphabet",
+ ]
+ )
+ r2 = deepinfra_emb.embed_query(
+ "What is the second letter of Greek alphabet"
+ )
+
+ """
+
+ model_id: str = DEFAULT_MODEL_ID
+ """Embeddings model to use."""
+ normalize: bool = False
+ """whether to normalize the computed embeddings"""
+ embed_instruction: str = "passage: "
+ """Instruction used to embed documents."""
+ query_instruction: str = "query: "
+ """Instruction used to embed the query."""
+ model_kwargs: Optional[dict] = None
+ """Other model keyword args"""
+ deepinfra_api_token: Optional[str] = None
+ """API token for Deep Infra. If not provided, the token is
+ fetched from the environment variable 'DEEPINFRA_API_TOKEN'."""
+ batch_size: int = MAX_BATCH_SIZE
+ """Batch size for embedding requests."""
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ deepinfra_api_token = get_from_dict_or_env(
+ values, "deepinfra_api_token", "DEEPINFRA_API_TOKEN"
+ )
+ values["deepinfra_api_token"] = deepinfra_api_token
+ return values
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ return {"model_id": self.model_id}
+
+ def _embed(self, input: List[str]) -> List[List[float]]:
+ _model_kwargs = self.model_kwargs or {}
+ # HTTP headers for authorization
+ headers = {
+ "Authorization": f"bearer {self.deepinfra_api_token}",
+ "Content-Type": "application/json",
+ }
+ # send request
+ try:
+ res = requests.post(
+ f"https://api.deepinfra.com/v1/inference/{self.model_id}",
+ headers=headers,
+ json={"inputs": input, "normalize": self.normalize, **_model_kwargs},
+ )
+ except requests.exceptions.RequestException as e:
+ raise ValueError(f"Error raised by inference endpoint: {e}")
+
+ if res.status_code != 200:
+ raise ValueError(
+ "Error raised by inference API HTTP code: %s, %s"
+ % (res.status_code, res.text)
+ )
+ try:
+ t = res.json()
+ embeddings = t["embeddings"]
+ except requests.exceptions.JSONDecodeError as e:
+ raise ValueError(
+ f"Error raised by inference API: {e}.\nResponse: {res.text}"
+ )
+
+ return embeddings
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed documents using a Deep Infra deployed embedding model.
+ For larger batches, the input list of texts is chunked into smaller
+ batches to avoid exceeding the maximum request size.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+
+ embeddings = []
+ instruction_pairs = [f"{self.embed_instruction}{text}" for text in texts]
+
+ chunks = [
+ instruction_pairs[i : i + self.batch_size]
+ for i in range(0, len(instruction_pairs), self.batch_size)
+ ]
+ for chunk in chunks:
+ embeddings += self._embed(chunk)
+
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed a query using a Deep Infra deployed embedding model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ instruction_pair = f"{self.query_instruction}{text}"
+ embedding = self._embed([instruction_pair])[0]
+ return embedding
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/edenai.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/edenai.py
new file mode 100644
index 0000000000000000000000000000000000000000..097c730ae423a0efdb02a43d583f34fb60c6844d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/edenai.py
@@ -0,0 +1,114 @@
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+)
+
+from langchain_community.utilities.requests import Requests
+
+
+class EdenAiEmbeddings(BaseModel, Embeddings):
+ """EdenAI embedding.
+ environment variable ``EDENAI_API_KEY`` set with your API key, or pass
+ it as a named parameter.
+ """
+
+ edenai_api_key: Optional[SecretStr] = Field(None, description="EdenAI API Token")
+
+ provider: str = "openai"
+ """embedding provider to use (eg: openai,google etc.)"""
+
+ model: Optional[str] = None
+ """
+ model name for above provider (eg: 'gpt-3.5-turbo-instruct' for openai)
+ available models are shown on https://docs.edenai.co/ under 'available providers'
+ """
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key exists in environment."""
+ values["edenai_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "edenai_api_key", "EDENAI_API_KEY")
+ )
+ return values
+
+ @staticmethod
+ def get_user_agent() -> str:
+ from langchain_community import __version__
+
+ return f"langchain/{__version__}"
+
+ def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Compute embeddings using EdenAi api."""
+ url = "https://api.edenai.run/v2/text/embeddings"
+
+ headers = {
+ "accept": "application/json",
+ "content-type": "application/json",
+ "authorization": f"Bearer {self.edenai_api_key.get_secret_value()}", # type: ignore[union-attr]
+ "User-Agent": self.get_user_agent(),
+ }
+
+ payload: Dict[str, Any] = {"texts": texts, "providers": self.provider}
+
+ if self.model is not None:
+ payload["settings"] = {self.provider: self.model}
+
+ request = Requests(headers=headers)
+ response = request.post(url=url, data=payload)
+ if response.status_code >= 500:
+ raise Exception(f"EdenAI Server: Error {response.status_code}")
+ elif response.status_code >= 400:
+ raise ValueError(f"EdenAI received an invalid payload: {response.text}")
+ elif response.status_code != 200:
+ raise Exception(
+ f"EdenAI returned an unexpected response with status "
+ f"{response.status_code}: {response.text}"
+ )
+
+ temp = response.json()
+
+ provider_response = temp[self.provider]
+ if provider_response.get("status") == "fail":
+ err_msg = provider_response.get("error", {}).get("message")
+ raise Exception(err_msg)
+
+ embeddings = []
+ for embed_item in temp[self.provider]["items"]:
+ embedding = embed_item["embedding"]
+
+ embeddings.append(embedding)
+
+ return embeddings
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed a list of documents using EdenAI.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+
+ return self._generate_embeddings(texts)
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed a query using EdenAI.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self._generate_embeddings([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/elasticsearch.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/elasticsearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea080ab9aa98915bc1e4f785e3e2fcbd438c4ac0
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/elasticsearch.py
@@ -0,0 +1,226 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, List, Optional
+
+from langchain_core._api import deprecated
+from langchain_core.utils import get_from_env
+
+if TYPE_CHECKING:
+ from elasticsearch import Elasticsearch
+ from elasticsearch.client import MlClient
+
+from langchain_core.embeddings import Embeddings
+
+
+@deprecated(
+ "0.1.11", alternative="Use class in langchain-elasticsearch package", pending=True
+)
+class ElasticsearchEmbeddings(Embeddings):
+ """Elasticsearch embedding models.
+
+ This class provides an interface to generate embeddings using a model deployed
+ in an Elasticsearch cluster. It requires an Elasticsearch connection object
+ and the model_id of the model deployed in the cluster.
+
+ In Elasticsearch you need to have an embedding model loaded and deployed.
+ - https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html
+ - https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html
+ """
+
+ def __init__(
+ self,
+ client: MlClient,
+ model_id: str,
+ *,
+ input_field: str = "text_field",
+ ):
+ """
+ Initialize the ElasticsearchEmbeddings instance.
+
+ Args:
+ client (MlClient): An Elasticsearch ML client object.
+ model_id (str): The model_id of the model deployed in the Elasticsearch
+ cluster.
+ input_field (str): The name of the key for the input text field in the
+ document. Defaults to 'text_field'.
+ """
+ self.client = client
+ self.model_id = model_id
+ self.input_field = input_field
+
+ @classmethod
+ def from_credentials(
+ cls,
+ model_id: str,
+ *,
+ es_cloud_id: Optional[str] = None,
+ es_user: Optional[str] = None,
+ es_password: Optional[str] = None,
+ input_field: str = "text_field",
+ ) -> ElasticsearchEmbeddings:
+ """Instantiate embeddings from Elasticsearch credentials.
+
+ Args:
+ model_id (str): The model_id of the model deployed in the Elasticsearch
+ cluster.
+ input_field (str): The name of the key for the input text field in the
+ document. Defaults to 'text_field'.
+ es_cloud_id: (str, optional): The Elasticsearch cloud ID to connect to.
+ es_user: (str, optional): Elasticsearch username.
+ es_password: (str, optional): Elasticsearch password.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import ElasticsearchEmbeddings
+
+ # Define the model ID and input field name (if different from default)
+ model_id = "your_model_id"
+ # Optional, only if different from 'text_field'
+ input_field = "your_input_field"
+
+ # Credentials can be passed in two ways. Either set the env vars
+ # ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically
+ # pulled in, or pass them in directly as kwargs.
+ embeddings = ElasticsearchEmbeddings.from_credentials(
+ model_id,
+ input_field=input_field,
+ # es_cloud_id="foo",
+ # es_user="bar",
+ # es_password="baz",
+ )
+
+ documents = [
+ "This is an example document.",
+ "Another example document to generate embeddings for.",
+ ]
+ embeddings_generator.embed_documents(documents)
+ """
+ try:
+ from elasticsearch import Elasticsearch
+ from elasticsearch.client import MlClient
+ except ImportError:
+ raise ImportError(
+ "elasticsearch package not found, please install with 'pip install "
+ "elasticsearch'"
+ )
+
+ es_cloud_id = es_cloud_id or get_from_env("es_cloud_id", "ES_CLOUD_ID")
+ es_user = es_user or get_from_env("es_user", "ES_USER")
+ es_password = es_password or get_from_env("es_password", "ES_PASSWORD")
+
+ # Connect to Elasticsearch
+ es_connection = Elasticsearch(
+ cloud_id=es_cloud_id, basic_auth=(es_user, es_password)
+ )
+ client = MlClient(es_connection)
+ return cls(client, model_id, input_field=input_field)
+
+ @classmethod
+ def from_es_connection(
+ cls,
+ model_id: str,
+ es_connection: Elasticsearch,
+ input_field: str = "text_field",
+ ) -> ElasticsearchEmbeddings:
+ """
+ Instantiate embeddings from an existing Elasticsearch connection.
+
+ This method provides a way to create an instance of the ElasticsearchEmbeddings
+ class using an existing Elasticsearch connection. The connection object is used
+ to create an MlClient, which is then used to initialize the
+ ElasticsearchEmbeddings instance.
+
+ Args:
+ model_id (str): The model_id of the model deployed in the Elasticsearch cluster.
+ es_connection (elasticsearch.Elasticsearch): An existing Elasticsearch
+ connection object. input_field (str, optional): The name of the key for the
+ input text field in the document. Defaults to 'text_field'.
+
+ Returns:
+ ElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class.
+
+ Example:
+ .. code-block:: python
+
+ from elasticsearch import Elasticsearch
+
+ from langchain_community.embeddings import ElasticsearchEmbeddings
+
+ # Define the model ID and input field name (if different from default)
+ model_id = "your_model_id"
+ # Optional, only if different from 'text_field'
+ input_field = "your_input_field"
+
+ # Create Elasticsearch connection
+ es_connection = Elasticsearch(
+ hosts=["localhost:9200"], http_auth=("user", "password")
+ )
+
+ # Instantiate ElasticsearchEmbeddings using the existing connection
+ embeddings = ElasticsearchEmbeddings.from_es_connection(
+ model_id,
+ es_connection,
+ input_field=input_field,
+ )
+
+ documents = [
+ "This is an example document.",
+ "Another example document to generate embeddings for.",
+ ]
+ embeddings_generator.embed_documents(documents)
+ """
+ # Importing MlClient from elasticsearch.client within the method to
+ # avoid unnecessary import if the method is not used
+ from elasticsearch.client import MlClient
+
+ # Create an MlClient from the given Elasticsearch connection
+ client = MlClient(es_connection)
+
+ # Return a new instance of the ElasticsearchEmbeddings class with
+ # the MlClient, model_id, and input_field
+ return cls(client, model_id, input_field=input_field)
+
+ def _embedding_func(self, texts: List[str]) -> List[List[float]]:
+ """
+ Generate embeddings for the given texts using the Elasticsearch model.
+
+ Args:
+ texts (List[str]): A list of text strings to generate embeddings for.
+
+ Returns:
+ List[List[float]]: A list of embeddings, one for each text in the input
+ list.
+ """
+ response = self.client.infer_trained_model(
+ model_id=self.model_id, docs=[{self.input_field: text} for text in texts]
+ )
+
+ embeddings = [doc["predicted_value"] for doc in response["inference_results"]]
+ return embeddings
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """
+ Generate embeddings for a list of documents.
+
+ Args:
+ texts (List[str]): A list of document text strings to generate embeddings
+ for.
+
+ Returns:
+ List[List[float]]: A list of embeddings, one for each document in the input
+ list.
+ """
+ return self._embedding_func(texts)
+
+ def embed_query(self, text: str) -> List[float]:
+ """
+ Generate an embedding for a single query text.
+
+ Args:
+ text (str): The query text to generate an embedding for.
+
+ Returns:
+ List[float]: The embedding for the input query text.
+ """
+ return self._embedding_func([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/embaas.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/embaas.py
new file mode 100644
index 0000000000000000000000000000000000000000..78fd42bf8501da2cd293cbd9854f805049ba952b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/embaas.py
@@ -0,0 +1,155 @@
+from typing import Any, Dict, List, Mapping, Optional
+
+import requests
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import BaseModel, ConfigDict, SecretStr
+from requests.adapters import HTTPAdapter, Retry
+from typing_extensions import NotRequired, TypedDict
+
+# Currently supported maximum batch size for embedding requests
+MAX_BATCH_SIZE = 256
+EMBAAS_API_URL = "https://api.embaas.io/v1/embeddings/"
+
+
+class EmbaasEmbeddingsPayload(TypedDict):
+ """Payload for the Embaas embeddings API."""
+
+ model: str
+ texts: List[str]
+ instruction: NotRequired[str]
+
+
+class EmbaasEmbeddings(BaseModel, Embeddings):
+ """Embaas's embedding service.
+
+ To use, you should have the
+ environment variable ``EMBAAS_API_KEY`` set with your API key, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ # initialize with default model and instruction
+ from langchain_community.embeddings import EmbaasEmbeddings
+ emb = EmbaasEmbeddings()
+
+ # initialize with custom model and instruction
+ from langchain_community.embeddings import EmbaasEmbeddings
+ emb_model = "instructor-large"
+ emb_inst = "Represent the Wikipedia document for retrieval"
+ emb = EmbaasEmbeddings(
+ model=emb_model,
+ instruction=emb_inst
+ )
+ """
+
+ model: str = "e5-large-v2"
+ """The model used for embeddings."""
+ instruction: Optional[str] = None
+ """Instruction used for domain-specific embeddings."""
+ api_url: str = EMBAAS_API_URL
+ """The URL for the embaas embeddings API."""
+ embaas_api_key: Optional[SecretStr] = None
+ """max number of retries for requests"""
+ max_retries: Optional[int] = 3
+ """request timeout in seconds"""
+ timeout: Optional[int] = 30
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ embaas_api_key = convert_to_secret_str(
+ get_from_dict_or_env(values, "embaas_api_key", "EMBAAS_API_KEY")
+ )
+ values["embaas_api_key"] = embaas_api_key
+ return values
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying params."""
+ return {"model": self.model, "instruction": self.instruction}
+
+ def _generate_payload(self, texts: List[str]) -> EmbaasEmbeddingsPayload:
+ """Generates payload for the API request."""
+ payload = EmbaasEmbeddingsPayload(texts=texts, model=self.model)
+ if self.instruction:
+ payload["instruction"] = self.instruction
+ return payload
+
+ def _handle_request(self, payload: EmbaasEmbeddingsPayload) -> List[List[float]]:
+ """Sends a request to the Embaas API and handles the response."""
+ headers = {
+ "Authorization": f"Bearer {self.embaas_api_key.get_secret_value()}", # type: ignore[union-attr]
+ "Content-Type": "application/json",
+ }
+
+ session = requests.Session()
+ retries = Retry(
+ total=self.max_retries,
+ backoff_factor=0.5,
+ allowed_methods=["POST"],
+ raise_on_status=True,
+ )
+
+ session.mount("http://", HTTPAdapter(max_retries=retries))
+ session.mount("https://", HTTPAdapter(max_retries=retries))
+ response = session.post(
+ self.api_url,
+ headers=headers,
+ json=payload,
+ timeout=self.timeout,
+ )
+
+ parsed_response = response.json()
+ embeddings = [item["embedding"] for item in parsed_response["data"]]
+
+ return embeddings
+
+ def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Generate embeddings using the Embaas API."""
+ payload = self._generate_payload(texts)
+ try:
+ return self._handle_request(payload)
+ except requests.exceptions.RequestException as e:
+ if e.response is None or not e.response.text:
+ raise ValueError(f"Error raised by embaas embeddings API: {e}")
+
+ parsed_response = e.response.json()
+ if "message" in parsed_response:
+ raise ValueError(
+ "Validation Error raised by embaas embeddings API:"
+ f"{parsed_response['message']}"
+ )
+ raise
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Get embeddings for a list of texts.
+
+ Args:
+ texts: The list of texts to get embeddings for.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ batches = [
+ texts[i : i + MAX_BATCH_SIZE] for i in range(0, len(texts), MAX_BATCH_SIZE)
+ ]
+ embeddings = [self._generate_embeddings(batch) for batch in batches]
+ # flatten the list of lists into a single list
+ return [embedding for batch in embeddings for embedding in batch]
+
+ def embed_query(self, text: str) -> List[float]:
+ """Get embeddings for a single text.
+
+ Args:
+ text: The text to get embeddings for.
+
+ Returns:
+ List of embeddings.
+ """
+ return self.embed_documents([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/ernie.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ernie.py
new file mode 100644
index 0000000000000000000000000000000000000000..34758c58b4c2029c530396b683840ccfd4536546
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ernie.py
@@ -0,0 +1,158 @@
+import asyncio
+import logging
+import threading
+from typing import Dict, List, Optional
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.runnables.config import run_in_executor
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from pydantic import BaseModel, ConfigDict
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.0.13",
+ alternative="langchain_community.embeddings.QianfanEmbeddingsEndpoint",
+)
+class ErnieEmbeddings(BaseModel, Embeddings):
+ """`Ernie Embeddings V1` embedding models."""
+
+ ernie_api_base: Optional[str] = None
+ ernie_client_id: Optional[str] = None
+ ernie_client_secret: Optional[str] = None
+ access_token: Optional[str] = None
+
+ chunk_size: int = 16
+
+ model_name: str = "ErnieBot-Embedding-V1"
+
+ _lock = threading.Lock()
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ values["ernie_api_base"] = get_from_dict_or_env(
+ values, "ernie_api_base", "ERNIE_API_BASE", "https://aip.baidubce.com"
+ )
+ values["ernie_client_id"] = get_from_dict_or_env(
+ values,
+ "ernie_client_id",
+ "ERNIE_CLIENT_ID",
+ )
+ values["ernie_client_secret"] = get_from_dict_or_env(
+ values,
+ "ernie_client_secret",
+ "ERNIE_CLIENT_SECRET",
+ )
+ return values
+
+ def _embedding(self, json: object) -> dict:
+ base_url = (
+ f"{self.ernie_api_base}/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings"
+ )
+ resp = requests.post(
+ f"{base_url}/embedding-v1",
+ headers={
+ "Content-Type": "application/json",
+ },
+ params={"access_token": self.access_token},
+ json=json,
+ )
+ return resp.json()
+
+ def _refresh_access_token_with_lock(self) -> None:
+ with self._lock:
+ logger.debug("Refreshing access token")
+ base_url: str = f"{self.ernie_api_base}/oauth/2.0/token"
+ resp = requests.post(
+ base_url,
+ headers={
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ },
+ params={
+ "grant_type": "client_credentials",
+ "client_id": self.ernie_client_id,
+ "client_secret": self.ernie_client_secret,
+ },
+ )
+ self.access_token = str(resp.json().get("access_token"))
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed search docs.
+
+ Args:
+ texts: The list of texts to embed
+
+ Returns:
+ List[List[float]]: List of embeddings, one for each text.
+ """
+
+ if not self.access_token:
+ self._refresh_access_token_with_lock()
+ text_in_chunks = [
+ texts[i : i + self.chunk_size]
+ for i in range(0, len(texts), self.chunk_size)
+ ]
+ lst = []
+ for chunk in text_in_chunks:
+ resp = self._embedding({"input": [text for text in chunk]})
+ if resp.get("error_code"):
+ if resp.get("error_code") == 111:
+ self._refresh_access_token_with_lock()
+ resp = self._embedding({"input": [text for text in chunk]})
+ else:
+ raise ValueError(f"Error from Ernie: {resp}")
+ lst.extend([i["embedding"] for i in resp["data"]])
+ return lst
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ List[float]: Embeddings for the text.
+ """
+
+ if not self.access_token:
+ self._refresh_access_token_with_lock()
+ resp = self._embedding({"input": [text]})
+ if resp.get("error_code"):
+ if resp.get("error_code") == 111:
+ self._refresh_access_token_with_lock()
+ resp = self._embedding({"input": [text]})
+ else:
+ raise ValueError(f"Error from Ernie: {resp}")
+ return resp["data"][0]["embedding"]
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Asynchronous Embed query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ List[float]: Embeddings for the text.
+ """
+
+ return await run_in_executor(None, self.embed_query, text)
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Asynchronous Embed search docs.
+
+ Args:
+ texts: The list of texts to embed
+
+ Returns:
+ List[List[float]]: List of embeddings, one for each text.
+ """
+
+ result = await asyncio.gather(*[self.aembed_query(text) for text in texts])
+
+ return list(result)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/fake.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bbfeeb45cd5e5935375469f2e9ae2110183df9b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/fake.py
@@ -0,0 +1,50 @@
+import hashlib
+from typing import List
+
+import numpy as np
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel
+
+
+class FakeEmbeddings(Embeddings, BaseModel):
+ """Fake embedding model."""
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self) -> List[float]:
+ return list(np.random.normal(size=self.size))
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ return [self._get_embedding() for _ in texts]
+
+ def embed_query(self, text: str) -> List[float]:
+ return self._get_embedding()
+
+
+class DeterministicFakeEmbedding(Embeddings, BaseModel):
+ """
+ Fake embedding model that always returns
+ the same embedding vector for the same text.
+ """
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self, seed: int) -> List[float]:
+ # set the seed for the random generator
+ np.random.seed(seed)
+ return list(np.random.normal(size=self.size))
+
+ @staticmethod
+ def _get_seed(text: str) -> int:
+ """
+ Get a seed for the random generator, using the hash of the text.
+ """
+ return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ return [self._get_embedding(seed=self._get_seed(_)) for _ in texts]
+
+ def embed_query(self, text: str) -> List[float]:
+ return self._get_embedding(seed=self._get_seed(text))
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/fastembed.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/fastembed.py
new file mode 100644
index 0000000000000000000000000000000000000000..d46f9210607e591786be4ed83c230d4fdf4873aa
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/fastembed.py
@@ -0,0 +1,152 @@
+import importlib
+import importlib.metadata
+from typing import Any, Dict, List, Literal, Optional, Sequence, cast
+
+import numpy as np
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import pre_init
+from pydantic import BaseModel, ConfigDict
+
+MIN_VERSION = "0.2.0"
+
+
+class FastEmbedEmbeddings(BaseModel, Embeddings):
+ """Qdrant FastEmbedding models.
+
+ FastEmbed is a lightweight, fast, Python library built for embedding generation.
+ See more documentation at:
+ * https://github.com/qdrant/fastembed/
+ * https://qdrant.github.io/fastembed/
+
+ To use this class, you must install the `fastembed` Python package.
+
+ `pip install fastembed`
+ Example:
+ from langchain_community.embeddings import FastEmbedEmbeddings
+ fastembed = FastEmbedEmbeddings()
+ """
+
+ model_name: str = "BAAI/bge-small-en-v1.5"
+ """Name of the FastEmbedding model to use
+ Defaults to "BAAI/bge-small-en-v1.5"
+ Find the list of supported models at
+ https://qdrant.github.io/fastembed/examples/Supported_Models/
+ """
+
+ max_length: int = 512
+ """The maximum number of tokens. Defaults to 512.
+ Unknown behavior for values > 512.
+ """
+
+ cache_dir: Optional[str] = None
+ """The path to the cache directory.
+ Defaults to `local_cache` in the parent directory
+ """
+
+ threads: Optional[int] = None
+ """The number of threads single onnxruntime session can use.
+ Defaults to None
+ """
+
+ doc_embed_type: Literal["default", "passage"] = "default"
+ """Type of embedding to use for documents
+ The available options are: "default" and "passage"
+ """
+
+ batch_size: int = 256
+ """Batch size for encoding. Higher values will use more memory, but be faster.
+ Defaults to 256.
+ """
+
+ parallel: Optional[int] = None
+ """If `>1`, parallel encoding is used, recommended for encoding of large datasets.
+ If `0`, use all available cores.
+ If `None`, don't use data-parallel processing, use default onnxruntime threading.
+ Defaults to `None`.
+ """
+
+ providers: Optional[Sequence[Any]] = None
+ """List of ONNX execution providers. Use `["CUDAExecutionProvider"]` to enable the
+ use of GPU when generating embeddings. This requires to install `fastembed-gpu`
+ instead of `fastembed`. See https://qdrant.github.io/fastembed/examples/FastEmbed_GPU
+ for more details.
+ Defaults to `None`.
+ """
+
+ model: Any = None # : :meta private:
+
+ model_config = ConfigDict(extra="allow", protected_namespaces=())
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that FastEmbed has been installed."""
+ model_name = values.get("model_name")
+ max_length = values.get("max_length")
+ cache_dir = values.get("cache_dir")
+ threads = values.get("threads")
+ providers = values.get("providers")
+ pkg_to_install = (
+ "fastembed-gpu"
+ if providers and "CUDAExecutionProvider" in providers
+ else "fastembed"
+ )
+
+ try:
+ fastembed = importlib.import_module("fastembed")
+
+ except ModuleNotFoundError:
+ raise ImportError(
+ "Could not import 'fastembed' Python package. "
+ f"Please install it with `pip install {pkg_to_install}`."
+ )
+
+ if importlib.metadata.version(pkg_to_install) < MIN_VERSION:
+ raise ImportError(
+ f"FastEmbedEmbeddings requires "
+ f'`pip install -U "{pkg_to_install}>={MIN_VERSION}"`.'
+ )
+
+ values["model"] = fastembed.TextEmbedding(
+ model_name=model_name,
+ max_length=max_length,
+ cache_dir=cache_dir,
+ threads=threads,
+ providers=providers,
+ )
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Generate embeddings for documents using FastEmbed.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ embeddings: List[np.ndarray]
+ if self.doc_embed_type == "passage":
+ embeddings = self.model.passage_embed(
+ texts, batch_size=self.batch_size, parallel=self.parallel
+ )
+ else:
+ embeddings = self.model.embed(
+ texts, batch_size=self.batch_size, parallel=self.parallel
+ )
+ return [cast(List[float], e.tolist()) for e in embeddings]
+
+ def embed_query(self, text: str) -> List[float]:
+ """Generate query embeddings using FastEmbed.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ query_embeddings: np.ndarray = next(
+ self.model.query_embed(
+ text, batch_size=self.batch_size, parallel=self.parallel
+ )
+ )
+ return cast(List[float], query_embeddings.tolist())
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/gigachat.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gigachat.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5b372c820055bc4a8099a5285c36b36cf440650
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gigachat.py
@@ -0,0 +1,195 @@
+from __future__ import annotations
+
+import logging
+from functools import cached_property
+from typing import Any, Dict, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import pre_init
+from langchain_core.utils.pydantic import get_fields
+from pydantic import BaseModel
+
+logger = logging.getLogger(__name__)
+
+MAX_BATCH_SIZE_CHARS = 1000000
+MAX_BATCH_SIZE_PARTS = 90
+
+
+@deprecated(
+ since="0.3.5",
+ removal="1.0",
+ alternative_import="langchain_gigachat.GigaChatEmbeddings",
+)
+class GigaChatEmbeddings(BaseModel, Embeddings):
+ """GigaChat Embeddings models.
+
+ Example:
+ .. code-block:: python
+ from langchain_community.embeddings.gigachat import GigaChatEmbeddings
+
+ embeddings = GigaChatEmbeddings(
+ credentials=..., scope=..., verify_ssl_certs=...
+ )
+ """
+
+ base_url: Optional[str] = None
+ """ Base API URL """
+ auth_url: Optional[str] = None
+ """ Auth URL """
+ credentials: Optional[str] = None
+ """ Auth Token """
+ scope: Optional[str] = None
+ """ Permission scope for access token """
+
+ access_token: Optional[str] = None
+ """ Access token for GigaChat """
+
+ model: Optional[str] = None
+ """Model name to use."""
+ user: Optional[str] = None
+ """ Username for authenticate """
+ password: Optional[str] = None
+ """ Password for authenticate """
+
+ timeout: Optional[float] = 600
+ """ Timeout for request. By default it works for long requests. """
+ verify_ssl_certs: Optional[bool] = None
+ """ Check certificates for all requests """
+
+ ca_bundle_file: Optional[str] = None
+ cert_file: Optional[str] = None
+ key_file: Optional[str] = None
+ key_file_password: Optional[str] = None
+ # Support for connection to GigaChat through SSL certificates
+
+ @cached_property
+ def _client(self) -> Any:
+ """Returns GigaChat API client"""
+ import gigachat
+
+ return gigachat.GigaChat(
+ base_url=self.base_url,
+ auth_url=self.auth_url,
+ credentials=self.credentials,
+ scope=self.scope,
+ access_token=self.access_token,
+ model=self.model,
+ user=self.user,
+ password=self.password,
+ timeout=self.timeout,
+ verify_ssl_certs=self.verify_ssl_certs,
+ ca_bundle_file=self.ca_bundle_file,
+ cert_file=self.cert_file,
+ key_file=self.key_file,
+ key_file_password=self.key_file_password,
+ )
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate authenticate data in environment and python package is installed."""
+ try:
+ import gigachat # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "Could not import gigachat python package. "
+ "Please install it with `pip install gigachat`."
+ )
+ fields = set(get_fields(cls).keys())
+ diff = set(values.keys()) - fields
+ if diff:
+ logger.warning(f"Extra fields {diff} in GigaChat class")
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed documents using a GigaChat embeddings models.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ result: List[List[float]] = []
+ size = 0
+ local_texts = []
+ embed_kwargs = {}
+ if self.model is not None:
+ embed_kwargs["model"] = self.model
+ for text in texts:
+ local_texts.append(text)
+ size += len(text)
+ if size > MAX_BATCH_SIZE_CHARS or len(local_texts) > MAX_BATCH_SIZE_PARTS:
+ for embedding in self._client.embeddings(
+ texts=local_texts, **embed_kwargs
+ ).data:
+ result.append(embedding.embedding)
+ size = 0
+ local_texts = []
+ # Call for last iteration
+ if local_texts:
+ for embedding in self._client.embeddings(
+ texts=local_texts, **embed_kwargs
+ ).data:
+ result.append(embedding.embedding)
+
+ return result
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed documents using a GigaChat embeddings models.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ result: List[List[float]] = []
+ size = 0
+ local_texts = []
+ embed_kwargs = {}
+ if self.model is not None:
+ embed_kwargs["model"] = self.model
+ for text in texts:
+ local_texts.append(text)
+ size += len(text)
+ if size > MAX_BATCH_SIZE_CHARS or len(local_texts) > MAX_BATCH_SIZE_PARTS:
+ embeddings = await self._client.aembeddings(
+ texts=local_texts, **embed_kwargs
+ )
+ for embedding in embeddings.data:
+ result.append(embedding.embedding)
+ size = 0
+ local_texts = []
+ # Call for last iteration
+ if local_texts:
+ embeddings = await self._client.aembeddings(
+ texts=local_texts, **embed_kwargs
+ )
+ for embedding in embeddings.data:
+ result.append(embedding.embedding)
+
+ return result
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed a query using a GigaChat embeddings models.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents(texts=[text])[0]
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Embed a query using a GigaChat embeddings models.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ docs = await self.aembed_documents(texts=[text])
+ return docs[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/google_palm.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/google_palm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d058bc46add0de24a83ad9cafe184a1f39355e40
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/google_palm.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from pydantic import BaseModel, ConfigDict
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _create_retry_decorator() -> Callable[[Any], Any]:
+ """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
+ import google.api_core.exceptions
+
+ multiplier = 2
+ min_seconds = 1
+ max_seconds = 60
+ max_retries = 10
+
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(max_retries),
+ wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),
+ retry=(
+ retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)
+ | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)
+ | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)
+ ),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+def embed_with_retry(
+ embeddings: GooglePalmEmbeddings, *args: Any, **kwargs: Any
+) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator()
+
+ @retry_decorator
+ def _embed_with_retry(*args: Any, **kwargs: Any) -> Any:
+ return embeddings.client.generate_embeddings(*args, **kwargs)
+
+ return _embed_with_retry(*args, **kwargs)
+
+
+class GooglePalmEmbeddings(BaseModel, Embeddings):
+ """Google's PaLM Embeddings APIs."""
+
+ client: Any
+ google_api_key: Optional[str]
+ model_name: str = "models/embedding-gecko-001"
+ """Model name to use."""
+ show_progress_bar: bool = False
+ """Whether to show a tqdm progress bar. Must have `tqdm` installed."""
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate api key, python package exists."""
+ google_api_key = get_from_dict_or_env(
+ values, "google_api_key", "GOOGLE_API_KEY"
+ )
+ try:
+ import google.generativeai as genai
+
+ genai.configure(api_key=google_api_key)
+ except ImportError:
+ raise ImportError("Could not import google.generativeai python package.")
+
+ values["client"] = genai
+
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ if self.show_progress_bar:
+ try:
+ from tqdm import tqdm
+
+ iter_ = tqdm(texts, desc="GooglePalmEmbeddings")
+ except ImportError:
+ logger.warning(
+ "Unable to show progress bar because tqdm could not be imported. "
+ "Please install with `pip install tqdm`."
+ )
+ iter_ = texts
+ else:
+ iter_ = texts
+ return [self.embed_query(text) for text in iter_]
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed query text."""
+ embedding = embed_with_retry(self, self.model_name, text)
+ return embedding["embedding"]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/gpt4all.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gpt4all.py
new file mode 100644
index 0000000000000000000000000000000000000000..5183cbb08bd84f9a28b00ecd84ed827c0ced4237
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gpt4all.py
@@ -0,0 +1,76 @@
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, model_validator
+
+
+class GPT4AllEmbeddings(BaseModel, Embeddings):
+ """GPT4All embedding models.
+
+ To use, you should have the gpt4all python package installed
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import GPT4AllEmbeddings
+
+ model_name = "all-MiniLM-L6-v2.gguf2.f16.gguf"
+ gpt4all_kwargs = {'allow_download': 'True'}
+ embeddings = GPT4AllEmbeddings(
+ model_name=model_name,
+ gpt4all_kwargs=gpt4all_kwargs
+ )
+ """
+
+ model_name: Optional[str] = None
+ n_threads: Optional[int] = None
+ device: Optional[str] = "cpu"
+ gpt4all_kwargs: Optional[dict] = {}
+ client: Any #: :meta private:
+
+ model_config = ConfigDict(protected_namespaces=())
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that GPT4All library is installed."""
+ try:
+ from gpt4all import Embed4All
+
+ values["client"] = Embed4All(
+ model_name=values.get("model_name"),
+ n_threads=values.get("n_threads"),
+ device=values.get("device"),
+ **(values.get("gpt4all_kwargs") or {}),
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import gpt4all library. "
+ "Please install the gpt4all library to "
+ "use this embedding model: pip install gpt4all"
+ )
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed a list of documents using GPT4All.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+
+ embeddings = [self.client.embed(text) for text in texts]
+ return [list(map(float, e)) for e in embeddings]
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed a query using GPT4All.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/gradient_ai.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gradient_ai.py
new file mode 100644
index 0000000000000000000000000000000000000000..697e7a30a3f723797bedaedbb8b1de8a382bc597
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/gradient_ai.py
@@ -0,0 +1,173 @@
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from packaging.version import parse
+from pydantic import BaseModel, ConfigDict, model_validator
+from typing_extensions import Self
+
+__all__ = ["GradientEmbeddings"]
+
+
+class GradientEmbeddings(BaseModel, Embeddings):
+ """Gradient.ai Embedding models.
+
+ GradientLLM is a class to interact with Embedding Models on gradient.ai
+
+ To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your
+ API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace,
+ or alternatively provide them as keywords to the constructor of this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import GradientEmbeddings
+ GradientEmbeddings(
+ model="bge-large",
+ gradient_workspace_id="12345614fc0_workspace",
+ gradient_access_token="gradientai-access_token",
+ )
+ """
+
+ model: str
+ "Underlying gradient.ai model id."
+
+ gradient_workspace_id: Optional[str] = None
+ "Underlying gradient.ai workspace_id."
+
+ gradient_access_token: Optional[str] = None
+ """gradient.ai API Token, which can be generated by going to
+ https://auth.gradient.ai/select-workspace
+ and selecting "Access tokens" under the profile drop-down.
+ """
+
+ gradient_api_url: str = "https://api.gradient.ai/api"
+ """Endpoint URL to use."""
+
+ query_prompt_for_retrieval: Optional[str] = None
+ """Query pre-prompt"""
+
+ client: Any = None #: :meta private:
+ """Gradient client."""
+
+ # LLM call kwargs
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+
+ values["gradient_access_token"] = get_from_dict_or_env(
+ values, "gradient_access_token", "GRADIENT_ACCESS_TOKEN"
+ )
+ values["gradient_workspace_id"] = get_from_dict_or_env(
+ values, "gradient_workspace_id", "GRADIENT_WORKSPACE_ID"
+ )
+
+ values["gradient_api_url"] = get_from_dict_or_env(
+ values,
+ "gradient_api_url",
+ "GRADIENT_API_URL",
+ default="https://api.gradient.ai/api",
+ )
+ return values
+
+ @model_validator(mode="after")
+ def post_init(self) -> Self:
+ try:
+ import gradientai
+ except ImportError:
+ raise ImportError(
+ 'GradientEmbeddings requires `pip install -U "gradientai>=1.4.0"`.'
+ )
+
+ if parse(gradientai.__version__) < parse("1.4.0"):
+ raise ImportError(
+ 'GradientEmbeddings requires `pip install -U "gradientai>=1.4.0"`.'
+ )
+
+ gradient = gradientai.Gradient(
+ access_token=self.gradient_access_token,
+ workspace_id=self.gradient_workspace_id,
+ host=self.gradient_api_url,
+ )
+ self.client = gradient.get_embeddings_model(slug=self.model)
+ return self
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to Gradient's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ inputs = [{"input": text} for text in texts]
+
+ result = self.client.embed(inputs=inputs).embeddings
+
+ return [e.embedding for e in result]
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Async call out to Gradient's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ inputs = [{"input": text} for text in texts]
+
+ result = (await self.client.aembed(inputs=inputs)).embeddings
+
+ return [e.embedding for e in result]
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Gradient's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ query = (
+ f"{self.query_prompt_for_retrieval} {text}"
+ if self.query_prompt_for_retrieval
+ else text
+ )
+ return self.embed_documents([query])[0]
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Async call out to Gradient's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ query = (
+ f"{self.query_prompt_for_retrieval} {text}"
+ if self.query_prompt_for_retrieval
+ else text
+ )
+ embeddings = await self.aembed_documents([query])
+ return embeddings[0]
+
+
+class TinyAsyncGradientEmbeddingClient: #: :meta private:
+ """Deprecated, TinyAsyncGradientEmbeddingClient was removed.
+
+ This class is just for backwards compatibility with older versions
+ of langchain_community.
+ It might be entirely removed in the future.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ raise ValueError("Deprecated,TinyAsyncGradientEmbeddingClient was removed.")
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..7afe57c9f5128f45c53328b5572db04a18191603
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface.py
@@ -0,0 +1,493 @@
+import warnings
+from typing import Any, Dict, List, Optional
+
+import requests
+from langchain_core._api import deprecated, warn_deprecated
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field, SecretStr
+
+DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
+DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-large"
+DEFAULT_BGE_MODEL = "BAAI/bge-large-en"
+DEFAULT_EMBED_INSTRUCTION = "Represent the document for retrieval: "
+DEFAULT_QUERY_INSTRUCTION = (
+ "Represent the question for retrieving supporting documents: "
+)
+DEFAULT_QUERY_BGE_INSTRUCTION_EN = (
+ "Represent this question for searching relevant passages: "
+)
+DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:"
+
+
+@deprecated(
+ since="0.2.2",
+ removal="1.0",
+ alternative_import="langchain_huggingface.HuggingFaceEmbeddings",
+)
+class HuggingFaceEmbeddings(BaseModel, Embeddings):
+ """HuggingFace sentence_transformers embedding models.
+
+ To use, you should have the ``sentence_transformers`` python package installed.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import HuggingFaceEmbeddings
+
+ model_name = "sentence-transformers/all-mpnet-base-v2"
+ model_kwargs = {'device': 'cpu'}
+ encode_kwargs = {'normalize_embeddings': False}
+ hf = HuggingFaceEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs
+ )
+ """
+
+ client: Any = None #: :meta private:
+ model_name: str = DEFAULT_MODEL_NAME
+ """Model name to use."""
+ cache_folder: Optional[str] = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the Sentence Transformer model, such as `device`,
+ `prompts`, `default_prompt_name`, `revision`, `trust_remote_code`, or `token`.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer"""
+ encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method of the Sentence
+ Transformer model, such as `prompt_name`, `prompt`, `batch_size`, `precision`,
+ `normalize_embeddings`, and more.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode"""
+ multi_process: bool = False
+ """Run encode() on multiple GPUs."""
+ show_progress: bool = False
+ """Whether to show a progress bar."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+
+ if "model_name" not in kwargs:
+ since = "0.2.16"
+ removal = "0.4.0"
+ warn_deprecated(
+ since=since,
+ removal=removal,
+ message=f"Default values for {self.__class__.__name__}.model_name"
+ + f" were deprecated in LangChain {since} and will be removed in"
+ + f" {removal}. Explicitly pass a model_name to the"
+ + f" {self.__class__.__name__} constructor instead.",
+ )
+
+ try:
+ import sentence_transformers
+
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import sentence_transformers python package. "
+ "Please install it with `pip install sentence-transformers`."
+ ) from exc
+
+ self.client = sentence_transformers.SentenceTransformer(
+ self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
+ )
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using a HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ import sentence_transformers
+
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
+ if self.multi_process:
+ pool = self.client.start_multi_process_pool()
+ embeddings = self.client.encode_multi_process(texts, pool)
+ sentence_transformers.SentenceTransformer.stop_multi_process_pool(pool)
+ else:
+ embeddings = self.client.encode(
+ texts, show_progress_bar=self.show_progress, **self.encode_kwargs
+ )
+
+ return embeddings.tolist()
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents([text])[0]
+
+
+@deprecated(
+ since="0.2.2",
+ removal="1.0",
+ alternative_import="langchain_huggingface.HuggingFaceEmbeddings",
+)
+class HuggingFaceInstructEmbeddings(BaseModel, Embeddings):
+ """Wrapper around sentence_transformers embedding models.
+
+ To use, you should have the ``sentence_transformers``
+ and ``InstructorEmbedding`` python packages installed.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import HuggingFaceInstructEmbeddings
+
+ model_name = "hkunlp/instructor-large"
+ model_kwargs = {'device': 'cpu'}
+ encode_kwargs = {'normalize_embeddings': True}
+ hf = HuggingFaceInstructEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs
+ )
+ """
+
+ client: Any = None #: :meta private:
+ model_name: str = DEFAULT_INSTRUCT_MODEL
+ """Model name to use."""
+ cache_folder: Optional[str] = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the model."""
+ encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method of the model."""
+ embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
+ """Instruction to use for embedding documents."""
+ query_instruction: str = DEFAULT_QUERY_INSTRUCTION
+ """Instruction to use for embedding query."""
+ show_progress: bool = False
+ """Whether to show a progress bar."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+
+ if "model_name" not in kwargs:
+ since = "0.2.16"
+ removal = "0.4.0"
+ warn_deprecated(
+ since=since,
+ removal=removal,
+ message=f"Default values for {self.__class__.__name__}.model_name"
+ + f" were deprecated in LangChain {since} and will be removed in"
+ + f" {removal}. Explicitly pass a model_name to the"
+ + f" {self.__class__.__name__} constructor instead.",
+ )
+
+ try:
+ from InstructorEmbedding import INSTRUCTOR
+
+ self.client = INSTRUCTOR(
+ self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
+ )
+ except ImportError as e:
+ raise ImportError("Dependencies for InstructorEmbedding not found.") from e
+
+ if "show_progress_bar" in self.encode_kwargs:
+ warn_deprecated(
+ since="0.2.5",
+ removal="1.0",
+ name="encode_kwargs['show_progress_bar']",
+ alternative=f"the show_progress method on {self.__class__.__name__}",
+ )
+ if self.show_progress:
+ warnings.warn(
+ "Both encode_kwargs['show_progress_bar'] and show_progress are set;"
+ "encode_kwargs['show_progress_bar'] takes precedence"
+ )
+ self.show_progress = self.encode_kwargs.pop("show_progress_bar")
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using a HuggingFace instruct model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ instruction_pairs = [[self.embed_instruction, text] for text in texts]
+ embeddings = self.client.encode(
+ instruction_pairs,
+ show_progress_bar=self.show_progress,
+ **self.encode_kwargs,
+ )
+ return embeddings.tolist()
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a HuggingFace instruct model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ instruction_pair = [self.query_instruction, text]
+ embedding = self.client.encode(
+ [instruction_pair],
+ show_progress_bar=self.show_progress,
+ **self.encode_kwargs,
+ )[0]
+ return embedding.tolist()
+
+
+@deprecated(
+ since="0.2.2",
+ removal="1.0",
+ alternative_import="langchain_huggingface.HuggingFaceEmbeddings",
+)
+class HuggingFaceBgeEmbeddings(BaseModel, Embeddings):
+ """HuggingFace sentence_transformers embedding models.
+
+ To use, you should have the ``sentence_transformers`` python package installed.
+ To use Nomic, make sure the version of ``sentence_transformers`` >= 2.3.0.
+
+ Bge Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
+
+ model_name = "BAAI/bge-large-en-v1.5"
+ model_kwargs = {'device': 'cpu'}
+ encode_kwargs = {'normalize_embeddings': True}
+ hf = HuggingFaceBgeEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs
+ )
+ Nomic Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
+
+ model_name = "nomic-ai/nomic-embed-text-v1"
+ model_kwargs = {
+ 'device': 'cpu',
+ 'trust_remote_code':True
+ }
+ encode_kwargs = {'normalize_embeddings': True}
+ hf = HuggingFaceBgeEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs,
+ query_instruction = "search_query:",
+ embed_instruction = "search_document:"
+ )
+ """
+
+ client: Any = None #: :meta private:
+ model_name: str = DEFAULT_BGE_MODEL
+ """Model name to use."""
+ cache_folder: Optional[str] = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the model."""
+ encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method of the model."""
+ query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN
+ """Instruction to use for embedding query."""
+ embed_instruction: str = ""
+ """Instruction to use for embedding document."""
+ show_progress: bool = False
+ """Whether to show a progress bar."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+
+ if "model_name" not in kwargs:
+ since = "0.2.5"
+ removal = "0.4.0"
+ warn_deprecated(
+ since=since,
+ removal=removal,
+ message=f"Default values for {self.__class__.__name__}.model_name"
+ + f" were deprecated in LangChain {since} and will be removed in"
+ + f" {removal}. Explicitly pass a model_name to the"
+ + f" {self.__class__.__name__} constructor instead.",
+ )
+
+ try:
+ import sentence_transformers
+
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import sentence_transformers python package. "
+ "Please install it with `pip install sentence-transformers`."
+ ) from exc
+ extra_model_kwargs = [
+ "torch_dtype",
+ "attn_implementation",
+ "provider",
+ "file_name",
+ "export",
+ ]
+ extra_model_kwargs_dict = {
+ k: self.model_kwargs.pop(k)
+ for k in extra_model_kwargs
+ if k in self.model_kwargs
+ }
+ self.client = sentence_transformers.SentenceTransformer(
+ self.model_name,
+ cache_folder=self.cache_folder,
+ **self.model_kwargs,
+ model_kwargs=extra_model_kwargs_dict,
+ )
+
+ if "-zh" in self.model_name:
+ self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH
+
+ if "show_progress_bar" in self.encode_kwargs:
+ warn_deprecated(
+ since="0.2.5",
+ removal="1.0",
+ name="encode_kwargs['show_progress_bar']",
+ alternative=f"the show_progress method on {self.__class__.__name__}",
+ )
+ if self.show_progress:
+ warnings.warn(
+ "Both encode_kwargs['show_progress_bar'] and show_progress are set;"
+ "encode_kwargs['show_progress_bar'] takes precedence"
+ )
+ self.show_progress = self.encode_kwargs.pop("show_progress_bar")
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using a HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ texts = [self.embed_instruction + t.replace("\n", " ") for t in texts]
+ embeddings = self.client.encode(
+ texts, show_progress_bar=self.show_progress, **self.encode_kwargs
+ )
+ return embeddings.tolist()
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ text = text.replace("\n", " ")
+ embedding = self.client.encode(
+ self.query_instruction + text,
+ show_progress_bar=self.show_progress,
+ **self.encode_kwargs,
+ )
+ return embedding.tolist()
+
+
+@deprecated(
+ since="0.2.2",
+ removal="1.0",
+ alternative_import="langchain_huggingface.HuggingFaceEndpointEmbeddings",
+)
+class HuggingFaceInferenceAPIEmbeddings(BaseModel, Embeddings):
+ """Embed texts using the HuggingFace API.
+
+ Requires a HuggingFace Inference API key and a model name.
+ """
+
+ api_key: SecretStr
+ """Your API key for the HuggingFace Inference API."""
+ model_name: str = "sentence-transformers/all-MiniLM-L6-v2"
+ """The name of the model to use for text embeddings."""
+ api_url: Optional[str] = None
+ """Custom inference endpoint url. None for using default public url."""
+ additional_headers: Dict[str, str] = {}
+ """Pass additional headers to the requests library if needed."""
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ @property
+ def _api_url(self) -> str:
+ return self.api_url or self._default_api_url
+
+ @property
+ def _default_api_url(self) -> str:
+ return (
+ "https://api-inference.huggingface.co"
+ "/pipeline"
+ "/feature-extraction"
+ f"/{self.model_name}"
+ )
+
+ @property
+ def _headers(self) -> dict:
+ return {
+ "Authorization": f"Bearer {self.api_key.get_secret_value()}",
+ **self.additional_headers,
+ }
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Get the embeddings for a list of texts.
+
+ Args:
+ texts (Documents): A list of texts to get embeddings for.
+
+ Returns:
+ Embedded texts as List[List[float]], where each inner List[float]
+ corresponds to a single input text.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import (
+ HuggingFaceInferenceAPIEmbeddings,
+ )
+
+ hf_embeddings = HuggingFaceInferenceAPIEmbeddings(
+ api_key="your_api_key",
+ model_name="sentence-transformers/all-MiniLM-l6-v2"
+ )
+ texts = ["Hello, world!", "How are you?"]
+ hf_embeddings.embed_documents(texts)
+ """ # noqa: E501
+ response = requests.post(
+ self._api_url,
+ headers=self._headers,
+ json={
+ "inputs": texts,
+ "options": {"wait_for_model": True, "use_cache": True},
+ },
+ )
+ return response.json()
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface_hub.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1a1fac3721df83b6424b08b8abe23bd1887869c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/huggingface_hub.py
@@ -0,0 +1,159 @@
+import json
+from typing import Any, Dict, List, Optional
+
+from langchain_core._api import deprecated
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, ConfigDict, model_validator
+from typing_extensions import Self
+
+DEFAULT_MODEL = "sentence-transformers/all-mpnet-base-v2"
+VALID_TASKS = ("feature-extraction",)
+
+
+@deprecated(
+ since="0.2.2",
+ removal="1.0",
+ alternative_import="langchain_huggingface.HuggingFaceEndpointEmbeddings",
+)
+class HuggingFaceHubEmbeddings(BaseModel, Embeddings):
+ """HuggingFaceHub embedding models.
+
+ To use, you should have the ``huggingface_hub`` python package installed, and the
+ environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import HuggingFaceHubEmbeddings
+ model = "sentence-transformers/all-mpnet-base-v2"
+ hf = HuggingFaceHubEmbeddings(
+ model=model,
+ task="feature-extraction",
+ huggingfacehub_api_token="my-api-key",
+ )
+ """
+
+ client: Any = None #: :meta private:
+ async_client: Any = None #: :meta private:
+ model: Optional[str] = None
+ """Model name to use."""
+ repo_id: Optional[str] = None
+ """Huggingfacehub repository id, for backward compatibility."""
+ task: Optional[str] = "feature-extraction"
+ """Task to call the model with."""
+ model_kwargs: Optional[dict] = None
+ """Keyword arguments to pass to the model."""
+
+ huggingfacehub_api_token: Optional[str] = None
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ huggingfacehub_api_token = get_from_dict_or_env(
+ values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
+ )
+
+ try:
+ from huggingface_hub import AsyncInferenceClient, InferenceClient
+
+ if values.get("model"):
+ values["repo_id"] = values["model"]
+ elif values.get("repo_id"):
+ values["model"] = values["repo_id"]
+ else:
+ values["model"] = DEFAULT_MODEL
+ values["repo_id"] = DEFAULT_MODEL
+
+ client = InferenceClient(
+ model=values["model"],
+ token=huggingfacehub_api_token,
+ )
+
+ async_client = AsyncInferenceClient(
+ model=values["model"],
+ token=huggingfacehub_api_token,
+ )
+
+ values["client"] = client
+ values["async_client"] = async_client
+
+ except ImportError:
+ raise ImportError(
+ "Could not import huggingface_hub python package. "
+ "Please install it with `pip install huggingface_hub`."
+ )
+ return values
+
+ @model_validator(mode="after")
+ def post_init(self) -> Self:
+ """Post init validation for the class."""
+ if self.task not in VALID_TASKS:
+ raise ValueError(
+ f"Got invalid task {self.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ return self
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ # api doc: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/embed
+ responses = self.client.post(
+ json={"inputs": texts, **_model_kwargs}, task=self.task
+ )
+ return json.loads(responses.decode())
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ responses = await self.async_client.post(
+ json={"inputs": texts, "parameters": _model_kwargs}, task=self.task
+ )
+ return json.loads(responses.decode())
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ response = self.embed_documents([text])[0]
+ return response
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ response = (await self.aembed_documents([text]))[0]
+ return response
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/hunyuan.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/hunyuan.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d0570a0ae2c63379f869717f5257797b5fb9f9c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/hunyuan.py
@@ -0,0 +1,124 @@
+import json
+from typing import Any, Dict, List, Literal, Optional, Type
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.runnables.config import run_in_executor
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import BaseModel, Field, SecretStr, model_validator
+
+
+class HunyuanEmbeddings(Embeddings, BaseModel):
+ """Tencent Hunyuan embedding models API by Tencent.
+
+ For more information, see https://cloud.tencent.com/document/product/1729
+ """
+
+ hunyuan_secret_id: Optional[SecretStr] = Field(alias="secret_id", default=None)
+ """Hunyuan Secret ID"""
+ hunyuan_secret_key: Optional[SecretStr] = Field(alias="secret_key", default=None)
+ """Hunyuan Secret Key"""
+ region: Literal["ap-guangzhou", "ap-beijing"] = "ap-guangzhou"
+ """The region of hunyuan service."""
+ embedding_ctx_length: int = 1024
+ """The max embedding context length of hunyuan embedding (defaults to 1024)."""
+ show_progress_bar: bool = False
+ """Show progress bar when embedding. Default is False."""
+
+ client: Any = Field(default=None, exclude=True)
+ """The tencentcloud client."""
+ request_cls: Optional[Type] = Field(default=None, exclude=True)
+ """The request class of tencentcloud sdk."""
+
+ @model_validator(mode="before")
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["hunyuan_secret_id"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "hunyuan_secret_id",
+ "HUNYUAN_SECRET_ID",
+ )
+ )
+ values["hunyuan_secret_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "hunyuan_secret_key",
+ "HUNYUAN_SECRET_KEY",
+ )
+ )
+
+ try:
+ from tencentcloud.common.credential import Credential
+ from tencentcloud.common.profile.client_profile import ClientProfile
+ from tencentcloud.hunyuan.v20230901.hunyuan_client import HunyuanClient
+ from tencentcloud.hunyuan.v20230901.models import GetEmbeddingRequest
+ except ImportError:
+ raise ImportError(
+ "Could not import tencentcloud sdk python package. Please install it "
+ 'with `pip install "tencentcloud-sdk-python>=3.0.1139"`.'
+ )
+
+ client_profile = ClientProfile()
+ client_profile.httpProfile.pre_conn_pool_size = 3
+
+ credential = Credential(
+ values["hunyuan_secret_id"].get_secret_value(),
+ values["hunyuan_secret_key"].get_secret_value(),
+ )
+
+ values["request_cls"] = GetEmbeddingRequest
+
+ values["client"] = HunyuanClient(credential, values["region"], client_profile)
+ return values
+
+ def _embed_text(self, text: str) -> List[float]:
+ if self.request_cls is None:
+ raise AssertionError("Request class is not initialized.")
+ request = self.request_cls()
+ request.Input = text
+
+ response = self.client.GetEmbedding(request)
+
+ _response: Dict[str, Any] = json.loads(response.to_json_string())
+
+ data: Optional[List[Dict[str, Any]]] = _response.get("Data")
+ if not data:
+ raise RuntimeError("Occur hunyuan embedding error: Data is empty")
+
+ embedding = data[0].get("Embedding")
+ if not embedding:
+ raise RuntimeError("Occur hunyuan embedding error: Embedding is empty")
+
+ return embedding
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed search docs."""
+ embeddings = []
+ if self.show_progress_bar:
+ try:
+ from tqdm import tqdm
+ except ImportError as e:
+ raise ImportError(
+ "Package tqdm must be installed if show_progress_bar=True. "
+ "Please install with 'pip install tqdm' or set "
+ "show_progress_bar=False."
+ ) from e
+ _iter = tqdm(iterable=texts, desc="Hunyuan Embedding")
+ else:
+ _iter = texts
+ for text in _iter:
+ embeddings.append(self.embed_query(text))
+
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Embed query text."""
+ return self._embed_text(text)
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Asynchronous Embed search docs."""
+ return await run_in_executor(None, self.embed_documents, texts)
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Asynchronous Embed query text."""
+ return await run_in_executor(None, self.embed_query, text)
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc41250b54f700160f6e2f06c6afc7c1ad723e25
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity.py
@@ -0,0 +1,324 @@
+"""written under MIT Licence, Michael Feil 2023."""
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+from typing import Any, Callable, Dict, List, Optional, Tuple
+
+import aiohttp
+import numpy as np
+import requests
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, ConfigDict, model_validator
+
+__all__ = ["InfinityEmbeddings"]
+
+
+class InfinityEmbeddings(BaseModel, Embeddings):
+ """Self-hosted embedding models for `infinity` package.
+
+ See https://github.com/michaelfeil/infinity
+ This also works for text-embeddings-inference and other
+ self-hosted openai-compatible servers.
+
+ Infinity is a package to interact with Embedding Models on https://github.com/michaelfeil/infinity
+
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import InfinityEmbeddings
+ InfinityEmbeddings(
+ model="BAAI/bge-small",
+ infinity_api_url="http://localhost:7997",
+ )
+ """
+
+ model: str
+ "Underlying Infinity model id."
+
+ infinity_api_url: str = "http://localhost:7997"
+ """Endpoint URL to use."""
+
+ client: Any = None #: :meta private:
+ """Infinity client."""
+
+ # LLM call kwargs
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+
+ values["infinity_api_url"] = get_from_dict_or_env(
+ values, "infinity_api_url", "INFINITY_API_URL"
+ )
+
+ values["client"] = TinyAsyncOpenAIInfinityEmbeddingClient(
+ host=values["infinity_api_url"],
+ )
+ return values
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Call out to Infinity's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ embeddings = self.client.embed(
+ model=self.model,
+ texts=texts,
+ )
+ return embeddings
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Async call out to Infinity's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ embeddings = await self.client.aembed(
+ model=self.model,
+ texts=texts,
+ )
+ return embeddings
+
+ def embed_query(self, text: str) -> List[float]:
+ """Call out to Infinity's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ return self.embed_documents([text])[0]
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Async call out to Infinity's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ embeddings = await self.aembed_documents([text])
+ return embeddings[0]
+
+
+class TinyAsyncOpenAIInfinityEmbeddingClient: #: :meta private:
+ """Helper tool to embed Infinity.
+
+ It is not a part of Langchain's stable API,
+ direct use discouraged.
+
+ Example:
+ .. code-block:: python
+
+
+ mini_client = TinyAsyncInfinityEmbeddingClient(
+ )
+ embeds = mini_client.embed(
+ model="BAAI/bge-small",
+ text=["doc1", "doc2"]
+ )
+ # or
+ embeds = await mini_client.aembed(
+ model="BAAI/bge-small",
+ text=["doc1", "doc2"]
+ )
+
+ """
+
+ def __init__(
+ self,
+ host: str = "http://localhost:7797/v1",
+ aiosession: Optional[aiohttp.ClientSession] = None,
+ ) -> None:
+ self.host = host
+ self.aiosession = aiosession
+
+ if self.host is None or len(self.host) < 3:
+ raise ValueError(" param `host` must be set to a valid url")
+ self._batch_size = 128
+
+ @staticmethod
+ def _permute(
+ texts: List[str], sorter: Callable = len
+ ) -> Tuple[List[str], Callable]:
+ """Sort texts in ascending order, and
+ delivers a lambda expr, which can sort a same length list
+ https://github.com/UKPLab/sentence-transformers/blob/
+ c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156
+
+ Args:
+ texts (List[str]): _description_
+ sorter (Callable, optional): _description_. Defaults to len.
+
+ Returns:
+ Tuple[List[str], Callable]: _description_
+
+ Example:
+ ```
+ texts = ["one","three","four"]
+ perm_texts, undo = self._permute(texts)
+ texts == undo(perm_texts)
+ ```
+ """
+
+ if len(texts) == 1:
+ # special case query
+ return texts, lambda t: t
+ length_sorted_idx = np.argsort([-sorter(sen) for sen in texts])
+ texts_sorted = [texts[idx] for idx in length_sorted_idx]
+
+ return texts_sorted, lambda unsorted_embeddings: [ # E731
+ unsorted_embeddings[idx] for idx in np.argsort(length_sorted_idx)
+ ]
+
+ def _batch(self, texts: List[str]) -> List[List[str]]:
+ """
+ splits Lists of text parts into batches of size max `self._batch_size`
+ When encoding vector database,
+
+ Args:
+ texts (List[str]): List of sentences
+ self._batch_size (int, optional): max batch size of one request.
+
+ Returns:
+ List[List[str]]: Batches of List of sentences
+ """
+ if len(texts) == 1:
+ # special case query
+ return [texts]
+ batches = []
+ for start_index in range(0, len(texts), self._batch_size):
+ batches.append(texts[start_index : start_index + self._batch_size])
+ return batches
+
+ @staticmethod
+ def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]:
+ if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1:
+ # special case query
+ return batch_of_texts[0]
+ texts = []
+ for sublist in batch_of_texts:
+ texts.extend(sublist)
+ return texts
+
+ def _kwargs_post_request(self, model: str, texts: List[str]) -> Dict[str, Any]:
+ """Build the kwargs for the Post request, used by sync
+
+ Args:
+ model (str): _description_
+ texts (List[str]): _description_
+
+ Returns:
+ Dict[str, Collection[str]]: _description_
+ """
+ return dict(
+ url=f"{self.host}/embeddings",
+ headers={
+ # "accept": "application/json",
+ "content-type": "application/json",
+ },
+ json=dict(
+ input=texts,
+ model=model,
+ ),
+ )
+
+ def _sync_request_embed(
+ self, model: str, batch_texts: List[str]
+ ) -> List[List[float]]:
+ response = requests.post(
+ **self._kwargs_post_request(model=model, texts=batch_texts)
+ )
+ if response.status_code != 200:
+ raise Exception(
+ f"Infinity returned an unexpected response with status "
+ f"{response.status_code}: {response.text}"
+ )
+ return [e["embedding"] for e in response.json()["data"]]
+
+ def embed(self, model: str, texts: List[str]) -> List[List[float]]:
+ """call the embedding of model
+
+ Args:
+ model (str): to embedding model
+ texts (List[str]): List of sentences to embed.
+
+ Returns:
+ List[List[float]]: List of vectors for each sentence
+ """
+ perm_texts, unpermute_func = self._permute(texts)
+ perm_texts_batched = self._batch(perm_texts)
+
+ # Request
+ map_args = (
+ self._sync_request_embed,
+ [model] * len(perm_texts_batched),
+ perm_texts_batched,
+ )
+ if len(perm_texts_batched) == 1:
+ embeddings_batch_perm = list(map(*map_args))
+ else:
+ with ThreadPoolExecutor(32) as p:
+ embeddings_batch_perm = list(p.map(*map_args))
+
+ embeddings_perm = self._unbatch(embeddings_batch_perm)
+ embeddings = unpermute_func(embeddings_perm)
+ return embeddings
+
+ async def _async_request(
+ self, session: aiohttp.ClientSession, kwargs: Dict[str, Any]
+ ) -> List[List[float]]:
+ async with session.post(**kwargs) as response:
+ if response.status != 200:
+ raise Exception(
+ f"Infinity returned an unexpected response with status "
+ f"{response.status}: {response.text}"
+ )
+ embedding = (await response.json())["data"]
+ return [e["embedding"] for e in embedding]
+
+ async def aembed(self, model: str, texts: List[str]) -> List[List[float]]:
+ """call the embedding of model, async method
+
+ Args:
+ model (str): to embedding model
+ texts (List[str]): List of sentences to embed.
+
+ Returns:
+ List[List[float]]: List of vectors for each sentence
+ """
+ perm_texts, unpermute_func = self._permute(texts)
+ perm_texts_batched = self._batch(perm_texts)
+
+ # Request
+ async with aiohttp.ClientSession(
+ trust_env=True, connector=aiohttp.TCPConnector(limit=32)
+ ) as session:
+ embeddings_batch_perm = await asyncio.gather(
+ *[
+ self._async_request(
+ session=session,
+ kwargs=self._kwargs_post_request(model=model, texts=t),
+ )
+ for t in perm_texts_batched
+ ]
+ )
+
+ embeddings_perm = self._unbatch(embeddings_batch_perm)
+ embeddings = unpermute_func(embeddings_perm)
+ return embeddings
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity_local.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity_local.py
new file mode 100644
index 0000000000000000000000000000000000000000..22e15b017a04b705abd391f625563494d34a2b44
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/infinity_local.py
@@ -0,0 +1,157 @@
+"""written under MIT Licence, Michael Feil 2023."""
+
+import asyncio
+from logging import getLogger
+from typing import Any, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, model_validator
+from typing_extensions import Self
+
+__all__ = ["InfinityEmbeddingsLocal"]
+
+logger = getLogger(__name__)
+
+
+class InfinityEmbeddingsLocal(BaseModel, Embeddings):
+ """Optimized Infinity embedding models.
+
+ https://github.com/michaelfeil/infinity
+ This class deploys a local Infinity instance to embed text.
+ The class requires async usage.
+
+ Infinity is a class to interact with Embedding Models on https://github.com/michaelfeil/infinity
+
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import InfinityEmbeddingsLocal
+ async with InfinityEmbeddingsLocal(
+ model="BAAI/bge-small-en-v1.5",
+ revision=None,
+ device="cpu",
+ ) as embedder:
+ embeddings = await engine.aembed_documents(["text1", "text2"])
+ """
+
+ model: str
+ "Underlying model id from huggingface, e.g. BAAI/bge-small-en-v1.5"
+
+ revision: Optional[str] = None
+ "Model version, the commit hash from huggingface"
+
+ batch_size: int = 32
+ "Internal batch size for inference, e.g. 32"
+
+ device: str = "auto"
+ "Device to use for inference, e.g. 'cpu' or 'cuda', or 'mps'"
+
+ backend: str = "torch"
+ "Backend for inference, e.g. 'torch' (recommended for ROCm/Nvidia)"
+ " or 'optimum' for onnx/tensorrt"
+
+ model_warmup: bool = True
+ "Warmup the model with the max batch size."
+
+ engine: Any = None #: :meta private:
+ """Infinity's AsyncEmbeddingEngine."""
+
+ # LLM call kwargs
+ model_config = ConfigDict(
+ extra="forbid",
+ protected_namespaces=(),
+ )
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that api key and python package exists in environment."""
+
+ try:
+ from infinity_emb import AsyncEmbeddingEngine
+ except ImportError:
+ raise ImportError(
+ "Please install the "
+ "`pip install 'infinity_emb[optimum,torch]>=0.0.24'` "
+ "package to use the InfinityEmbeddingsLocal."
+ )
+ self.engine = AsyncEmbeddingEngine(
+ model_name_or_path=self.model,
+ device=self.device,
+ revision=self.revision,
+ model_warmup=self.model_warmup,
+ batch_size=self.batch_size,
+ engine=self.backend,
+ )
+ return self
+
+ async def __aenter__(self) -> None:
+ """start the background worker.
+ recommended usage is with the async with statement.
+
+ async with InfinityEmbeddingsLocal(
+ model="BAAI/bge-small-en-v1.5",
+ revision=None,
+ device="cpu",
+ ) as embedder:
+ embeddings = await engine.aembed_documents(["text1", "text2"])
+ """
+ await self.engine.__aenter__()
+
+ async def __aexit__(self, *args: Any) -> None:
+ """stop the background worker,
+ required to free references to the pytorch model."""
+ await self.engine.__aexit__(*args)
+
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Async call out to Infinity's embedding endpoint.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ if not self.engine.running:
+ logger.warning(
+ "Starting Infinity engine on the fly. This is not recommended."
+ "Please start the engine before using it."
+ )
+ async with self:
+ # spawning threadpool for multithreaded encode, tokenization
+ embeddings, _ = await self.engine.embed(texts)
+ # stopping threadpool on exit
+ logger.warning("Stopped infinity engine after usage.")
+ else:
+ embeddings, _ = await self.engine.embed(texts)
+ return embeddings
+
+ async def aembed_query(self, text: str) -> List[float]:
+ """Async call out to Infinity's embedding endpoint.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ embeddings = await self.aembed_documents([text])
+ return embeddings[0]
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """
+ This method is async only.
+ """
+ logger.warning(
+ "This method is async only. "
+ "Please use the async version `await aembed_documents`."
+ )
+ return asyncio.run(self.aembed_documents(texts))
+
+ def embed_query(self, text: str) -> List[float]:
+ """ """
+ logger.warning(
+ "This method is async only."
+ " Please use the async version `await aembed_query`."
+ )
+ return asyncio.run(self.aembed_query(text))
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/ipex_llm.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ipex_llm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8022616f22d41ab77a9526bb5564e71b3919af6d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/ipex_llm.py
@@ -0,0 +1,137 @@
+# This file is adapted from
+# https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/embeddings/huggingface.py
+
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field
+
+DEFAULT_BGE_MODEL = "BAAI/bge-small-en-v1.5"
+DEFAULT_QUERY_BGE_INSTRUCTION_EN = (
+ "Represent this question for searching relevant passages: "
+)
+DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:"
+
+
+class IpexLLMBgeEmbeddings(BaseModel, Embeddings):
+ """Wrapper around the BGE embedding model
+ with IPEX-LLM optimizations on Intel CPUs and GPUs.
+
+ To use, you should have the ``ipex-llm``
+ and ``sentence_transformers`` package installed. Refer to
+ `here `_
+ for installation on Intel CPU.
+
+ Example on Intel CPU:
+ .. code-block:: python
+
+ from langchain_community.embeddings import IpexLLMBgeEmbeddings
+
+ embedding_model = IpexLLMBgeEmbeddings(
+ model_name="BAAI/bge-large-en-v1.5",
+ model_kwargs={},
+ encode_kwargs={"normalize_embeddings": True},
+ )
+
+ Refer to
+ `here `_
+ for installation on Intel GPU.
+
+ Example on Intel GPU:
+ .. code-block:: python
+
+ from langchain_community.embeddings import IpexLLMBgeEmbeddings
+
+ embedding_model = IpexLLMBgeEmbeddings(
+ model_name="BAAI/bge-large-en-v1.5",
+ model_kwargs={"device": "xpu"},
+ encode_kwargs={"normalize_embeddings": True},
+ )
+ """
+
+ client: Any = None #: :meta private:
+ model_name: str = DEFAULT_BGE_MODEL
+ """Model name to use."""
+ cache_folder: Optional[str] = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the model."""
+ encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method of the model."""
+ query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN
+ """Instruction to use for embedding query."""
+ embed_instruction: str = ""
+ """Instruction to use for embedding document."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+ try:
+ import sentence_transformers
+ from ipex_llm.transformers.convert import _optimize_post, _optimize_pre
+
+ except ImportError as exc:
+ base_url = (
+ "https://python.langchain.com/v0.1/docs/integrations/text_embedding/"
+ )
+ raise ImportError(
+ "Could not import ipex_llm or sentence_transformers. "
+ f"Please refer to {base_url}/ipex_llm/ "
+ "for install required packages on Intel CPU. "
+ f"And refer to {base_url}/ipex_llm_gpu/ "
+ "for install required packages on Intel GPU. "
+ ) from exc
+
+ # Set "cpu" as default device
+ if "device" not in self.model_kwargs:
+ self.model_kwargs["device"] = "cpu"
+
+ if self.model_kwargs["device"] not in ["cpu", "xpu"]:
+ raise ValueError(
+ "IpexLLMBgeEmbeddings currently only supports device to be "
+ f"'cpu' or 'xpu', but you have: {self.model_kwargs['device']}."
+ )
+
+ self.client = sentence_transformers.SentenceTransformer(
+ self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
+ )
+
+ # Add ipex-llm optimizations
+ self.client = _optimize_pre(self.client)
+ self.client = _optimize_post(self.client)
+ if self.model_kwargs["device"] == "xpu":
+ self.client = self.client.half().to("xpu")
+
+ if "-zh" in self.model_name:
+ self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Compute doc embeddings using a HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+ """
+ texts = [self.embed_instruction + t.replace("\n", " ") for t in texts]
+ embeddings = self.client.encode(texts, **self.encode_kwargs)
+ return embeddings.tolist()
+
+ def embed_query(self, text: str) -> List[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+ """
+ text = text.replace("\n", " ")
+ embedding = self.client.encode(
+ self.query_instruction + text, **self.encode_kwargs
+ )
+ return embedding.tolist()
diff --git a/python/user_packages/Python313/site-packages/langchain_community/embeddings/itrex.py b/python/user_packages/Python313/site-packages/langchain_community/embeddings/itrex.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f9a8e0731bfd04ba5b0a6dce4e81b6df6e666a1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_community/embeddings/itrex.py
@@ -0,0 +1,214 @@
+import importlib.util
+import os
+from typing import Any, Dict, List, Optional
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict
+
+
+class QuantizedBgeEmbeddings(BaseModel, Embeddings):
+ """Leverage Itrex runtime to unlock the performance of compressed NLP models.
+
+ Please ensure that you have installed intel-extension-for-transformers.
+
+ Input:
+ model_name: str = Model name.
+ max_seq_len: int = The maximum sequence length for tokenization. (default 512)
+ pooling_strategy: str =
+ "mean" or "cls", pooling strategy for the final layer. (default "mean")
+ query_instruction: Optional[str] =
+ An instruction to add to the query before embedding. (default None)
+ document_instruction: Optional[str] =
+ An instruction to add to each document before embedding. (default None)
+ padding: Optional[bool] =
+ Whether to add padding during tokenization or not. (default True)
+ model_kwargs: Optional[Dict] =
+ Parameters to add to the model during initialization. (default {})
+ encode_kwargs: Optional[Dict] =
+ Parameters to add during the embedding forward pass. (default {})
+ onnx_file_name: Optional[str] =
+ File name of onnx optimized model which is exported by itrex.
+ (default "int8-model.onnx")
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.embeddings import QuantizedBgeEmbeddings
+
+ model_name = "Intel/bge-small-en-v1.5-sts-int8-static-inc"
+ encode_kwargs = {'normalize_embeddings': True}
+ hf = QuantizedBgeEmbeddings(
+ model_name,
+ encode_kwargs=encode_kwargs,
+ query_instruction="Represent this sentence for searching relevant passages: "
+ )
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ model_name: str,
+ *,
+ max_seq_len: int = 512,
+ pooling_strategy: str = "mean", # "mean" or "cls"
+ query_instruction: Optional[str] = None,
+ document_instruction: Optional[str] = None,
+ padding: bool = True,
+ model_kwargs: Optional[Dict] = None,
+ encode_kwargs: Optional[Dict] = None,
+ onnx_file_name: Optional[str] = "int8-model.onnx",
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(**kwargs)
+
+ # check sentence_transformers python package
+ if importlib.util.find_spec("intel_extension_for_transformers") is None:
+ raise ImportError(
+ "Could not import intel_extension_for_transformers python package. "
+ "Please install it with "
+ "`pip install -U intel-extension-for-transformers`."
+ )
+
+ # check torch python package
+ if importlib.util.find_spec("torch") is None:
+ raise ImportError(
+ "Could not import torch python package. "
+ "Please install it with `pip install -U torch`."
+ )
+
+ # check onnx python package
+ if importlib.util.find_spec("onnx") is None:
+ raise ImportError(
+ "Could not import onnx python package. "
+ "Please install it with `pip install -U onnx`."
+ )
+
+ self.model_name_or_path = model_name
+ self.max_seq_len = max_seq_len
+ self.pooling = pooling_strategy
+ self.padding = padding
+ self.encode_kwargs = encode_kwargs or {}
+ self.model_kwargs = model_kwargs or {}
+
+ self.normalize = self.encode_kwargs.get("normalize_embeddings", False)
+ self.batch_size = self.encode_kwargs.get("batch_size", 32)
+
+ self.query_instruction = query_instruction
+ self.document_instruction = document_instruction
+ self.onnx_file_name = onnx_file_name
+
+ self.load_model()
+
+ def load_model(self) -> None:
+ from huggingface_hub import hf_hub_download
+ from intel_extension_for_transformers.transformers import AutoModel
+ from transformers import AutoConfig, AutoTokenizer
+
+ self.hidden_size = AutoConfig.from_pretrained(
+ self.model_name_or_path
+ ).hidden_size
+ self.transformer_tokenizer = AutoTokenizer.from_pretrained(
+ self.model_name_or_path,
+ )
+ onnx_model_path = os.path.join(self.model_name_or_path, self.onnx_file_name) # type: ignore[arg-type]
+ if not os.path.exists(onnx_model_path):
+ onnx_model_path = hf_hub_download(
+ self.model_name_or_path, filename=self.onnx_file_name
+ )
+ self.transformer_model = AutoModel.from_pretrained(
+ onnx_model_path, use_embedding_runtime=True
+ )
+
+ model_config = ConfigDict(
+ extra="allow",
+ protected_namespaces=(),
+ )
+
+ def _embed(self, inputs: Any) -> Any:
+ import torch
+
+ engine_input = [value for value in inputs.values()]
+ outputs = self.transformer_model.generate(engine_input)
+ if "last_hidden_state:0" in outputs:
+ last_hidden_state = outputs["last_hidden_state:0"]
+ else:
+ last_hidden_state = [out for out in outputs.values()][0]
+ last_hidden_state = torch.tensor(last_hidden_state).reshape(
+ inputs["input_ids"].shape[0], inputs["input_ids"].shape[1], self.hidden_size
+ )
+ if self.pooling == "mean":
+ emb = self._mean_pooling(last_hidden_state, inputs["attention_mask"])
+ elif self.pooling == "cls":
+ emb = self._cls_pooling(last_hidden_state)
+ else:
+ raise ValueError("pooling method no supported")
+
+ if self.normalize:
+ emb = torch.nn.functional.normalize(emb, p=2, dim=1)
+ return emb
+
+ @staticmethod
+ def _cls_pooling(last_hidden_state: Any) -> Any:
+ return last_hidden_state[:, 0]
+
+ @staticmethod
+ def _mean_pooling(last_hidden_state: Any, attention_mask: Any) -> Any:
+ try:
+ import torch
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import torch, please install with `pip install -U torch`."
+ ) from e
+ input_mask_expanded = (
+ attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
+ )
+ sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)
+ sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
+ return sum_embeddings / sum_mask
+
+ def _embed_text(self, texts: List[str]) -> List[List[float]]:
+ inputs = self.transformer_tokenizer(
+ texts,
+ max_length=self.max_seq_len,
+ truncation=True,
+ padding=self.padding,
+ return_tensors="pt",
+ )
+ return self._embed(inputs).tolist()
+
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
+ """Embed a list of text documents using the Optimized Embedder model.
+
+ Input:
+ texts: List[str] = List of text documents to embed.
+ Output:
+ List[List[float]] = The embeddings of each text document.
+ """
+ try:
+ import pandas as pd
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import pandas, please install with `pip install -U pandas`."
+ ) from e
+ docs = [
+ self.document_instruction + d if self.document_instruction else d
+ for d in texts
+ ]
+
+ # group into batches
+ text_list_df = pd.DataFrame(docs, columns=["texts"]).reset_index()
+
+ # assign each example with its batch
+ text_list_df["batch_index"] = text_list_df["index"] // self.batch_size
+
+ # create groups
+ batches = list(text_list_df.groupby(["batch_index"])["texts"].apply(list))
+
+ vectors = []
+ for batch in batches:
+ vectors += self._embed_text(batch)
+ return vectors
+
+ def embed_query(self, text: str) -> List[float]:
+ if self.query_instruction:
+ text = self.query_instruction + text
+ return self._embed_text([text])[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db2d3cdcb8d27ed7fc347b565763ade4ed9a870a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/_import_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/_import_utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dac932e942356c48d65d4a91eace15ded1fde0b9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/_import_utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/agents.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/agents.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5f3bee2f6960af285f42ed733ac5d9ac8b0194a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/agents.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/caches.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/caches.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67352943d34b61bb7315ce457d582795a8a2def1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/caches.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_history.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_history.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df940e3506cac86191ead35e383074007c9b6aa9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_history.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_loaders.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_loaders.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f2f9400db46d7c933b50fed6b3d27c7c542fad1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_loaders.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_sessions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_sessions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a41a45dfdfe34cd2dd4d6a5c86cbde08b3757ab
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/chat_sessions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/cross_encoders.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/cross_encoders.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7dadfdca6e7871254942ce737d5794b35b608d4c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/cross_encoders.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/env.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/env.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e0c40196e700b003bf0769a08b48c975bdd2a4e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/env.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/exceptions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2c89e3005f392340ae2ec73afdfe84135649324
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/exceptions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/globals.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/globals.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b583f2f58228cf5e603fa4efbbc7743dcaca57c9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/globals.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/prompt_values.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/prompt_values.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7ac027177077be9d0e27b8790f4ef1698d8e28a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/prompt_values.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/rate_limiters.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/rate_limiters.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0daf6a18136c0358aa82a660a7e972f052309ca
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/rate_limiters.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/retrievers.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/retrievers.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3be59006798ee61eceeff2499c4f75b406445f95
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/retrievers.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/stores.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/stores.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..260395684248f1a8317fb0dce4d9b2f63e090ecf
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/stores.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/structured_query.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/structured_query.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72898effd123cf8eff3f0b1f61b6029009594fa2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/structured_query.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/sys_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/sys_info.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..761606e46169cd5b8a7a2f13d65b270f8bc7b2a8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/sys_info.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/version.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cefe1b48f5d7e3579a3915e18201e552c898a0e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/__pycache__/version.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/_api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1028cd366bb906c26f8c4dfe04081a2aba1fcda2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_api/__init__.py
@@ -0,0 +1,87 @@
+"""Helper functions for managing the LangChain API.
+
+This module is only relevant for LangChain developers, not for users.
+
+!!! warning
+
+ This module and its submodules are for internal use only. Do not use them in your
+ own code. We may change the API at any time with no warning.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core._api.beta_decorator import (
+ LangChainBetaWarning,
+ beta,
+ suppress_langchain_beta_warning,
+ surface_langchain_beta_warnings,
+ )
+ from langchain_core._api.deprecation import (
+ LangChainDeprecationWarning,
+ deprecated,
+ suppress_langchain_deprecation_warning,
+ surface_langchain_deprecation_warnings,
+ warn_deprecated,
+ )
+ from langchain_core._api.path import as_import_path, get_relative_path
+
+__all__ = (
+ "LangChainBetaWarning",
+ "LangChainDeprecationWarning",
+ "as_import_path",
+ "beta",
+ "deprecated",
+ "get_relative_path",
+ "suppress_langchain_beta_warning",
+ "suppress_langchain_deprecation_warning",
+ "surface_langchain_beta_warnings",
+ "surface_langchain_deprecation_warnings",
+ "warn_deprecated",
+)
+
+_dynamic_imports = {
+ "LangChainBetaWarning": "beta_decorator",
+ "beta": "beta_decorator",
+ "suppress_langchain_beta_warning": "beta_decorator",
+ "surface_langchain_beta_warnings": "beta_decorator",
+ "as_import_path": "path",
+ "get_relative_path": "path",
+ "LangChainDeprecationWarning": "deprecation",
+ "deprecated": "deprecation",
+ "surface_langchain_deprecation_warnings": "deprecation",
+ "suppress_langchain_deprecation_warning": "deprecation",
+ "warn_deprecated": "deprecation",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ """Dynamically import and return an attribute from a submodule.
+
+ This function enables lazy loading of API functions from submodules, reducing
+ initial import time and circular dependency issues.
+
+ Args:
+ attr_name: Name of the attribute to import.
+
+ Returns:
+ The imported attribute object.
+
+ Raises:
+ AttributeError: If the attribute is not a valid dynamic import.
+ """
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ """Return a list of available attributes for this module.
+
+ Returns:
+ List of attribute names that can be imported from this module.
+ """
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c58a27ae7732e18ed5ee79c303b388e63c730b28
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90c151dcece03f16efe24e989dc8592bbb3e3cfe
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b9189b1a60c769517938a0707a7e1a5846fafb8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/internal.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/internal.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5fafc544d6fa6dc2f0e92d40988d80d8e55dab0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/internal.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/path.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/path.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae47d4cf7e099891a7c71d9082d8d85597c64124
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_api/__pycache__/path.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/beta_decorator.py b/python/user_packages/Python313/site-packages/langchain_core/_api/beta_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..94671a112249319a7742188786060aed12d8c59e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_api/beta_decorator.py
@@ -0,0 +1,253 @@
+"""Helper functions for marking parts of the LangChain API as beta.
+
+This module was loosely adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
+module.
+
+!!! warning
+
+ This module is for internal use only. Do not use it in your own code. We may change
+ the API at any time with no warning.
+"""
+
+import contextlib
+import functools
+import inspect
+import warnings
+from collections.abc import Callable, Generator
+from typing import Any, TypeVar, cast
+
+from langchain_core._api.internal import is_caller_internal
+
+
+class LangChainBetaWarning(DeprecationWarning):
+ """A class for issuing beta warnings for LangChain users."""
+
+
+# PUBLIC API
+
+
+T = TypeVar("T", bound=Callable[..., Any] | type)
+
+
+def beta(
+ *,
+ message: str = "",
+ name: str = "",
+ obj_type: str = "",
+ addendum: str = "",
+) -> Callable[[T], T]:
+ """Decorator to mark a function, a class, or a property as beta.
+
+ When marking a classmethod, a staticmethod, or a property, the `@beta` decorator
+ should go *under* `@classmethod` and `@staticmethod` (i.e., `beta` should directly
+ decorate the underlying callable), but *over* `@property`.
+
+ When marking a class `C` intended to be used as a base class in a multiple
+ inheritance hierarchy, `C` *must* define an `__init__` method (if `C` instead
+ inherited its `__init__` from its own base class, then `@beta` would mess up
+ `__init__` inheritance when installing its own (annotation-emitting) `C.__init__`).
+
+ Args:
+ message: Override the default beta message.
+
+ The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and
+ %(removal)s format specifiers will be replaced by the values of the
+ respective arguments passed to this function.
+ name: The name of the beta object.
+ obj_type: The object type being beta.
+ addendum: Additional text appended directly to the final message.
+
+ Returns:
+ A decorator which can be used to mark functions or classes as beta.
+
+ Example:
+ ```python
+ @beta
+ def the_function_to_annotate():
+ pass
+ ```
+ """
+
+ def beta(
+ obj: T,
+ *,
+ _obj_type: str = obj_type,
+ _name: str = name,
+ _message: str = message,
+ _addendum: str = addendum,
+ ) -> T:
+ """Implementation of the decorator returned by `beta`."""
+
+ def emit_warning() -> None:
+ """Emit the warning."""
+ warn_beta(
+ message=_message,
+ name=_name,
+ obj_type=_obj_type,
+ addendum=_addendum,
+ )
+
+ warned = False
+
+ def warning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Wrapper for the original wrapped callable that emits a warning.
+
+ Args:
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The return value of the function being wrapped.
+ """
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(*args, **kwargs)
+
+ async def awarning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Same as warning_emitting_wrapper, but for async functions."""
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return await wrapped(*args, **kwargs)
+
+ if isinstance(obj, type):
+ if not _obj_type:
+ _obj_type = "class"
+ wrapped = obj.__init__ # type: ignore[misc]
+ _name = _name or obj.__qualname__
+ old_doc = obj.__doc__
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the annotation of a class."""
+ # Can't set new_doc on some extension objects.
+ with contextlib.suppress(AttributeError):
+ obj.__doc__ = new_doc
+
+ def warn_if_direct_instance(
+ self: Any, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Warn that the class is in beta."""
+ nonlocal warned
+ if not warned and type(self) is obj and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(self, *args, **kwargs)
+
+ obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
+ warn_if_direct_instance
+ )
+ return obj
+
+ elif isinstance(obj, property):
+ if not _obj_type:
+ _obj_type = "attribute"
+ wrapped = None
+ _name = _name or obj.fget.__qualname__
+ old_doc = obj.__doc__
+
+ def _fget(instance: Any) -> Any:
+ if instance is not None:
+ emit_warning()
+ return obj.fget(instance)
+
+ def _fset(instance: Any, value: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ obj.fset(instance, value)
+
+ def _fdel(instance: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ obj.fdel(instance)
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> Any:
+ """Finalize the property."""
+ return property(fget=_fget, fset=_fset, fdel=_fdel, doc=new_doc)
+
+ else:
+ _name = _name or obj.__qualname__
+ if not _obj_type:
+ # edge case: when a function is within another function
+ # within a test, this will call it a "method" not a "function"
+ _obj_type = "function" if "." not in _name else "method"
+ wrapped = obj
+ old_doc = wrapped.__doc__
+
+ def finalize(wrapper: Callable[..., Any], new_doc: str, /) -> T:
+ """Wrap the wrapped function using the wrapper and update the docstring.
+
+ Args:
+ wrapper: The wrapper function.
+ new_doc: The new docstring.
+
+ Returns:
+ The wrapped function.
+ """
+ wrapper = functools.wraps(wrapped)(wrapper)
+ wrapper.__doc__ = new_doc
+ return cast("T", wrapper)
+
+ old_doc = inspect.cleandoc(old_doc or "").strip("\n") or ""
+ components = [message, addendum]
+ details = " ".join([component.strip() for component in components if component])
+ new_doc = f".. beta::\n {details}\n\n{old_doc}\n"
+
+ if inspect.iscoroutinefunction(obj):
+ return finalize(awarning_emitting_wrapper, new_doc)
+ return finalize(warning_emitting_wrapper, new_doc)
+
+ return beta
+
+
+@contextlib.contextmanager
+def suppress_langchain_beta_warning() -> Generator[None, None, None]:
+ """Context manager to suppress `LangChainDeprecationWarning`."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LangChainBetaWarning)
+ yield
+
+
+def warn_beta(
+ *,
+ message: str = "",
+ name: str = "",
+ obj_type: str = "",
+ addendum: str = "",
+) -> None:
+ """Display a standardized beta annotation.
+
+ Args:
+ message: Override the default beta message.
+
+ The %(name)s, %(obj_type)s, %(addendum)s format specifiers will be replaced
+ by the values of the respective arguments passed to this function.
+ name: The name of the annotated object.
+ obj_type: The object type being annotated.
+ addendum: Additional text appended directly to the final message.
+ """
+ if not message:
+ message = ""
+
+ if obj_type:
+ message += f"The {obj_type} `{name}`"
+ else:
+ message += f"`{name}`"
+
+ message += " is in beta. It is actively being worked on, so the API may change."
+
+ if addendum:
+ message += f" {addendum}"
+
+ warning = LangChainBetaWarning(message)
+ warnings.warn(warning, category=LangChainBetaWarning, stacklevel=4)
+
+
+def surface_langchain_beta_warnings() -> None:
+ """Unmute LangChain beta warnings."""
+ warnings.filterwarnings(
+ "default",
+ category=LangChainBetaWarning,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/deprecation.py b/python/user_packages/Python313/site-packages/langchain_core/_api/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccc31d6b9a5fcff4a2ee6f325c11009338951190
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_api/deprecation.py
@@ -0,0 +1,617 @@
+"""Helper functions for deprecating parts of the LangChain API.
+
+This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
+module.
+
+!!! warning
+
+ This module is for internal use only. Do not use it in your own code. We may change
+ the API at any time with no warning.
+"""
+
+import contextlib
+import functools
+import inspect
+import sys
+import warnings
+from collections.abc import Callable, Generator
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ParamSpec,
+ TypeGuard,
+ TypeVar,
+ cast,
+)
+
+from pydantic.fields import FieldInfo
+
+from langchain_core._api.internal import is_caller_internal
+
+if TYPE_CHECKING:
+ from pydantic.v1.fields import FieldInfo as FieldInfoV1
+
+
+def _is_pydantic_v1_field_info(obj: Any) -> TypeGuard["FieldInfoV1"]:
+ """Check if `obj` is a `pydantic.v1.fields.FieldInfo` without forcing import.
+
+ Importing `pydantic.v1` emits a `UserWarning` on Python 3.14+. Skipping the
+ import entirely when no caller has constructed a v1 `FieldInfo` keeps that
+ warning out of `langchain_core`'s import path. If a caller did construct one,
+ `pydantic.v1.fields` is already in `sys.modules` and isinstance is safe.
+ """
+ mod = sys.modules.get("pydantic.v1.fields")
+ if mod is None:
+ return False
+ return isinstance(obj, mod.FieldInfo)
+
+
+def _build_deprecation_message(
+ *,
+ alternative: str = "",
+ alternative_import: str = "",
+) -> str:
+ """Build a simple deprecation message for `__deprecated__` attribute.
+
+ Args:
+ alternative: An alternative API name.
+ alternative_import: A fully qualified import path for the alternative.
+
+ Returns:
+ A deprecation message string for IDE/type checker display.
+ """
+ if alternative_import:
+ return f"Use {alternative_import} instead."
+ if alternative:
+ return f"Use {alternative} instead."
+ return "Deprecated."
+
+
+class LangChainDeprecationWarning(DeprecationWarning):
+ """A class for issuing deprecation warnings for LangChain users."""
+
+
+class LangChainPendingDeprecationWarning(PendingDeprecationWarning):
+ """A class for issuing deprecation warnings for LangChain users."""
+
+
+# PUBLIC API
+
+
+# Bound is `Any` (not `FieldInfoV1`) because importing `pydantic.v1` at module
+# scope emits a `UserWarning` on Python 3.14+; v1 `FieldInfo` support is handled
+# at runtime via `_is_pydantic_v1_field_info`.
+T = TypeVar("T", bound=type | Callable[..., Any] | Any)
+
+
+def _validate_deprecation_params(
+ removal: str,
+ alternative: str,
+ alternative_import: str,
+ *,
+ pending: bool,
+) -> None:
+ """Validate the deprecation parameters."""
+ if pending and removal:
+ msg = "A pending deprecation cannot have a scheduled removal"
+ raise ValueError(msg)
+ if alternative and alternative_import:
+ msg = "Cannot specify both alternative and alternative_import"
+ raise ValueError(msg)
+
+ if alternative_import and "." not in alternative_import:
+ msg = (
+ "alternative_import must be a fully qualified module path. Got "
+ f" {alternative_import}"
+ )
+ raise ValueError(msg)
+
+
+def deprecated(
+ since: str,
+ *,
+ message: str = "",
+ name: str = "",
+ alternative: str = "",
+ alternative_import: str = "",
+ pending: bool = False,
+ obj_type: str = "",
+ addendum: str = "",
+ removal: str = "",
+ package: str = "",
+) -> Callable[[T], T]:
+ """Decorator to mark a function, a class, or a property as deprecated.
+
+ When deprecating a classmethod, a staticmethod, or a property, the `@deprecated`
+ decorator should go *under* `@classmethod` and `@staticmethod` (i.e., `deprecated`
+ should directly decorate the underlying callable), but *over* `@property`.
+
+ When deprecating a class `C` intended to be used as a base class in a multiple
+ inheritance hierarchy, `C` *must* define an `__init__` method (if `C` instead
+ inherited its `__init__` from its own base class, then `@deprecated` would mess up
+ `__init__` inheritance when installing its own (deprecation-emitting) `C.__init__`).
+
+ Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to
+ 'class' if decorating a class, 'attribute' if decorating a property, and 'function'
+ otherwise.
+
+ Args:
+ since: The release at which this API became deprecated.
+ message: Override the default deprecation message.
+
+ The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,
+ `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the
+ values of the respective arguments passed to this function.
+ name: The name of the deprecated object.
+ alternative: An alternative API that the user may use in place of the deprecated
+ API.
+
+ The deprecation warning will tell the user about this alternative if
+ provided.
+ alternative_import: An alternative import that the user may use instead.
+ pending: If `True`, uses a `PendingDeprecationWarning` instead of a
+ `DeprecationWarning`.
+
+ Cannot be used together with removal.
+ obj_type: The object type being deprecated.
+ addendum: Additional text appended directly to the final message.
+ removal: The expected removal version.
+
+ With the default (an empty string), no removal version is shown in the
+ warning message.
+
+ Cannot be used together with pending.
+ package: The package of the deprecated object.
+
+ Returns:
+ A decorator to mark a function or class as deprecated.
+
+ Example:
+ ```python
+ @deprecated("1.4.0")
+ def the_function_to_deprecate():
+ pass
+ ```
+ """
+ _validate_deprecation_params(
+ removal, alternative, alternative_import, pending=pending
+ )
+
+ def deprecate(
+ obj: T,
+ *,
+ _obj_type: str = obj_type,
+ _name: str = name,
+ _message: str = message,
+ _alternative: str = alternative,
+ _alternative_import: str = alternative_import,
+ _pending: bool = pending,
+ _addendum: str = addendum,
+ _package: str = package,
+ ) -> T:
+ """Implementation of the decorator returned by `deprecated`."""
+
+ def emit_warning() -> None:
+ """Emit the warning."""
+ warn_deprecated(
+ since,
+ message=_message,
+ name=_name,
+ alternative=_alternative,
+ alternative_import=_alternative_import,
+ pending=_pending,
+ obj_type=_obj_type,
+ addendum=_addendum,
+ removal=removal,
+ package=_package,
+ )
+
+ warned = False
+
+ def warning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Wrapper for the original wrapped callable that emits a warning.
+
+ Args:
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The return value of the function being wrapped.
+ """
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(*args, **kwargs)
+
+ async def awarning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Same as warning_emitting_wrapper, but for async functions."""
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return await wrapped(*args, **kwargs)
+
+ _package = _package or obj.__module__.split(".")[0].replace("_", "-")
+
+ if isinstance(obj, type):
+ if not _obj_type:
+ _obj_type = "class"
+ wrapped = obj.__init__ # type: ignore[misc]
+ _name = _name or obj.__qualname__
+ old_doc = obj.__doc__
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the deprecation of a class."""
+ # Can't set new_doc on some extension objects.
+ with contextlib.suppress(AttributeError):
+ obj.__doc__ = new_doc
+
+ def warn_if_direct_instance(
+ self: Any, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Warn that the class is in beta."""
+ nonlocal warned
+ if not warned and type(self) is obj and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(self, *args, **kwargs)
+
+ obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
+ warn_if_direct_instance
+ )
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ obj.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return obj
+
+ elif _is_pydantic_v1_field_info(obj):
+ wrapped = None
+ if not _obj_type:
+ _obj_type = "attribute"
+ if not _name:
+ msg = f"Field {obj} must have a name to be deprecated."
+ raise ValueError(msg)
+ old_doc = obj.description
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ from pydantic.v1.fields import FieldInfo as FieldInfoV1 # noqa: PLC0415
+
+ return cast(
+ "T",
+ FieldInfoV1(
+ default=obj.default,
+ default_factory=obj.default_factory,
+ description=new_doc,
+ alias=obj.alias,
+ exclude=obj.exclude,
+ ),
+ )
+
+ elif isinstance(obj, FieldInfo):
+ wrapped = None
+ if not _obj_type:
+ _obj_type = "attribute"
+ if not _name:
+ msg = f"Field {obj} must have a name to be deprecated."
+ raise ValueError(msg)
+ old_doc = obj.description
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ return cast(
+ "T",
+ FieldInfo(
+ default=obj.default,
+ default_factory=obj.default_factory,
+ description=new_doc,
+ alias=obj.alias,
+ exclude=obj.exclude,
+ ),
+ )
+
+ elif isinstance(obj, property):
+ if not _obj_type:
+ _obj_type = "attribute"
+ wrapped = None
+ _name = _name or cast("type | Callable", obj.fget).__qualname__
+ old_doc = obj.__doc__
+
+ class _DeprecatedProperty(property):
+ """A deprecated property."""
+
+ def __init__(
+ self,
+ fget: Callable[[Any], Any] | None = None,
+ fset: Callable[[Any, Any], None] | None = None,
+ fdel: Callable[[Any], None] | None = None,
+ doc: str | None = None,
+ ) -> None:
+ super().__init__(fget, fset, fdel, doc)
+ self.__orig_fget = fget
+ self.__orig_fset = fset
+ self.__orig_fdel = fdel
+
+ def __get__(self, instance: Any, owner: type | None = None) -> Any:
+ if instance is not None or owner is not None:
+ emit_warning()
+ if self.fget is None:
+ return None
+ return self.fget(instance)
+
+ def __set__(self, instance: Any, value: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ if self.fset is not None:
+ self.fset(instance, value)
+
+ def __delete__(self, instance: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ if self.fdel is not None:
+ self.fdel(instance)
+
+ def __set_name__(self, owner: type | None, set_name: str) -> None:
+ nonlocal _name
+ if _name == "":
+ _name = set_name
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the property."""
+ prop = _DeprecatedProperty(
+ fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
+ )
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ prop.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return cast("T", prop)
+
+ else:
+ _name = _name or cast("type | Callable", obj).__qualname__
+ if not _obj_type:
+ # edge case: when a function is within another function
+ # within a test, this will call it a "method" not a "function"
+ _obj_type = "function" if "." not in _name else "method"
+ wrapped = obj
+ old_doc = wrapped.__doc__
+
+ def finalize(wrapper: Callable[..., Any], new_doc: str, /) -> T:
+ """Wrap the wrapped function using the wrapper and update the docstring.
+
+ Args:
+ wrapper: The wrapper function.
+ new_doc: The new docstring.
+
+ Returns:
+ The wrapped function.
+ """
+ wrapper = functools.wraps(wrapped)(wrapper)
+ wrapper.__doc__ = new_doc
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ wrapper.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return cast("T", wrapper)
+
+ old_doc = inspect.cleandoc(old_doc or "").strip("\n")
+
+ # old_doc can be None
+ if not old_doc:
+ old_doc = ""
+
+ # Modify the docstring to include a deprecation notice.
+ if (
+ _alternative
+ and _alternative.rsplit(".", maxsplit=1)[-1].lower()
+ == _alternative.rsplit(".", maxsplit=1)[-1]
+ ) or _alternative:
+ _alternative = f"`{_alternative}`"
+
+ if (
+ _alternative_import
+ and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
+ == _alternative_import.rsplit(".", maxsplit=1)[-1]
+ ) or _alternative_import:
+ _alternative_import = f"`{_alternative_import}`"
+
+ components = [
+ _message,
+ f"Use {_alternative} instead." if _alternative else "",
+ f"Use {_alternative_import} instead." if _alternative_import else "",
+ _addendum,
+ ]
+ details = " ".join([component.strip() for component in components if component])
+ package = _package or (
+ _name.split(".")[0].replace("_", "-") if "." in _name else None
+ )
+ if removal:
+ if removal.startswith("1.") and package and package.startswith("langchain"):
+ removal_str = f"It will not be removed until {package}=={removal}."
+ else:
+ removal_str = f"It will be removed in {package}=={removal}."
+ else:
+ removal_str = ""
+ new_doc = f"""\
+!!! deprecated "{since} {details} {removal_str}"
+
+{old_doc}\
+"""
+
+ if inspect.iscoroutinefunction(obj):
+ return finalize(awarning_emitting_wrapper, new_doc)
+ return finalize(warning_emitting_wrapper, new_doc)
+
+ return deprecate
+
+
+@contextlib.contextmanager
+def suppress_langchain_deprecation_warning() -> Generator[None, None, None]:
+ """Context manager to suppress `LangChainDeprecationWarning`."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LangChainDeprecationWarning)
+ warnings.simplefilter("ignore", LangChainPendingDeprecationWarning)
+ yield
+
+
+def warn_deprecated(
+ since: str,
+ *,
+ message: str = "",
+ name: str = "",
+ alternative: str = "",
+ alternative_import: str = "",
+ pending: bool = False,
+ obj_type: str = "",
+ addendum: str = "",
+ removal: str = "",
+ package: str = "",
+) -> None:
+ """Display a standardized deprecation.
+
+ Args:
+ since: The release at which this API became deprecated.
+ message: Override the default deprecation message.
+
+ The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,
+ `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the
+ values of the respective arguments passed to this function.
+ name: The name of the deprecated object.
+ alternative: An alternative API that the user may use in place of the
+ deprecated API.
+
+ The deprecation warning will tell the user about this alternative if
+ provided.
+ alternative_import: An alternative import that the user may use instead.
+ pending: If `True`, uses a `PendingDeprecationWarning` instead of a
+ `DeprecationWarning`.
+
+ Cannot be used together with removal.
+ obj_type: The object type being deprecated.
+ addendum: Additional text appended directly to the final message.
+ removal: The expected removal version.
+
+ With the default (an empty string), no removal version is shown in the
+ warning message.
+
+ Cannot be used together with pending.
+ package: The package of the deprecated object.
+ """
+ if not pending and removal:
+ removal = f"in {removal}"
+
+ if not message:
+ message = ""
+ package_ = (
+ package or name.split(".", maxsplit=1)[0].replace("_", "-")
+ if "." in name
+ else "LangChain"
+ )
+
+ if obj_type:
+ message += f"The {obj_type} `{name}`"
+ else:
+ message += f"`{name}`"
+
+ if pending:
+ message += " will be deprecated in a future version"
+ else:
+ message += f" was deprecated in {package_} {since}"
+
+ if removal:
+ message += f" and will be removed {removal}"
+
+ if alternative_import:
+ alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")
+ if alt_package == package_:
+ message += f". Use {alternative_import} instead."
+ else:
+ alt_module, alt_name = alternative_import.rsplit(".", 1)
+ message += (
+ f". An updated version of the {obj_type} exists in the "
+ f"{alt_package} package and should be used instead. To use it run "
+ f"`pip install -U {alt_package}` and import as "
+ f"`from {alt_module} import {alt_name}`."
+ )
+ elif alternative:
+ message += f". Use {alternative} instead."
+
+ if addendum:
+ message += f" {addendum}"
+
+ warning_cls = (
+ LangChainPendingDeprecationWarning if pending else LangChainDeprecationWarning
+ )
+ warning = warning_cls(message)
+ warnings.warn(warning, category=LangChainDeprecationWarning, stacklevel=4)
+
+
+def surface_langchain_deprecation_warnings() -> None:
+ """Unmute LangChain deprecation warnings."""
+ warnings.filterwarnings(
+ "default",
+ category=LangChainPendingDeprecationWarning,
+ )
+
+ warnings.filterwarnings(
+ "default",
+ category=LangChainDeprecationWarning,
+ )
+
+
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
+
+def rename_parameter(
+ *,
+ since: str,
+ removal: str,
+ old: str,
+ new: str,
+) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
+ """Decorator indicating that parameter *old* of *func* is renamed to *new*.
+
+ The actual implementation of *func* should use *new*, not *old*. If *old* is passed
+ to *func*, a `DeprecationWarning` is emitted, and its value is used, even if *new*
+ is also passed by keyword.
+
+ Args:
+ since: The version in which the parameter was renamed.
+ removal: The version in which the old parameter will be removed.
+ old: The old parameter name.
+ new: The new parameter name.
+
+ Returns:
+ A decorator indicating that a parameter was renamed.
+
+ Example:
+ ```python
+ @_api.rename_parameter("3.1", "bad_name", "good_name")
+ def func(good_name): ...
+ ```
+ """
+
+ def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
+ @functools.wraps(f)
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ if new in kwargs and old in kwargs:
+ msg = f"{f.__name__}() got multiple values for argument {new!r}"
+ raise TypeError(msg)
+ if old in kwargs:
+ warn_deprecated(
+ since,
+ removal=removal,
+ message=f"The parameter `{old}` of `{f.__name__}` was "
+ f"deprecated in {since} and will be removed "
+ f"in {removal} Use `{new}` instead.",
+ )
+ kwargs[new] = kwargs.pop(old)
+ return f(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/internal.py b/python/user_packages/Python313/site-packages/langchain_core/_api/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bebb59347e27ba30bc0ff5c69c194ada210ca59
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_api/internal.py
@@ -0,0 +1,23 @@
+import inspect
+from typing import cast
+
+
+def is_caller_internal(depth: int = 2) -> bool:
+ """Return whether the caller at `depth` of this function is internal."""
+ try:
+ frame = inspect.currentframe()
+ except AttributeError:
+ return False
+ if frame is None:
+ return False
+ try:
+ for _ in range(depth):
+ frame = frame.f_back
+ if frame is None:
+ return False
+ # Directly access the module name from the frame's global variables
+ module_globals = frame.f_globals
+ caller_module_name = cast("str", module_globals.get("__name__", ""))
+ return caller_module_name.startswith("langchain")
+ finally:
+ del frame
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_api/path.py b/python/user_packages/Python313/site-packages/langchain_core/_api/path.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b597523eb9a8d315e8bb8fe5b4c86277c8cfbf6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_api/path.py
@@ -0,0 +1,50 @@
+import os
+from pathlib import Path
+
+HERE = Path(__file__).parent
+
+# Get directory of langchain package
+PACKAGE_DIR = HERE.parent
+SEPARATOR = os.sep
+
+
+def get_relative_path(file: Path | str, *, relative_to: Path = PACKAGE_DIR) -> str:
+ """Get the path of the file as a relative path to the package directory.
+
+ Args:
+ file: The file path to convert.
+ relative_to: The base path to make the file path relative to.
+
+ Returns:
+ The relative path as a string.
+ """
+ if isinstance(file, str):
+ file = Path(file)
+ return str(file.relative_to(relative_to))
+
+
+def as_import_path(
+ file: Path | str,
+ *,
+ suffix: str | None = None,
+ relative_to: Path = PACKAGE_DIR,
+) -> str:
+ """Path of the file as a LangChain import exclude langchain top namespace.
+
+ Args:
+ file: The file path to convert.
+ suffix: An optional suffix to append to the import path.
+ relative_to: The base path to make the file path relative to.
+
+ Returns:
+ The import path as a string.
+ """
+ if isinstance(file, str):
+ file = Path(file)
+ path = get_relative_path(file, relative_to=relative_to)
+ if file.is_file():
+ path = path[: -len(file.suffix)]
+ import_path = path.replace(SEPARATOR, ".")
+ if suffix:
+ import_path += "." + suffix
+ return import_path
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/_security/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a6fd41939ffc2fb5b175c2c04c563426245296e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_security/__init__.py
@@ -0,0 +1,36 @@
+"""SSRF protection and security utilities.
+
+This is an **internal** module (note the `_security` prefix). It is NOT part of
+the public `langchain-core` API and may change or be removed at any time without
+notice. External code should not import from or depend on anything in this
+module. Any vulnerability reports should target the public APIs that use these
+utilities, not this internal module directly.
+"""
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+ validate_hostname,
+ validate_resolved_ip,
+ validate_url,
+ validate_url_sync,
+)
+from langchain_core._security._transport import (
+ SSRFSafeSyncTransport,
+ SSRFSafeTransport,
+ ssrf_safe_async_client,
+ ssrf_safe_client,
+)
+
+__all__ = [
+ "SSRFBlockedError",
+ "SSRFPolicy",
+ "SSRFSafeSyncTransport",
+ "SSRFSafeTransport",
+ "ssrf_safe_async_client",
+ "ssrf_safe_client",
+ "validate_hostname",
+ "validate_resolved_ip",
+ "validate_url",
+ "validate_url_sync",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd1cb12631debecc0912b30ed314170b3da533a8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f8cba44f491179f92cf27308a5f90b722ff2390
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_policy.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_policy.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3577f500768f93c9125d11fe0244ea51d6427ce4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_policy.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..632d1d8c3879e3aaaef5585f9b50964116c0c207
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_transport.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_transport.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66161fc1148ea5483a427a17d7a8f6715df7c5c0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/_security/__pycache__/_transport.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/_exceptions.py b/python/user_packages/Python313/site-packages/langchain_core/_security/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6046a4829a8b45d51d3b5a4fc595e78e0621f165
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_security/_exceptions.py
@@ -0,0 +1,9 @@
+"""SSRF protection exceptions."""
+
+
+class SSRFBlockedError(Exception):
+ """Raised when a request is blocked by SSRF protection policy."""
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+ super().__init__(f"SSRF blocked: {reason}")
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/_policy.py b/python/user_packages/Python313/site-packages/langchain_core/_security/_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..79cf437c899a27d5f530ccbd4ecc55fd9995b0d4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_security/_policy.py
@@ -0,0 +1,306 @@
+"""SSRF protection policy with IP validation and DNS-aware URL checking."""
+
+import asyncio
+import dataclasses
+import ipaddress
+import os
+import socket
+import urllib.parse
+
+from langchain_core._security._exceptions import SSRFBlockedError
+
+# ---------------------------------------------------------------------------
+# Blocklist constants
+# ---------------------------------------------------------------------------
+
+_BLOCKED_IPV4_NETWORKS: tuple[ipaddress.IPv4Network, ...] = tuple(
+ ipaddress.IPv4Network(n)
+ for n in (
+ "10.0.0.0/8", # RFC 1918 - private class A
+ "172.16.0.0/12", # RFC 1918 - private class B
+ "192.168.0.0/16", # RFC 1918 - private class C
+ "127.0.0.0/8", # RFC 1122 - loopback
+ "169.254.0.0/16", # RFC 3927 - link-local
+ "0.0.0.0/8", # RFC 1122 - "this network"
+ "100.64.0.0/10", # RFC 6598 - shared/CGN address space
+ "192.0.0.0/24", # RFC 6890 - IETF protocol assignments
+ "192.0.2.0/24", # RFC 5737 - TEST-NET-1 (documentation)
+ "198.18.0.0/15", # RFC 2544 - benchmarking
+ "198.51.100.0/24", # RFC 5737 - TEST-NET-2 (documentation)
+ "203.0.113.0/24", # RFC 5737 - TEST-NET-3 (documentation)
+ "224.0.0.0/4", # RFC 5771 - multicast
+ "240.0.0.0/4", # RFC 1112 - reserved for future use
+ "255.255.255.255/32", # RFC 919 - limited broadcast
+ )
+)
+
+_BLOCKED_IPV6_NETWORKS: tuple[ipaddress.IPv6Network, ...] = tuple(
+ ipaddress.IPv6Network(n)
+ for n in (
+ "::1/128", # RFC 4291 - loopback
+ "fc00::/7", # RFC 4193 - unique local addresses (ULA)
+ "fe80::/10", # RFC 4291 - link-local
+ "ff00::/8", # RFC 4291 - multicast
+ "::ffff:0:0/96", # RFC 4291 - IPv4-mapped IPv6 addresses
+ "::0.0.0.0/96", # RFC 4291 - IPv4-compatible IPv6 (deprecated)
+ "64:ff9b::/96", # RFC 6052 - NAT64 well-known prefix
+ "64:ff9b:1::/48", # RFC 8215 - NAT64 discovery prefix
+ )
+)
+
+_CLOUD_METADATA_IPS: frozenset[str] = frozenset(
+ {
+ "169.254.169.254", # AWS, GCP, Azure, DigitalOcean, Oracle Cloud
+ "169.254.170.2", # AWS ECS task metadata
+ "169.254.170.23", # AWS EKS Pod Identity Agent
+ "100.100.100.200", # Alibaba Cloud metadata
+ "fd00:ec2::254", # AWS EC2 IMDSv2 over IPv6 (Nitro instances)
+ "fd00:ec2::23", # AWS EKS Pod Identity Agent (IPv6)
+ "fe80::a9fe:a9fe", # OpenStack Nova metadata (IPv6 link-local)
+ }
+)
+
+# Network ranges that are always blocked when block_cloud_metadata=True,
+# independent of block_private_ips. The entire link-local range is used by
+# cloud metadata services across providers.
+_CLOUD_METADATA_NETWORKS: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = (
+ ipaddress.IPv4Network("169.254.0.0/16"),
+)
+
+_CLOUD_METADATA_HOSTNAMES: frozenset[str] = frozenset(
+ {
+ "metadata.google.internal",
+ "metadata.amazonaws.com",
+ "metadata",
+ "instance-data",
+ }
+)
+
+_LOCALHOST_NAMES: frozenset[str] = frozenset(
+ {
+ "localhost",
+ "localhost.localdomain",
+ "host.docker.internal",
+ }
+)
+
+_K8S_SUFFIX = ".svc.cluster.local"
+
+_LOOPBACK_IPV4 = ipaddress.IPv4Network("127.0.0.0/8")
+_LOOPBACK_IPV6 = ipaddress.IPv6Address("::1")
+
+# NAT64 well-known prefixes
+_NAT64_PREFIX = ipaddress.IPv6Network("64:ff9b::/96")
+_NAT64_DISCOVERY_PREFIX = ipaddress.IPv6Network("64:ff9b:1::/48")
+
+
+# ---------------------------------------------------------------------------
+# SSRFPolicy
+# ---------------------------------------------------------------------------
+
+
+@dataclasses.dataclass(frozen=True)
+class SSRFPolicy:
+ """Immutable policy controlling which URLs/IPs are considered safe."""
+
+ allowed_schemes: frozenset[str] = frozenset({"http", "https"})
+ block_private_ips: bool = True
+ block_localhost: bool = True
+ block_cloud_metadata: bool = True
+ block_k8s_internal: bool = True
+ allowed_hosts: frozenset[str] = frozenset()
+ additional_blocked_cidrs: tuple[
+ ipaddress.IPv4Network | ipaddress.IPv6Network, ...
+ ] = ()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _extract_embedded_ipv4(
+ addr: ipaddress.IPv6Address,
+) -> ipaddress.IPv4Address | None:
+ """Extract an embedded IPv4 from IPv4-mapped or NAT64 IPv6 addresses."""
+ # Check ipv4_mapped first (covers ::ffff:x.x.x.x)
+ if addr.ipv4_mapped is not None:
+ return addr.ipv4_mapped
+
+ # Check NAT64 prefixes — embedded IPv4 is in the last 4 bytes
+ if addr in _NAT64_PREFIX or addr in _NAT64_DISCOVERY_PREFIX:
+ raw = addr.packed
+ return ipaddress.IPv4Address(raw[-4:])
+
+ return None
+
+
+def _ip_in_blocked_networks(
+ addr: ipaddress.IPv4Address | ipaddress.IPv6Address,
+ policy: SSRFPolicy,
+) -> str | None:
+ """Return a reason string if *addr* falls in a blocked range, else None."""
+ # NOTE: if profiling shows this is a hot path, consider memoising with
+ # @functools.lru_cache (key on (addr, id(policy))).
+ if isinstance(addr, ipaddress.IPv4Address):
+ if policy.block_private_ips:
+ for net in _BLOCKED_IPV4_NETWORKS:
+ if addr in net:
+ return "private IP range"
+ for net in policy.additional_blocked_cidrs: # type: ignore[assignment]
+ if isinstance(net, ipaddress.IPv4Network) and addr in net:
+ return "blocked CIDR"
+ else:
+ if policy.block_private_ips:
+ for net in _BLOCKED_IPV6_NETWORKS: # type: ignore[assignment]
+ if addr in net:
+ return "private IP range"
+ for net in policy.additional_blocked_cidrs: # type: ignore[assignment]
+ if isinstance(net, ipaddress.IPv6Network) and addr in net:
+ return "blocked CIDR"
+
+ # Loopback check — independent of block_private_ips so that
+ # block_localhost=True still catches 127.x.x.x / ::1 even when
+ # private IPs are allowed.
+ if policy.block_localhost:
+ if isinstance(addr, ipaddress.IPv4Address) and (
+ addr in _LOOPBACK_IPV4 or addr in ipaddress.IPv4Network("0.0.0.0/8")
+ ):
+ return "localhost address"
+ if isinstance(addr, ipaddress.IPv6Address) and addr == _LOOPBACK_IPV6:
+ return "localhost address"
+
+ # Cloud metadata check — IP set *and* network ranges (e.g. 169.254.0.0/16).
+ # Independent of block_private_ips so that allow_private=True still blocks
+ # cloud metadata endpoints.
+ if policy.block_cloud_metadata:
+ if str(addr) in _CLOUD_METADATA_IPS:
+ return "cloud metadata endpoint"
+ for net in _CLOUD_METADATA_NETWORKS: # type: ignore[assignment]
+ if addr in net:
+ return "cloud metadata endpoint"
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Public validation functions
+# ---------------------------------------------------------------------------
+
+
+def validate_resolved_ip(ip_str: str, policy: SSRFPolicy) -> None:
+ """Validate a resolved IP address against the SSRF policy.
+
+ Raises SSRFBlockedError if the IP is blocked.
+ """
+ try:
+ addr = ipaddress.ip_address(ip_str)
+ except ValueError as exc:
+ raise SSRFBlockedError("invalid IP address") from exc
+
+ if isinstance(addr, ipaddress.IPv6Address):
+ inner = _extract_embedded_ipv4(addr)
+ if inner is not None:
+ addr = inner
+
+ reason = _ip_in_blocked_networks(addr, policy)
+ if reason is not None:
+ raise SSRFBlockedError(reason)
+
+
+def validate_hostname(hostname: str, policy: SSRFPolicy) -> None:
+ """Validate a hostname against the SSRF policy.
+
+ Raises SSRFBlockedError if the hostname is blocked.
+ """
+ lower = hostname.lower()
+
+ if policy.block_localhost and lower in _LOCALHOST_NAMES:
+ raise SSRFBlockedError("localhost address")
+
+ if policy.block_cloud_metadata and lower in _CLOUD_METADATA_HOSTNAMES:
+ raise SSRFBlockedError("cloud metadata endpoint")
+
+ if policy.block_k8s_internal and lower.endswith(_K8S_SUFFIX):
+ raise SSRFBlockedError("Kubernetes internal DNS")
+
+
+def _effective_allowed_hosts(policy: SSRFPolicy) -> frozenset[str]:
+ """Return allowed_hosts, augmented for local environments."""
+ extra: set[str] = set()
+ if os.environ.get("LANGCHAIN_ENV", "").startswith("local"):
+ extra.update({"localhost", "testserver"})
+ if extra:
+ return policy.allowed_hosts | frozenset(extra)
+ return policy.allowed_hosts
+
+
+async def validate_url(url: str, policy: SSRFPolicy = SSRFPolicy()) -> None:
+ """Validate a URL against the SSRF policy, including DNS resolution.
+
+ This is the primary entry-point for async code paths. It delegates
+ scheme/hostname/allowed-hosts checks to `validate_url_sync`, then
+ resolves DNS and validates every resolved IP.
+
+ Raises:
+ SSRFBlockedError: If the URL violates the policy.
+ """
+ parsed = urllib.parse.urlparse(url)
+ hostname = parsed.hostname or ""
+
+ validate_url_sync(url, policy)
+
+ allowed = {h.lower() for h in _effective_allowed_hosts(policy)}
+ if hostname.lower() in allowed:
+ return
+
+ scheme = (parsed.scheme or "").lower()
+ port = parsed.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = await asyncio.to_thread(
+ socket.getaddrinfo, hostname, port, type=socket.SOCK_STREAM
+ )
+ except socket.gaierror as exc:
+ msg = "DNS resolution failed"
+ raise SSRFBlockedError(msg) from exc
+
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ validate_resolved_ip(str(sockaddr[0]), policy)
+
+
+def validate_url_sync(url: str, policy: SSRFPolicy = SSRFPolicy()) -> None:
+ """Synchronous URL validation (no DNS resolution).
+
+ Suitable for Pydantic validators and other sync contexts. Checks scheme
+ and hostname patterns only - use `validate_url` for full DNS-aware checking.
+
+ Raises:
+ SSRFBlockedError: If the URL violates the policy.
+ """
+ parsed = urllib.parse.urlparse(url)
+
+ scheme = (parsed.scheme or "").lower()
+ if scheme not in policy.allowed_schemes:
+ msg = f"scheme '{scheme}' not allowed"
+ raise SSRFBlockedError(msg)
+
+ hostname = parsed.hostname
+ if not hostname:
+ msg = "missing hostname"
+ raise SSRFBlockedError(msg)
+
+ allowed = _effective_allowed_hosts(policy)
+ if hostname.lower() in {h.lower() for h in allowed}:
+ return
+
+ try:
+ ipaddress.ip_address(hostname)
+ validate_resolved_ip(hostname, policy)
+ except SSRFBlockedError:
+ raise
+ except ValueError:
+ pass
+ else:
+ return
+
+ validate_hostname(hostname, policy)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/_ssrf_protection.py b/python/user_packages/Python313/site-packages/langchain_core/_security/_ssrf_protection.py
new file mode 100644
index 0000000000000000000000000000000000000000..0eb3cd7e11c6e227602f013757910947c81c50dd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_security/_ssrf_protection.py
@@ -0,0 +1,155 @@
+"""SSRF Protection - thin wrapper raising ValueError for internal callers.
+
+Delegates all validation to `langchain_core._security._policy`.
+"""
+
+import os
+import socket
+from typing import Annotated, Any
+from urllib.parse import urlparse
+
+from pydantic import (
+ AnyHttpUrl,
+ BeforeValidator,
+ HttpUrl,
+)
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+)
+from langchain_core._security._policy import (
+ validate_resolved_ip as _validate_resolved_ip,
+)
+from langchain_core._security._policy import (
+ validate_url_sync as _validate_url_sync,
+)
+
+
+def _policy_for(*, allow_private: bool, allow_http: bool) -> SSRFPolicy:
+ """Build an `SSRFPolicy` from the legacy flag interface."""
+ schemes = frozenset({"http", "https"}) if allow_http else frozenset({"https"})
+ return SSRFPolicy(
+ allowed_schemes=schemes,
+ block_private_ips=not allow_private,
+ block_localhost=not allow_private,
+ block_cloud_metadata=True,
+ block_k8s_internal=True,
+ )
+
+
+def validate_safe_url(
+ url: str | AnyHttpUrl,
+ *,
+ allow_private: bool = False,
+ allow_http: bool = True,
+) -> str:
+ """Validate a URL for SSRF protection.
+
+ This function validates URLs to prevent Server-Side Request Forgery (SSRF) attacks
+ by blocking requests to private networks and cloud metadata endpoints.
+
+ Args:
+ url: The URL to validate (string or Pydantic HttpUrl).
+ allow_private: If `True`, allows private IPs and localhost (for development).
+ Cloud metadata endpoints are ALWAYS blocked.
+ allow_http: If `True`, allows both HTTP and HTTPS. If `False`, only HTTPS.
+
+ Returns:
+ The validated URL as a string.
+
+ Raises:
+ ValueError: If URL is invalid or potentially dangerous.
+ """
+ url_str = str(url)
+ parsed = urlparse(url_str)
+ hostname = parsed.hostname or ""
+
+ # Test-environment bypass (preserved from original implementation)
+ if (
+ os.environ.get("LANGCHAIN_ENV") == "local_test"
+ and hostname.startswith("test")
+ and "server" in hostname
+ ):
+ return url_str
+
+ policy = _policy_for(allow_private=allow_private, allow_http=allow_http)
+
+ # Synchronous scheme + hostname checks
+ try:
+ _validate_url_sync(url_str, policy)
+ except SSRFBlockedError as exc:
+ raise ValueError(str(exc)) from exc
+
+ # DNS resolution and IP validation
+ try:
+ addr_info = socket.getaddrinfo(
+ hostname,
+ parsed.port or (443 if parsed.scheme == "https" else 80),
+ socket.AF_UNSPEC,
+ socket.SOCK_STREAM,
+ )
+
+ for result in addr_info:
+ ip_str: str = result[4][0] # type: ignore[assignment]
+ try:
+ _validate_resolved_ip(ip_str, policy)
+ except SSRFBlockedError as exc:
+ raise ValueError(str(exc)) from exc
+
+ except socket.gaierror as e:
+ msg = f"Failed to resolve hostname '{hostname}': {e}"
+ raise ValueError(msg) from e
+ except OSError as e:
+ msg = f"Network error while validating URL: {e}"
+ raise ValueError(msg) from e
+
+ return url_str
+
+
+def is_safe_url(
+ url: str | AnyHttpUrl,
+ *,
+ allow_private: bool = False,
+ allow_http: bool = True,
+) -> bool:
+ """Non-throwing version of `validate_safe_url`."""
+ try:
+ validate_safe_url(url, allow_private=allow_private, allow_http=allow_http)
+ except ValueError:
+ return False
+ else:
+ return True
+
+
+def _validate_url_ssrf_strict(v: Any) -> Any:
+ """Validate URL for SSRF protection (strict mode)."""
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=False, allow_http=True)
+ return v
+
+
+def _validate_url_ssrf_https_only(v: Any) -> Any:
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=False, allow_http=False)
+ return v
+
+
+def _validate_url_ssrf_relaxed(v: Any) -> Any:
+ """Validate URL for SSRF protection (relaxed mode - allows private IPs)."""
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=True, allow_http=True)
+ return v
+
+
+# Annotated types with SSRF protection
+SSRFProtectedUrl = Annotated[HttpUrl, BeforeValidator(_validate_url_ssrf_strict)]
+SSRFProtectedUrlRelaxed = Annotated[
+ HttpUrl, BeforeValidator(_validate_url_ssrf_relaxed)
+]
+SSRFProtectedHttpsUrl = Annotated[
+ HttpUrl, BeforeValidator(_validate_url_ssrf_https_only)
+]
+SSRFProtectedHttpsUrlStr = Annotated[
+ str, BeforeValidator(_validate_url_ssrf_https_only)
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/_security/_transport.py b/python/user_packages/Python313/site-packages/langchain_core/_security/_transport.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bbc8d8989fcd5f379af83f1e36d268d059907db
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/_security/_transport.py
@@ -0,0 +1,252 @@
+"""SSRF-safe httpx transport with DNS resolution and IP pinning."""
+
+import asyncio
+import socket
+
+import httpx
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+ _effective_allowed_hosts,
+ validate_resolved_ip,
+ validate_url_sync,
+)
+
+# Keys that AsyncHTTPTransport accepts (forwarded from factory kwargs).
+_TRANSPORT_KWARGS = frozenset(
+ {
+ "verify",
+ "cert",
+ "trust_env",
+ "http1",
+ "http2",
+ "limits",
+ "retries",
+ }
+)
+
+
+class SSRFSafeTransport(httpx.AsyncBaseTransport):
+ """httpx async transport that validates DNS results against an SSRF policy.
+
+ For every outgoing request the transport:
+ 1. Checks the URL scheme against `policy.allowed_schemes`.
+ 2. Validates the hostname against blocked patterns.
+ 3. Resolves DNS and validates **all** returned IPs.
+ 4. Rewrites the request to connect to the first valid IP while
+ preserving the original `Host` header and TLS SNI hostname.
+
+ Redirects are re-validated on each hop because `follow_redirects`
+ is set on the *client*, causing `handle_async_request` to be called
+ again for each redirect target.
+ """
+
+ def __init__(
+ self,
+ policy: SSRFPolicy = SSRFPolicy(),
+ **transport_kwargs: object,
+ ) -> None:
+ self._policy = policy
+ self._inner = httpx.AsyncHTTPTransport(**transport_kwargs) # type: ignore[arg-type]
+
+ # ------------------------------------------------------------------ #
+ # Core request handler
+ # ------------------------------------------------------------------ #
+
+ async def handle_async_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ hostname = request.url.host or ""
+ scheme = request.url.scheme.lower()
+
+ # 1-3. Scheme, hostname, and pattern checks (reuse sync validator).
+ try:
+ validate_url_sync(str(request.url), self._policy)
+ except SSRFBlockedError:
+ raise
+
+ # Allowed-hosts bypass - skip DNS/IP validation entirely.
+ allowed = {h.lower() for h in _effective_allowed_hosts(self._policy)}
+ if hostname.lower() in allowed:
+ return await self._inner.handle_async_request(request)
+
+ # 4. DNS resolution
+ port = request.url.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = await asyncio.to_thread(
+ socket.getaddrinfo,
+ hostname,
+ port,
+ type=socket.SOCK_STREAM,
+ )
+ except socket.gaierror as exc:
+ raise SSRFBlockedError("DNS resolution failed") from exc
+
+ if not addrinfo:
+ raise SSRFBlockedError("DNS resolution returned no results")
+
+ # 5. Validate ALL resolved IPs - any blocked means reject.
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ ip_str: str = sockaddr[0] # type: ignore[assignment]
+ validate_resolved_ip(ip_str, self._policy)
+
+ # 6. Pin to first resolved IP.
+ pinned_ip = addrinfo[0][4][0]
+
+ # 7. Rewrite URL to use pinned IP, preserving Host header and SNI.
+ pinned_url = request.url.copy_with(host=pinned_ip)
+
+ # Build extensions dict, adding sni_hostname for HTTPS so TLS
+ # certificate validation uses the original hostname.
+ extensions = dict(request.extensions)
+ if scheme == "https":
+ extensions["sni_hostname"] = hostname.encode("ascii")
+
+ pinned_request = httpx.Request(
+ method=request.method,
+ url=pinned_url,
+ headers=request.headers, # Host header already set to original
+ content=request.content,
+ extensions=extensions,
+ )
+
+ return await self._inner.handle_async_request(pinned_request)
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle
+ # ------------------------------------------------------------------ #
+
+ async def aclose(self) -> None:
+ await self._inner.aclose()
+
+
+# ---------------------------------------------------------------------- #
+# Factory
+# ---------------------------------------------------------------------- #
+
+
+class SSRFSafeSyncTransport(httpx.BaseTransport):
+ """httpx sync transport that validates DNS results against an SSRF policy.
+
+ Sync mirror of `SSRFSafeTransport`. See that class for full documentation.
+ """
+
+ def __init__(
+ self,
+ policy: SSRFPolicy = SSRFPolicy(),
+ **transport_kwargs: object,
+ ) -> None:
+ self._policy = policy
+ self._inner = httpx.HTTPTransport(**transport_kwargs) # type: ignore[arg-type]
+
+ def handle_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ hostname = request.url.host or ""
+ scheme = request.url.scheme.lower()
+
+ validate_url_sync(str(request.url), self._policy)
+
+ allowed = {h.lower() for h in _effective_allowed_hosts(self._policy)}
+ if hostname.lower() in allowed:
+ return self._inner.handle_request(request)
+
+ port = request.url.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = socket.getaddrinfo(
+ hostname,
+ port,
+ type=socket.SOCK_STREAM,
+ )
+ except socket.gaierror as exc:
+ raise SSRFBlockedError("DNS resolution failed") from exc
+
+ if not addrinfo:
+ raise SSRFBlockedError("DNS resolution returned no results")
+
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ ip_str: str = sockaddr[0] # type: ignore[assignment]
+ validate_resolved_ip(ip_str, self._policy)
+
+ pinned_ip = addrinfo[0][4][0]
+ pinned_url = request.url.copy_with(host=pinned_ip)
+
+ extensions = dict(request.extensions)
+ if scheme == "https":
+ extensions["sni_hostname"] = hostname.encode("ascii")
+
+ pinned_request = httpx.Request(
+ method=request.method,
+ url=pinned_url,
+ headers=request.headers,
+ content=request.content,
+ extensions=extensions,
+ )
+
+ return self._inner.handle_request(pinned_request)
+
+ def close(self) -> None:
+ self._inner.close()
+
+
+# ---------------------------------------------------------------------- #
+# Factories
+# ---------------------------------------------------------------------- #
+
+
+def ssrf_safe_client(
+ policy: SSRFPolicy = SSRFPolicy(),
+ **kwargs: object,
+) -> httpx.Client:
+ """Create an `httpx.Client` with SSRF protection."""
+ transport_kwargs: dict[str, object] = {}
+ client_kwargs: dict[str, object] = {}
+ for key, value in kwargs.items():
+ if key in _TRANSPORT_KWARGS:
+ transport_kwargs[key] = value
+ else:
+ client_kwargs[key] = value
+
+ transport = SSRFSafeSyncTransport(policy=policy, **transport_kwargs)
+
+ client_kwargs.setdefault("follow_redirects", True)
+ client_kwargs.setdefault("max_redirects", 10)
+
+ return httpx.Client(
+ transport=transport,
+ **client_kwargs, # type: ignore[arg-type]
+ )
+
+
+def ssrf_safe_async_client(
+ policy: SSRFPolicy = SSRFPolicy(),
+ **kwargs: object,
+) -> httpx.AsyncClient:
+ """Create an `httpx.AsyncClient` with SSRF protection.
+
+ Drop-in replacement for `httpx.AsyncClient(...)` - callers just swap
+ the constructor call. Transport-specific kwargs (`verify`, `cert`,
+ `retries`, etc.) are forwarded to the inner `AsyncHTTPTransport`;
+ everything else goes to the `AsyncClient`.
+ """
+ transport_kwargs: dict[str, object] = {}
+ client_kwargs: dict[str, object] = {}
+ for key, value in kwargs.items():
+ if key in _TRANSPORT_KWARGS:
+ transport_kwargs[key] = value
+ else:
+ client_kwargs[key] = value
+
+ transport = SSRFSafeTransport(policy=policy, **transport_kwargs)
+
+ # Apply defaults only if not overridden by caller.
+ client_kwargs.setdefault("follow_redirects", True)
+ client_kwargs.setdefault("max_redirects", 10)
+
+ return httpx.AsyncClient(
+ transport=transport,
+ **client_kwargs, # type: ignore[arg-type]
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1f1775248f4c58ce4a4250b8b600c4d76ce7184
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__init__.py
@@ -0,0 +1,132 @@
+"""Callback handlers allow listening to events in LangChain."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.base import (
+ AsyncCallbackHandler,
+ BaseCallbackHandler,
+ BaseCallbackManager,
+ CallbackManagerMixin,
+ Callbacks,
+ ChainManagerMixin,
+ LLMManagerMixin,
+ RetrieverManagerMixin,
+ RunManagerMixin,
+ ToolManagerMixin,
+ )
+ from langchain_core.callbacks.file import FileCallbackHandler
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForChainGroup,
+ AsyncCallbackManagerForChainRun,
+ AsyncCallbackManagerForLLMRun,
+ AsyncCallbackManagerForRetrieverRun,
+ AsyncCallbackManagerForToolRun,
+ AsyncParentRunManager,
+ AsyncRunManager,
+ BaseRunManager,
+ CallbackManager,
+ CallbackManagerForChainGroup,
+ CallbackManagerForChainRun,
+ CallbackManagerForLLMRun,
+ CallbackManagerForRetrieverRun,
+ CallbackManagerForToolRun,
+ ParentRunManager,
+ RunManager,
+ adispatch_custom_event,
+ dispatch_custom_event,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+ from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
+ from langchain_core.callbacks.usage import (
+ UsageMetadataCallbackHandler,
+ get_usage_metadata_callback,
+ )
+
+__all__ = (
+ "AsyncCallbackHandler",
+ "AsyncCallbackManager",
+ "AsyncCallbackManagerForChainGroup",
+ "AsyncCallbackManagerForChainRun",
+ "AsyncCallbackManagerForLLMRun",
+ "AsyncCallbackManagerForRetrieverRun",
+ "AsyncCallbackManagerForToolRun",
+ "AsyncParentRunManager",
+ "AsyncRunManager",
+ "BaseCallbackHandler",
+ "BaseCallbackManager",
+ "BaseRunManager",
+ "CallbackManager",
+ "CallbackManagerForChainGroup",
+ "CallbackManagerForChainRun",
+ "CallbackManagerForLLMRun",
+ "CallbackManagerForRetrieverRun",
+ "CallbackManagerForToolRun",
+ "CallbackManagerMixin",
+ "Callbacks",
+ "ChainManagerMixin",
+ "FileCallbackHandler",
+ "LLMManagerMixin",
+ "ParentRunManager",
+ "RetrieverManagerMixin",
+ "RunManager",
+ "RunManagerMixin",
+ "StdOutCallbackHandler",
+ "StreamingStdOutCallbackHandler",
+ "ToolManagerMixin",
+ "UsageMetadataCallbackHandler",
+ "adispatch_custom_event",
+ "dispatch_custom_event",
+ "get_usage_metadata_callback",
+)
+
+_dynamic_imports = {
+ "AsyncCallbackHandler": "base",
+ "BaseCallbackHandler": "base",
+ "BaseCallbackManager": "base",
+ "CallbackManagerMixin": "base",
+ "Callbacks": "base",
+ "ChainManagerMixin": "base",
+ "LLMManagerMixin": "base",
+ "RetrieverManagerMixin": "base",
+ "RunManagerMixin": "base",
+ "ToolManagerMixin": "base",
+ "FileCallbackHandler": "file",
+ "AsyncCallbackManager": "manager",
+ "AsyncCallbackManagerForChainGroup": "manager",
+ "AsyncCallbackManagerForChainRun": "manager",
+ "AsyncCallbackManagerForLLMRun": "manager",
+ "AsyncCallbackManagerForRetrieverRun": "manager",
+ "AsyncCallbackManagerForToolRun": "manager",
+ "AsyncParentRunManager": "manager",
+ "AsyncRunManager": "manager",
+ "BaseRunManager": "manager",
+ "CallbackManager": "manager",
+ "CallbackManagerForChainGroup": "manager",
+ "CallbackManagerForChainRun": "manager",
+ "CallbackManagerForLLMRun": "manager",
+ "CallbackManagerForRetrieverRun": "manager",
+ "CallbackManagerForToolRun": "manager",
+ "ParentRunManager": "manager",
+ "RunManager": "manager",
+ "adispatch_custom_event": "manager",
+ "dispatch_custom_event": "manager",
+ "StdOutCallbackHandler": "stdout",
+ "StreamingStdOutCallbackHandler": "streaming_stdout",
+ "UsageMetadataCallbackHandler": "usage",
+ "get_usage_metadata_callback": "usage",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87bf3d9cf774c0705dafbff9ee6919968c7ebc54
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..add9635a043c708b803b3e1d46c017176f85ecd0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/file.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/file.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a103e5b183b9045c986f5d789256655bc19bf50
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/file.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8525117c488d1ce967d753251c0f320152ff1c5e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a1e09f67b6500349d7bc97476751d61bf7cf4cf
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d83432100c09f46c3558048cb6b3bb8f6be846e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28d817f4d2dfdb194e59105deafef96c64420a15
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/base.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..234193190407861fe3833dc4949d76ed71dc7146
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/base.py
@@ -0,0 +1,1223 @@
+"""Base callback handler for LangChain."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+ from uuid import UUID
+
+ from langchain_protocol.protocol import MessagesData
+ from tenacity import RetryCallState
+ from typing_extensions import Self
+
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class RetrieverManagerMixin:
+ """Mixin for `Retriever` callbacks."""
+
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when `Retriever` errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when `Retriever` ends running.
+
+ Args:
+ documents: The documents retrieved.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class LLMManagerMixin:
+ """Mixin for LLM callbacks."""
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on new output token.
+
+ Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text completion LLMs).
+
+ Args:
+ token: The new token.
+ chunk: The new generated chunk, containing content and other information.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM ends running.
+
+ Args:
+ response: The response which was generated.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_stream_event(
+ self,
+ event: MessagesData,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on each protocol event from `stream_events(version="v3")`.
+
+ Also fires for the async equivalent
+ (`astream_events(version="v3")`).
+
+ Fires once per `MessagesData` event — `message-start`, per-block
+ `content-block-start` / `content-block-delta` /
+ `content-block-finish`, and `message-finish`. Analogous to
+ `on_llm_new_token` in v1 streaming, but at event granularity rather
+ than chunk: a single chunk can map to multiple events (e.g. a
+ `content-block-start` plus its first `content-block-delta`), and
+ lifecycle boundaries are explicit.
+
+ Fires uniformly whether the provider emits events natively via
+ `_stream_chat_model_events` or goes through the chunk-to-event
+ compat bridge. Observers see the same event stream regardless of
+ how the underlying model produces output.
+
+ Not fired from v1 `stream()` / `astream()`; for those, keep using
+ `on_llm_new_token`. Purely additive — `on_chat_model_start`,
+ `on_llm_end`, and `on_llm_error` still fire around a v2 call as
+ they do around a v1 call.
+
+ Args:
+ event: The protocol event.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class ChainManagerMixin:
+ """Mixin for chain callbacks."""
+
+ def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_action(
+ self,
+ action: AgentAction,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_finish(
+ self,
+ finish: AgentFinish,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class ToolManagerMixin:
+ """Mixin for tool callbacks."""
+
+ def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class CallbackManagerMixin:
+ """Mixin for callback manager."""
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM starts running.
+
+ !!! warning
+
+ This method is called for non-chat models (regular text completion LLMs). If
+ you're implementing a handler for a chat model, you should use
+ `on_chat_model_start` instead.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chat model starts running.
+
+ !!! warning
+
+ This method is called for chat models. If you're implementing a handler for
+ a non-chat model, you should use `on_llm_start` instead.
+
+ !!! note
+
+ When overriding this method, the signature **must** include the two
+ required positional arguments `serialized` and `messages`. Avoid
+ using `*args` in your override — doing so causes an `IndexError`
+ in the fallback path when the callback system converts `messages`
+ to prompt strings for `on_llm_start`. Always declare the
+ signature explicitly:
+
+ .. code-block:: python
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ raise NotImplementedError # triggers fallback to on_llm_start
+
+ Args:
+ serialized: The serialized chat model.
+ messages: The messages. Must be a list of message lists — this is a
+ required positional argument and must be present in any override.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+ # NotImplementedError is thrown intentionally
+ # Callback handler will fall back to on_llm_start if this exception is thrown
+ msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
+ raise NotImplementedError(msg)
+
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the `Retriever` starts running.
+
+ Args:
+ serialized: The serialized `Retriever`.
+ query: The query.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized chain.
+ input_str: The input string.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ inputs: The inputs.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class RunManagerMixin:
+ """Mixin for run manager."""
+
+ def on_text(
+ self,
+ text: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on a retry event.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Override to define a handler for a custom event.
+
+ Args:
+ name: The name of the custom event.
+ data: The data for the custom event.
+
+ Format will match the format specified by the user.
+ run_id: The ID of the run.
+ tags: The tags associated with the custom event (includes inherited tags).
+ metadata: The metadata associated with the custom event (includes inherited
+ metadata).
+ """
+
+
+class BaseCallbackHandler(
+ LLMManagerMixin,
+ ChainManagerMixin,
+ ToolManagerMixin,
+ RetrieverManagerMixin,
+ CallbackManagerMixin,
+ RunManagerMixin,
+):
+ """Base callback handler."""
+
+ raise_error: bool = False
+ """Whether to raise an error if an exception occurs."""
+
+ run_inline: bool = False
+ """Whether to run the callback inline."""
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return False
+
+ @property
+ def ignore_retry(self) -> bool:
+ """Whether to ignore retry callbacks."""
+ return False
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return False
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return False
+
+ @property
+ def ignore_retriever(self) -> bool:
+ """Whether to ignore retriever callbacks."""
+ return False
+
+ @property
+ def ignore_chat_model(self) -> bool:
+ """Whether to ignore chat model callbacks."""
+ return False
+
+ @property
+ def ignore_custom_event(self) -> bool:
+ """Ignore custom event."""
+ return False
+
+
+class AsyncCallbackHandler(BaseCallbackHandler):
+ """Base async callback handler."""
+
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the model starts running.
+
+ !!! warning
+
+ This method is called for non-chat models (regular text completion LLMs). If
+ you're implementing a handler for a chat model, you should use
+ `on_chat_model_start` instead.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chat model starts running.
+
+ !!! warning
+
+ This method is called for chat models. If you're implementing a handler for
+ a non-chat model, you should use `on_llm_start` instead.
+
+ !!! note
+
+ When overriding this method, the signature **must** include the two
+ required positional arguments `serialized` and `messages`. Avoid
+ using `*args` in your override — doing so causes an `IndexError`
+ in the fallback path when the callback system converts `messages`
+ to prompt strings for `on_llm_start`. Always declare the
+ signature explicitly:
+
+ .. code-block:: python
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ raise NotImplementedError # triggers fallback to on_llm_start
+
+ Args:
+ serialized: The serialized chat model.
+ messages: The messages. Must be a list of message lists — this is a
+ required positional argument and must be present in any override.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+ # NotImplementedError is thrown intentionally
+ # Callback handler will fall back to on_llm_start if this exception is thrown
+ msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
+ raise NotImplementedError(msg)
+
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on new output token. Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text completion LLMs).
+
+ Args:
+ token: The new token.
+ chunk: The new generated chunk, containing content and other information.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the model ends running.
+
+ Args:
+ response: The response which was generated.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+ """
+
+ async def on_stream_event(
+ self,
+ event: MessagesData,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on each protocol event produced by `astream_events(version="v3")`.
+
+ See :meth:`LLMManagerMixin.on_stream_event` for the full contract.
+ Fires once per `MessagesData` event at event granularity, uniformly
+ across native and compat-bridge providers, and is purely additive
+ to the existing `on_chat_model_start` / `on_llm_end` /
+ `on_llm_error` callbacks.
+
+ Args:
+ event: The protocol event.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ inputs: The inputs.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_text(
+ self,
+ text: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on a retry event.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_agent_action(
+ self,
+ action: AgentAction,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_agent_finish(
+ self,
+ finish: AgentFinish,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the retriever start.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the retriever end.
+
+ Args:
+ documents: The documents retrieved.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on retriever error.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Override to define a handler for custom events.
+
+ Args:
+ name: The name of the custom event.
+ data: The data for the custom event.
+
+ Format will match the format specified by the user.
+ run_id: The ID of the run.
+ tags: The tags associated with the custom event (includes inherited tags).
+ metadata: The metadata associated with the custom event (includes inherited
+ metadata).
+ """
+
+
+class BaseCallbackManager(CallbackManagerMixin):
+ """Base callback manager."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ tags: list[str] | None = None,
+ inheritable_tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize callback manager.
+
+ Args:
+ handlers: The handlers.
+ inheritable_handlers: The inheritable handlers.
+ parent_run_id: The parent run ID.
+ tags: The tags.
+ inheritable_tags: The inheritable tags.
+ metadata: The metadata.
+ inheritable_metadata: The inheritable metadata.
+ """
+ self.handlers: list[BaseCallbackHandler] = handlers
+ self.inheritable_handlers: list[BaseCallbackHandler] = (
+ inheritable_handlers or []
+ )
+ self.parent_run_id: UUID | None = parent_run_id
+ self.tags = tags or []
+ self.inheritable_tags = inheritable_tags or []
+ self.metadata = metadata or {}
+ self.inheritable_metadata = inheritable_metadata or {}
+
+ def copy(self) -> Self:
+ """Return a copy of the callback manager."""
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ )
+
+ def merge(self, other: BaseCallbackManager) -> Self:
+ """Merge the callback manager with another callback manager.
+
+ May be overwritten in subclasses.
+
+ Primarily used internally within `merge_configs`.
+
+ Returns:
+ The merged callback manager of the same type as the current object.
+
+ Example:
+ ```python
+ # Merging two callback managers`
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ trace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ # Combine handlers and inheritable_handlers separately, using sets
+ # to deduplicate (order not preserved)
+ combined_handlers = list(set(self.handlers) | set(other.handlers))
+ combined_inheritable = list(
+ set(self.inheritable_handlers) | set(other.inheritable_handlers)
+ )
+
+ return self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=combined_handlers,
+ inheritable_handlers=combined_inheritable,
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ inheritable_metadata={
+ **self.inheritable_metadata,
+ **other.inheritable_metadata,
+ },
+ )
+
+ @property
+ def is_async(self) -> bool:
+ """Whether the callback manager is async."""
+ return False
+
+ def add_handler(
+ self,
+ handler: BaseCallbackHandler,
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add a handler to the callback manager.
+
+ Args:
+ handler: The handler to add.
+ inherit: Whether to inherit the handler.
+ """
+ if handler not in self.handlers:
+ self.handlers.append(handler)
+ if inherit and handler not in self.inheritable_handlers:
+ self.inheritable_handlers.append(handler)
+
+ def remove_handler(self, handler: BaseCallbackHandler) -> None:
+ """Remove a handler from the callback manager.
+
+ Args:
+ handler: The handler to remove.
+ """
+ if handler in self.handlers:
+ self.handlers.remove(handler)
+ if handler in self.inheritable_handlers:
+ self.inheritable_handlers.remove(handler)
+
+ def set_handlers(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Set handlers as the only handlers on the callback manager.
+
+ Args:
+ handlers: The handlers to set.
+ inherit: Whether to inherit the handlers.
+ """
+ self.handlers = []
+ self.inheritable_handlers = []
+ for handler in handlers:
+ self.add_handler(handler, inherit=inherit)
+
+ def set_handler(
+ self,
+ handler: BaseCallbackHandler,
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Set handler as the only handler on the callback manager.
+
+ Args:
+ handler: The handler to set.
+ inherit: Whether to inherit the handler.
+ """
+ self.set_handlers([handler], inherit=inherit)
+
+ def add_tags(
+ self,
+ tags: list[str],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add tags to the callback manager.
+
+ Args:
+ tags: The tags to add.
+ inherit: Whether to inherit the tags.
+ """
+ for tag in tags:
+ if tag in self.tags:
+ self.remove_tags([tag])
+ self.tags.extend(tags)
+ if inherit:
+ self.inheritable_tags.extend(tags)
+
+ def remove_tags(self, tags: list[str]) -> None:
+ """Remove tags from the callback manager.
+
+ Args:
+ tags: The tags to remove.
+ """
+ for tag in tags:
+ if tag in self.tags:
+ self.tags.remove(tag)
+ if tag in self.inheritable_tags:
+ self.inheritable_tags.remove(tag)
+
+ def add_metadata(
+ self,
+ metadata: dict[str, Any],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add metadata to the callback manager.
+
+ Args:
+ metadata: The metadata to add.
+ inherit: Whether to inherit the metadata.
+ """
+ self.metadata.update(metadata)
+ if inherit:
+ self.inheritable_metadata.update(metadata)
+
+ def remove_metadata(self, keys: list[str]) -> None:
+ """Remove metadata from the callback manager.
+
+ Args:
+ keys: The keys to remove.
+ """
+ for key in keys:
+ self.metadata.pop(key, None)
+ self.inheritable_metadata.pop(key, None)
+
+
+Callbacks = list[BaseCallbackHandler] | BaseCallbackManager | None
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/file.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/file.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ba0e863c73dad6ffc1add52f5647e71d87d8f41
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/file.py
@@ -0,0 +1,267 @@
+"""Callback handler that writes to a file."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, TextIO, cast
+
+from typing_extensions import Self, override
+
+from langchain_core._api import warn_deprecated
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.utils.input import print_text
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+
+
+_GLOBAL_DEPRECATION_WARNED = False
+
+
+class FileCallbackHandler(BaseCallbackHandler):
+ """Callback handler that writes to a file.
+
+ This handler supports both context manager usage (recommended) and direct
+ instantiation (deprecated) for backwards compatibility.
+
+ Examples:
+ Using as a context manager (recommended):
+
+ ```python
+ with FileCallbackHandler("output.txt") as handler:
+ # Use handler with your chain/agent
+ chain.invoke(inputs, config={"callbacks": [handler]})
+ ```
+
+ Direct instantiation (deprecated):
+
+ ```python
+ handler = FileCallbackHandler("output.txt")
+ # File remains open until handler is garbage collected
+ try:
+ chain.invoke(inputs, config={"callbacks": [handler]})
+ finally:
+ handler.close() # Explicit cleanup recommended
+ ```
+
+ Args:
+ filename: The file path to write to.
+ mode: The file open mode. Defaults to `'a'` (append).
+ color: Default color for text output.
+
+ !!! note
+
+ When not used as a context manager, a deprecation warning will be issued on
+ first use. The file will be opened immediately in `__init__` and closed in
+ `__del__` or when `close()` is called explicitly.
+
+ """
+
+ def __init__(
+ self, filename: str, mode: str = "a", color: str | None = None
+ ) -> None:
+ """Initialize the file callback handler.
+
+ Args:
+ filename: Path to the output file.
+ mode: File open mode (e.g., `'w'`, `'a'`, `'x'`). Defaults to `'a'`.
+ color: Default text color for output.
+
+ """
+ self.filename = filename
+ self.mode = mode
+ self.color = color
+ self._file_opened_in_context = False
+ self.file: TextIO = cast(
+ "TextIO",
+ # Open the file in the specified mode with UTF-8 encoding.
+ Path(self.filename).open(self.mode, encoding="utf-8"), # noqa: SIM115
+ )
+
+ def __enter__(self) -> Self:
+ """Enter the context manager.
+
+ Returns:
+ The `FileCallbackHandler` instance.
+
+ !!! note
+
+ The file is already opened in `__init__`, so this just marks that the
+ handler is being used as a context manager.
+
+ """
+ self._file_opened_in_context = True
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: object,
+ ) -> None:
+ """Exit the context manager and close the file.
+
+ Args:
+ exc_type: Exception type if an exception occurred.
+ exc_val: Exception value if an exception occurred.
+ exc_tb: Exception traceback if an exception occurred.
+
+ """
+ self.close()
+
+ def __del__(self) -> None:
+ """Destructor to cleanup when done."""
+ self.close()
+
+ def close(self) -> None:
+ """Close the file if it's open.
+
+ This method is safe to call multiple times and will only close
+ the file if it's currently open.
+
+ """
+ if hasattr(self, "file") and self.file and not self.file.closed:
+ self.file.close()
+
+ def _write(
+ self,
+ text: str,
+ color: str | None = None,
+ end: str = "",
+ ) -> None:
+ """Write text to the file with deprecation warning if needed.
+
+ Args:
+ text: The text to write to the file.
+ color: Optional color for the text. Defaults to `self.color`.
+ end: String appended after the text.
+ file: Optional file to write to. Defaults to `self.file`.
+
+ Raises:
+ RuntimeError: If the file is closed or not available.
+
+ """
+ global _GLOBAL_DEPRECATION_WARNED # noqa: PLW0603
+ if not self._file_opened_in_context and not _GLOBAL_DEPRECATION_WARNED:
+ warn_deprecated(
+ since="0.3.67",
+ pending=True,
+ message=(
+ "Using FileCallbackHandler without a context manager is "
+ "deprecated. Use 'with FileCallbackHandler(...) as "
+ "handler:' instead."
+ ),
+ )
+ _GLOBAL_DEPRECATION_WARNED = True
+
+ if not hasattr(self, "file") or self.file is None or self.file.closed:
+ msg = "File is not open. Use FileCallbackHandler as a context manager."
+ raise RuntimeError(msg)
+
+ print_text(text, file=self.file, color=color, end=end)
+
+ @override
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print that we are entering a chain.
+
+ Args:
+ serialized: The serialized chain information.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments that may contain `'name'`.
+
+ """
+ name = (
+ kwargs.get("name")
+ or serialized.get("name", serialized.get("id", [""])[-1])
+ or ""
+ )
+ self._write(f"\n\n> Entering new {name} chain...", end="\n")
+
+ @override
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Print that we finished a chain.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write("\n> Finished chain.", end="\n")
+
+ @override
+ def on_agent_action(
+ self, action: AgentAction, color: str | None = None, **kwargs: Any
+ ) -> Any:
+ """Handle agent action by writing the action log.
+
+ Args:
+ action: The agent action containing the log to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(action.log, color=color or self.color)
+
+ @override
+ def on_tool_end(
+ self,
+ output: str,
+ color: str | None = None,
+ observation_prefix: str | None = None,
+ llm_prefix: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Handle tool end by writing the output with optional prefixes.
+
+ Args:
+ output: The tool output to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ observation_prefix: Optional prefix to write before the output.
+ llm_prefix: Optional prefix to write after the output.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if observation_prefix is not None:
+ self._write(f"\n{observation_prefix}")
+ self._write(output)
+ if llm_prefix is not None:
+ self._write(f"\n{llm_prefix}")
+
+ @override
+ def on_text(
+ self, text: str, color: str | None = None, end: str = "", **kwargs: Any
+ ) -> None:
+ """Handle text output.
+
+ Args:
+ text: The text to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ end: String appended after the text.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(text, color=color or self.color, end=end)
+
+ @override
+ def on_agent_finish(
+ self, finish: AgentFinish, color: str | None = None, **kwargs: Any
+ ) -> None:
+ """Handle agent finish by writing the finish log.
+
+ Args:
+ finish: The agent finish object containing the log to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(finish.log, color=color or self.color, end="\n")
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/manager.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1ba9b76c0a299d4642eabd56443688fc817c17c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/manager.py
@@ -0,0 +1,2792 @@
+"""Run managers."""
+
+from __future__ import annotations
+
+import asyncio
+import atexit
+import functools
+import logging
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import asynccontextmanager, contextmanager
+from contextvars import copy_context
+from typing import TYPE_CHECKING, Any, TypeVar, cast
+
+from typing_extensions import Self, override
+
+from langchain_core.callbacks.base import (
+ BaseCallbackHandler,
+ BaseCallbackManager,
+ Callbacks,
+ ChainManagerMixin,
+ LLMManagerMixin,
+ RetrieverManagerMixin,
+ RunManagerMixin,
+ ToolManagerMixin,
+)
+from langchain_core.callbacks.stdout import StdOutCallbackHandler
+from langchain_core.globals import get_debug
+from langchain_core.messages import BaseMessage, get_buffer_string
+from langchain_core.utils.env import env_var_is_set
+from langchain_core.utils.uuid import uuid7
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator, Coroutine, Generator, Sequence
+ from uuid import UUID
+
+ from langchain_protocol.protocol import MessagesData
+ from tenacity import RetryCallState
+
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.documents import Document
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+ from langchain_core.runnables.config import RunnableConfig
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+
+def _get_debug() -> bool:
+ return get_debug()
+
+
+@contextmanager
+def trace_as_chain_group(
+ group_name: str,
+ callback_manager: CallbackManager | None = None,
+ *,
+ inputs: dict[str, Any] | None = None,
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+) -> Generator[CallbackManagerForChainGroup, None, None]:
+ """Get a callback manager for a chain group in a context manager.
+
+ Useful for grouping different calls together as a single run even if they aren't
+ composed in a single chain.
+
+ Args:
+ group_name: The name of the chain group.
+ callback_manager: The callback manager to use.
+ inputs: The inputs to the chain group.
+ project_name: The name of the project.
+ example_id: The ID of the example.
+ run_id: The ID of the run.
+ tags: The inheritable tags to apply to all runs.
+ metadata: The metadata to apply to all runs.
+
+ !!! note
+
+ Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in
+ LangSmith.
+
+ Yields:
+ The callback manager for the chain group.
+
+ Example:
+ ```python
+ llm_input = "Foo"
+ with trace_as_chain_group("group_name", inputs={"input": llm_input}) as manager:
+ # Use the callback manager for the chain group
+ res = llm.invoke(llm_input, {"callbacks": manager})
+ manager.on_chain_end({"output": res})
+ ```
+ """
+ from langchain_core.tracers.context import ( # noqa: PLC0415 -- deferred to avoid importing langsmith at module level
+ _get_trace_callbacks,
+ )
+
+ cb = _get_trace_callbacks(
+ project_name, example_id, callback_manager=callback_manager
+ )
+ cm = CallbackManager.configure(
+ inheritable_callbacks=cb,
+ inheritable_tags=tags,
+ inheritable_metadata=metadata,
+ )
+
+ run_manager = cm.on_chain_start({"name": group_name}, inputs or {}, run_id=run_id)
+ child_cm = run_manager.get_child()
+ group_cm = CallbackManagerForChainGroup(
+ child_cm.handlers,
+ child_cm.inheritable_handlers,
+ child_cm.parent_run_id,
+ parent_run_manager=run_manager,
+ tags=child_cm.tags,
+ inheritable_tags=child_cm.inheritable_tags,
+ metadata=child_cm.metadata,
+ inheritable_metadata=child_cm.inheritable_metadata,
+ )
+ try:
+ yield group_cm
+ except Exception as e:
+ if not group_cm.ended:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ if not group_cm.ended:
+ run_manager.on_chain_end({})
+
+
+@asynccontextmanager
+async def atrace_as_chain_group(
+ group_name: str,
+ callback_manager: AsyncCallbackManager | None = None,
+ *,
+ inputs: dict[str, Any] | None = None,
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+) -> AsyncGenerator[AsyncCallbackManagerForChainGroup, None]:
+ """Get an async callback manager for a chain group in a context manager.
+
+ Useful for grouping different async calls together as a single run even if they
+ aren't composed in a single chain.
+
+ Args:
+ group_name: The name of the chain group.
+ callback_manager: The async callback manager to use, which manages tracing and
+ other callback behavior.
+ inputs: The inputs to the chain group.
+ project_name: The name of the project.
+ example_id: The ID of the example.
+ run_id: The ID of the run.
+ tags: The inheritable tags to apply to all runs.
+ metadata: The metadata to apply to all runs.
+
+ Yields:
+ The async callback manager for the chain group.
+
+ !!! note
+
+ Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in
+ LangSmith.
+
+ Example:
+ ```python
+ llm_input = "Foo"
+ async with atrace_as_chain_group(
+ "group_name", inputs={"input": llm_input}
+ ) as manager:
+ # Use the async callback manager for the chain group
+ res = await llm.ainvoke(llm_input, {"callbacks": manager})
+ await manager.on_chain_end({"output": res})
+ ```
+ """
+ from langchain_core.tracers.context import ( # noqa: PLC0415 -- deferred to avoid importing langsmith at module level
+ _get_trace_callbacks,
+ )
+
+ cb = _get_trace_callbacks(
+ project_name, example_id, callback_manager=callback_manager
+ )
+ cm = AsyncCallbackManager.configure(
+ inheritable_callbacks=cb, inheritable_tags=tags, inheritable_metadata=metadata
+ )
+
+ run_manager = await cm.on_chain_start(
+ {"name": group_name}, inputs or {}, run_id=run_id
+ )
+ child_cm = run_manager.get_child()
+ group_cm = AsyncCallbackManagerForChainGroup(
+ child_cm.handlers,
+ child_cm.inheritable_handlers,
+ child_cm.parent_run_id,
+ parent_run_manager=run_manager,
+ tags=child_cm.tags,
+ inheritable_tags=child_cm.inheritable_tags,
+ metadata=child_cm.metadata,
+ inheritable_metadata=child_cm.inheritable_metadata,
+ )
+ try:
+ yield group_cm
+ except Exception as e:
+ if not group_cm.ended:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ if not group_cm.ended:
+ await run_manager.on_chain_end({})
+
+
+Func = TypeVar("Func", bound=Callable)
+
+
+def shielded(func: Func) -> Func:
+ """Makes so an awaitable method is always shielded from cancellation.
+
+ Args:
+ func: The function to shield.
+
+ Returns:
+ The shielded function
+
+ """
+
+ @functools.wraps(func)
+ async def wrapped(*args: Any, **kwargs: Any) -> Any:
+ # Capture the current context to preserve context variables
+ ctx = copy_context()
+
+ # Create the coroutine
+ coro = func(*args, **kwargs)
+
+ # For Python 3.11+, create task with explicit context
+ # For older versions, fallback to original behavior
+ try:
+ # Create a task with the captured context to preserve context variables
+ task = asyncio.create_task(coro, context=ctx) # type: ignore[call-arg, unused-ignore]
+ # `call-arg` used to not fail 3.9 or 3.10 tests
+ return await asyncio.shield(task)
+ except TypeError:
+ # Python < 3.11 fallback - create task normally then shield
+ # This won't preserve context perfectly but is better than nothing
+ task = asyncio.create_task(coro)
+ return await asyncio.shield(task)
+
+ return cast("Func", wrapped)
+
+
+def handle_event(
+ handlers: list[BaseCallbackHandler],
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ """Generic event handler for `CallbackManager`.
+
+ Args:
+ handlers: The list of handlers that will handle the event.
+ event_name: The name of the event (e.g., `'on_llm_start'`).
+ ignore_condition_name: Name of the attribute defined on handler that if `True`
+ will cause the handler to be skipped for the given event.
+ *args: The arguments to pass to the event handler.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ """
+ coros: list[Coroutine[Any, Any, Any]] = []
+
+ try:
+ message_strings: list[str] | None = None
+ for handler in handlers:
+ try:
+ if ignore_condition_name is None or not getattr(
+ handler, ignore_condition_name
+ ):
+ event = getattr(handler, event_name)(*args, **kwargs)
+ if asyncio.iscoroutine(event):
+ coros.append(event)
+ except NotImplementedError as e:
+ if event_name == "on_chat_model_start":
+ if message_strings is None:
+ message_strings = [get_buffer_string(m) for m in args[1]]
+ handle_event(
+ [handler],
+ "on_llm_start",
+ "ignore_llm",
+ args[0],
+ message_strings,
+ *args[2:],
+ **kwargs,
+ )
+ else:
+ handler_name = handler.__class__.__name__
+ logger.warning(
+ "NotImplementedError in %s.%s callback: %s",
+ handler_name,
+ event_name,
+ repr(e),
+ )
+ except Exception as e:
+ logger.warning(
+ "Error in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ if handler.raise_error:
+ raise
+ finally:
+ if coros:
+ try:
+ # Raises RuntimeError if there is no current event loop.
+ asyncio.get_running_loop()
+ loop_running = True
+ except RuntimeError:
+ loop_running = False
+
+ if loop_running:
+ # If we try to submit this coroutine to the running loop
+ # we end up in a deadlock, as we'd have gotten here from a
+ # running coroutine, which we cannot interrupt to run this one.
+ # The solution is to run the synchronous function on the globally shared
+ # thread pool executor to avoid blocking the main event loop.
+ _executor().submit(
+ cast("Callable", copy_context().run), _run_coros, coros
+ ).result()
+ else:
+ # If there's no running loop, we can run the coroutines directly.
+ _run_coros(coros)
+
+
+def _run_coros(coros: list[Coroutine[Any, Any, Any]]) -> None:
+ if hasattr(asyncio, "Runner"):
+ # Python 3.11+
+ # Run the coroutines in a new event loop, taking care to
+ # - install signal handlers
+ # - run pending tasks scheduled by `coros`
+ # - close asyncgens and executors
+ # - close the loop
+ with asyncio.Runner() as runner:
+ # Run the coroutine, get the result
+ for coro in coros:
+ try:
+ runner.run(coro)
+ except Exception as e:
+ logger.warning("Error in callback coroutine: %s", repr(e))
+
+ # Run pending tasks scheduled by coros until they are all done
+ while pending := asyncio.all_tasks(runner.get_loop()):
+ runner.run(asyncio.wait(pending))
+ else:
+ # Before Python 3.11 we need to run each coroutine in a new event loop
+ # as the Runner api is not available.
+ for coro in coros:
+ try:
+ asyncio.run(coro)
+ except Exception as e:
+ logger.warning("Error in callback coroutine: %s", repr(e))
+
+
+async def _ahandle_event_for_handler(
+ handler: BaseCallbackHandler,
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ try:
+ if ignore_condition_name is None or not getattr(handler, ignore_condition_name):
+ event = getattr(handler, event_name)
+ if asyncio.iscoroutinefunction(event):
+ await event(*args, **kwargs)
+ elif handler.run_inline:
+ event(*args, **kwargs)
+ else:
+ await asyncio.get_event_loop().run_in_executor(
+ None,
+ cast(
+ "Callable",
+ functools.partial(copy_context().run, event, *args, **kwargs),
+ ),
+ )
+ except NotImplementedError as e:
+ if event_name == "on_chat_model_start":
+ message_strings = [get_buffer_string(m) for m in args[1]]
+ await _ahandle_event_for_handler(
+ handler,
+ "on_llm_start",
+ "ignore_llm",
+ args[0],
+ message_strings,
+ *args[2:],
+ **kwargs,
+ )
+ else:
+ logger.warning(
+ "NotImplementedError in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ except Exception as e:
+ logger.warning(
+ "Error in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ if handler.raise_error:
+ raise
+
+
+async def ahandle_event(
+ handlers: list[BaseCallbackHandler],
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ """Async generic event handler for `AsyncCallbackManager`.
+
+ Args:
+ handlers: The list of handlers that will handle the event.
+ event_name: The name of the event (e.g., `'on_llm_start'`).
+ ignore_condition_name: Name of the attribute defined on handler that if `True`
+ will cause the handler to be skipped for the given event.
+ *args: The arguments to pass to the event handler.
+ **kwargs: The keyword arguments to pass to the event handler.
+
+ """
+ for handler in [h for h in handlers if h.run_inline]:
+ await _ahandle_event_for_handler(
+ handler, event_name, ignore_condition_name, *args, **kwargs
+ )
+ await asyncio.gather(
+ *(
+ _ahandle_event_for_handler(
+ handler,
+ event_name,
+ ignore_condition_name,
+ *args,
+ **kwargs,
+ )
+ for handler in handlers
+ if not handler.run_inline
+ )
+ )
+
+
+class BaseRunManager(RunManagerMixin):
+ """Base class for run manager (a bound callback manager)."""
+
+ def __init__(
+ self,
+ *,
+ run_id: UUID,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler],
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ inheritable_tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize the run manager.
+
+ Args:
+ run_id: The ID of the run.
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ tags: The list of tags.
+ inheritable_tags: The list of inheritable tags.
+ metadata: The metadata.
+ inheritable_metadata: The inheritable metadata.
+
+ """
+ self.run_id = run_id
+ self.handlers = handlers
+ self.inheritable_handlers = inheritable_handlers
+ self.parent_run_id = parent_run_id
+ self.tags = tags or []
+ self.inheritable_tags = inheritable_tags or []
+ self.metadata = metadata or {}
+ self.inheritable_metadata = inheritable_metadata or {}
+
+ @classmethod
+ def get_noop_manager(cls) -> Self:
+ """Return a manager that doesn't perform any operations.
+
+ Returns:
+ The noop manager.
+
+ """
+ return cls(
+ run_id=uuid7(),
+ handlers=[],
+ inheritable_handlers=[],
+ tags=[],
+ inheritable_tags=[],
+ metadata={},
+ inheritable_metadata={},
+ )
+
+
+class RunManager(BaseRunManager):
+ """Synchronous run manager."""
+
+ def on_text(
+ self,
+ text: str,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a text is received.
+
+ Args:
+ text: The received text.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_text",
+ None,
+ text,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a retry is received.
+
+ Args:
+ retry_state: The retry state.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retry",
+ "ignore_retry",
+ retry_state,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class ParentRunManager(RunManager):
+ """Synchronous parent run manager."""
+
+ def get_child(self, tag: str | None = None) -> CallbackManager:
+ """Get a child callback manager.
+
+ Args:
+ tag: The tag for the child callback manager.
+
+ Returns:
+ The child callback manager.
+
+ """
+ manager = CallbackManager(handlers=[], parent_run_id=self.run_id)
+ manager.set_handlers(self.inheritable_handlers)
+ manager.add_tags(self.inheritable_tags)
+ manager.add_metadata(self.inheritable_metadata)
+ if tag is not None:
+ manager.add_tags([tag], inherit=False)
+ return manager
+
+
+class AsyncRunManager(BaseRunManager, ABC):
+ """Async run manager."""
+
+ @abstractmethod
+ def get_sync(self) -> RunManager:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+
+ async def on_text(
+ self,
+ text: str,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a text is received.
+
+ Args:
+ text: The received text.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_text",
+ None,
+ text,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ **kwargs: Any,
+ ) -> None:
+ """Async run when a retry is received.
+
+ Args:
+ retry_state: The retry state.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retry",
+ "ignore_retry",
+ retry_state,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncParentRunManager(AsyncRunManager):
+ """Async parent run manager."""
+
+ def get_child(self, tag: str | None = None) -> AsyncCallbackManager:
+ """Get a child callback manager.
+
+ Args:
+ tag: The tag for the child callback manager.
+
+ Returns:
+ The child callback manager.
+
+ """
+ manager = AsyncCallbackManager(handlers=[], parent_run_id=self.run_id)
+ manager.set_handlers(self.inheritable_handlers)
+ manager.add_tags(self.inheritable_tags)
+ manager.add_metadata(self.inheritable_metadata)
+ if tag is not None:
+ manager.add_tags([tag], inherit=False)
+ return manager
+
+
+class CallbackManagerForLLMRun(RunManager, LLMManagerMixin):
+ """Callback manager for LLM run."""
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM generates a new token.
+
+ Args:
+ token: The new token.
+ chunk: The chunk.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_new_token",
+ "ignore_llm",
+ token=token,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ chunk=chunk,
+ **kwargs,
+ )
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The LLM result.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_end",
+ "ignore_llm",
+ response,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_error",
+ "ignore_llm",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_stream_event(self, event: MessagesData, **kwargs: Any) -> None:
+ """Run on each protocol event from `stream_events(version="v3")`.
+
+ Args:
+ event: The protocol event.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_stream_event",
+ "ignore_llm",
+ event,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin):
+ """Async callback manager for LLM run."""
+
+ def get_sync(self) -> CallbackManagerForLLMRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+ return CallbackManagerForLLMRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM generates a new token.
+
+ Args:
+ token: The new token.
+ chunk: The chunk.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_new_token",
+ "ignore_llm",
+ token,
+ chunk=chunk,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The LLM result.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_end",
+ "ignore_llm",
+ response,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_error",
+ "ignore_llm",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_stream_event(self, event: MessagesData, **kwargs: Any) -> None:
+ """Run on each protocol event from `astream_events(version="v3")`.
+
+ Args:
+ event: The protocol event.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_stream_event",
+ "ignore_llm",
+ event,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForChainRun(ParentRunManager, ChainManagerMixin):
+ """Callback manager for chain run."""
+
+ def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_chain_end",
+ "ignore_chain",
+ outputs,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_chain_error",
+ "ignore_chain",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
+ """Run when agent action is received.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_agent_action",
+ "ignore_agent",
+ action,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent finish is received.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_agent_finish",
+ "ignore_agent",
+ finish,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForChainRun(AsyncParentRunManager, ChainManagerMixin):
+ """Async callback manager for chain run."""
+
+ def get_sync(self) -> CallbackManagerForChainRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+ """
+ return CallbackManagerForChainRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @shielded
+ async def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_chain_end",
+ "ignore_chain",
+ outputs,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_chain_error",
+ "ignore_chain",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
+ """Run when agent action is received.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_agent_action",
+ "ignore_agent",
+ action,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent finish is received.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_agent_finish",
+ "ignore_agent",
+ finish,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForToolRun(ParentRunManager, ToolManagerMixin):
+ """Callback manager for tool run."""
+
+ def on_tool_end(
+ self,
+ output: Any,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_tool_end",
+ "ignore_agent",
+ output,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_tool_error",
+ "ignore_agent",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForToolRun(AsyncParentRunManager, ToolManagerMixin):
+ """Async callback manager for tool run."""
+
+ def get_sync(self) -> CallbackManagerForToolRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+ """
+ return CallbackManagerForToolRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Async run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_tool_end",
+ "ignore_agent",
+ output,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_tool_error",
+ "ignore_agent",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForRetrieverRun(ParentRunManager, RetrieverManagerMixin):
+ """Callback manager for retriever run."""
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever ends running.
+
+ Args:
+ documents: The retrieved documents.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retriever_end",
+ "ignore_retriever",
+ documents,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retriever_error",
+ "ignore_retriever",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForRetrieverRun(
+ AsyncParentRunManager,
+ RetrieverManagerMixin,
+):
+ """Async callback manager for retriever run."""
+
+ def get_sync(self) -> CallbackManagerForRetrieverRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+ return CallbackManagerForRetrieverRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @shielded
+ async def on_retriever_end(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> None:
+ """Run when the retriever ends running.
+
+ Args:
+ documents: The retrieved documents.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_end",
+ "ignore_retriever",
+ documents,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_error",
+ "ignore_retriever",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManager(BaseCallbackManager):
+ """Callback manager for LangChain."""
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[CallbackManagerForLLMRun]:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The list of prompts.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A callback manager for each prompt as an LLM run.
+
+ """
+ managers = []
+ for i, prompt in enumerate(prompts):
+ # Can't have duplicate runs with the same run ID (if provided)
+ run_id_ = run_id if i == 0 and run_id is not None else uuid7()
+ handle_event(
+ self.handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ managers.append(
+ CallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ return managers
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[CallbackManagerForLLMRun]:
+ """Run when chat model starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The list of messages.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A callback manager for each list of messages as an LLM run.
+
+ """
+ managers = []
+ for message_list in messages:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+ handle_event(
+ self.handlers,
+ "on_chat_model_start",
+ "ignore_chat_model",
+ serialized,
+ [message_list],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ managers.append(
+ CallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ return managers
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any] | None,
+ inputs: dict[str, Any] | Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForChainRun:
+ """Run when chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The callback manager for the chain run.
+
+ """
+ if run_id is None:
+ run_id = uuid7()
+ handle_event(
+ self.handlers,
+ "on_chain_start",
+ "ignore_chain",
+ serialized,
+ inputs,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return CallbackManagerForChainRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForToolRun:
+ """Run when tool starts running.
+
+ Args:
+ serialized: Serialized representation of the tool.
+ input_str: The input to the tool as a string.
+
+ Non-string inputs are cast to strings.
+ run_id: ID for the run.
+ parent_run_id: The ID of the parent run.
+ inputs: The original input to the tool if provided.
+
+ Recommended for usage instead of input_str when the original input is
+ needed.
+
+ If provided, the inputs are expected to be formatted as a dict. The keys
+ will correspond to the named-arguments in the tool.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ Returns:
+ The callback manager for the tool run.
+
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_tool_start",
+ "ignore_agent",
+ serialized,
+ input_str,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ inputs=inputs,
+ **kwargs,
+ )
+
+ return CallbackManagerForToolRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any] | None,
+ query: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForRetrieverRun:
+ """Run when the retriever starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The callback manager for the retriever run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_retriever_start",
+ "ignore_retriever",
+ serialized,
+ query,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return CallbackManagerForRetrieverRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Dispatch an adhoc event to the handlers (async version).
+
+ This event should NOT be used in any internal LangChain code. The event is meant
+ specifically for users of the library to dispatch custom events that are
+ tailored to their application.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+ run_id: The ID of the run.
+
+ Raises:
+ ValueError: If additional keyword arguments are passed.
+ """
+ if not self.handlers:
+ return
+ if kwargs:
+ msg = (
+ "The dispatcher API does not accept additional keyword arguments."
+ "Please do not pass any additional keyword arguments, instead "
+ "include them in the data field."
+ )
+ raise ValueError(msg)
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_custom_event",
+ "ignore_custom_event",
+ name,
+ data,
+ run_id=run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ )
+
+ @classmethod
+ def configure(
+ cls,
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ verbose: bool = False, # noqa: FBT001,FBT002
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+ ) -> CallbackManager:
+ """Configure the callback manager.
+
+ Args:
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ verbose: Whether to enable verbose mode.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ langsmith_inheritable_metadata: Default inheritable metadata applied
+ to any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Returns:
+ The configured callback manager.
+ """
+ return _configure(
+ cls,
+ inheritable_callbacks,
+ local_callbacks,
+ inheritable_tags,
+ local_tags,
+ inheritable_metadata,
+ local_metadata,
+ verbose=verbose,
+ langsmith_inheritable_metadata=langsmith_inheritable_metadata,
+ langsmith_inheritable_tags=langsmith_inheritable_tags,
+ )
+
+
+class CallbackManagerForChainGroup(CallbackManager):
+ """Callback manager for the chain group."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ parent_run_manager: CallbackManagerForChainRun,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the callback manager.
+
+ Args:
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ parent_run_manager: The parent run manager.
+ **kwargs: Additional keyword arguments.
+
+ """
+ super().__init__(
+ handlers,
+ inheritable_handlers,
+ parent_run_id,
+ **kwargs,
+ )
+ self.parent_run_manager = parent_run_manager
+ self.ended = False
+
+ @override
+ def copy(self) -> CallbackManagerForChainGroup:
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ def merge(
+ self: CallbackManagerForChainGroup, other: BaseCallbackManager
+ ) -> CallbackManagerForChainGroup:
+ """Merge the group callback manager with another callback manager.
+
+ Overwrites the merge method in the base class to ensure that the parent run
+ manager is preserved. Keeps the `parent_run_manager` from the current object.
+
+ Returns:
+ A copy of the current object with the handlers, tags, and other attributes
+ merged from the other object.
+
+ Example:
+ ```python
+ # Merging two callback managers
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ trace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(type(merged_manager))
+ #
+
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ manager = self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=[],
+ inheritable_handlers=[],
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ handlers = self.handlers + other.handlers
+ inheritable_handlers = self.inheritable_handlers + other.inheritable_handlers
+
+ for handler in handlers:
+ manager.add_handler(handler)
+
+ for handler in inheritable_handlers:
+ manager.add_handler(handler, inherit=True)
+ return manager
+
+ def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when traced chain group ends.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self.ended = True
+ return self.parent_run_manager.on_chain_end(outputs, **kwargs)
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self.ended = True
+ return self.parent_run_manager.on_chain_error(error, **kwargs)
+
+
+class AsyncCallbackManager(BaseCallbackManager):
+ """Async callback manager that handles callbacks from LangChain."""
+
+ @property
+ def is_async(self) -> bool:
+ """Return whether the handler is async."""
+ return True
+
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[AsyncCallbackManagerForLLMRun]:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The list of prompts.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The list of async callback managers, one for each LLM run corresponding to
+ each prompt.
+ """
+ inline_tasks = []
+ non_inline_tasks = []
+ inline_handlers = [handler for handler in self.handlers if handler.run_inline]
+ non_inline_handlers = [
+ handler for handler in self.handlers if not handler.run_inline
+ ]
+ managers = []
+
+ for prompt in prompts:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+
+ if inline_handlers:
+ inline_tasks.append(
+ ahandle_event(
+ inline_handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ )
+ else:
+ non_inline_tasks.append(
+ ahandle_event(
+ non_inline_handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ )
+
+ managers.append(
+ AsyncCallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ # Run inline tasks sequentially
+ for inline_task in inline_tasks:
+ await inline_task
+
+ # Run non-inline tasks concurrently
+ if non_inline_tasks:
+ await asyncio.gather(*non_inline_tasks)
+
+ return managers
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[AsyncCallbackManagerForLLMRun]:
+ """Async run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The list of messages.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The list of async callback managers, one for each LLM run corresponding to
+ each inner message list.
+ """
+ inline_tasks = []
+ non_inline_tasks = []
+ managers = []
+
+ for message_list in messages:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+
+ for handler in self.handlers:
+ task = ahandle_event(
+ [handler],
+ "on_chat_model_start",
+ "ignore_chat_model",
+ serialized,
+ [message_list],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ if handler.run_inline:
+ inline_tasks.append(task)
+ else:
+ non_inline_tasks.append(task)
+
+ managers.append(
+ AsyncCallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ # Run inline tasks sequentially
+ for task in inline_tasks:
+ await task
+
+ # Run non-inline tasks concurrently
+ if non_inline_tasks:
+ await asyncio.gather(*non_inline_tasks)
+
+ return managers
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any] | None,
+ inputs: dict[str, Any] | Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForChainRun:
+ """Async run when chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the chain run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_chain_start",
+ "ignore_chain",
+ serialized,
+ inputs,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForChainRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForToolRun:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input to the tool.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the tool run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_tool_start",
+ "ignore_agent",
+ serialized,
+ input_str,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForToolRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Dispatch an adhoc event to the handlers (async version).
+
+ This event should NOT be used in any internal LangChain code. The event is meant
+ specifically for users of the library to dispatch custom events that are
+ tailored to their application.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+ run_id: The ID of the run.
+
+ Raises:
+ ValueError: If additional keyword arguments are passed.
+ """
+ if not self.handlers:
+ return
+ if run_id is None:
+ run_id = uuid7()
+
+ if kwargs:
+ msg = (
+ "The dispatcher API does not accept additional keyword arguments."
+ "Please do not pass any additional keyword arguments, instead "
+ "include them in the data field."
+ )
+ raise ValueError(msg)
+ await ahandle_event(
+ self.handlers,
+ "on_custom_event",
+ "ignore_custom_event",
+ name,
+ data,
+ run_id=run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ )
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any] | None,
+ query: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForRetrieverRun:
+ """Run when the retriever starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the retriever run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_start",
+ "ignore_retriever",
+ serialized,
+ query,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForRetrieverRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @classmethod
+ def configure(
+ cls,
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ verbose: bool = False, # noqa: FBT001,FBT002
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+ ) -> AsyncCallbackManager:
+ """Configure the async callback manager.
+
+ Args:
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ verbose: Whether to enable verbose mode.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ langsmith_inheritable_metadata: Default inheritable metadata applied
+ to any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Returns:
+ The configured async callback manager.
+ """
+ return _configure(
+ cls,
+ inheritable_callbacks,
+ local_callbacks,
+ inheritable_tags,
+ local_tags,
+ inheritable_metadata,
+ local_metadata,
+ verbose=verbose,
+ langsmith_inheritable_metadata=langsmith_inheritable_metadata,
+ langsmith_inheritable_tags=langsmith_inheritable_tags,
+ )
+
+
+class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):
+ """Async callback manager for the chain group."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ parent_run_manager: AsyncCallbackManagerForChainRun,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the async callback manager.
+
+ Args:
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ parent_run_manager: The parent run manager.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(
+ handlers,
+ inheritable_handlers,
+ parent_run_id,
+ **kwargs,
+ )
+ self.parent_run_manager = parent_run_manager
+ self.ended = False
+
+ def copy(self) -> AsyncCallbackManagerForChainGroup:
+ """Return a copy the async callback manager."""
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ def merge(
+ self: AsyncCallbackManagerForChainGroup, other: BaseCallbackManager
+ ) -> AsyncCallbackManagerForChainGroup:
+ """Merge the group callback manager with another callback manager.
+
+ Overwrites the merge method in the base class to ensure that the parent run
+ manager is preserved. Keeps the `parent_run_manager` from the current object.
+
+ Returns:
+ A copy of the current `AsyncCallbackManagerForChainGroup` with the handlers,
+ tags, etc. of the other callback manager merged in.
+
+ Example:
+ ```python
+ # Merging two callback managers
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ atrace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ async with atrace_as_chain_group(
+ "My Group Name", tags=["tag1"]
+ ) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(type(merged_manager))
+ #
+
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ manager = self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=[],
+ inheritable_handlers=[],
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ handlers = self.handlers + other.handlers
+ inheritable_handlers = self.inheritable_handlers + other.inheritable_handlers
+
+ for handler in handlers:
+ manager.add_handler(handler)
+
+ for handler in inheritable_handlers:
+ manager.add_handler(handler, inherit=True)
+ return manager
+
+ async def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when traced chain group ends.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ self.ended = True
+ await self.parent_run_manager.on_chain_end(outputs, **kwargs)
+
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+ """
+ self.ended = True
+ await self.parent_run_manager.on_chain_error(error, **kwargs)
+
+
+T = TypeVar("T", CallbackManager, AsyncCallbackManager)
+
+
+def _configure(
+ callback_manager_cls: type[T],
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ verbose: bool = False,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+) -> T:
+ """Configure the callback manager.
+
+ Args:
+ callback_manager_cls: The callback manager class.
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ verbose: Whether to enable verbose mode.
+ langsmith_inheritable_metadata: Default inheritable metadata applied to
+ any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Raises:
+ RuntimeError: If `LANGCHAIN_TRACING` is set but `LANGCHAIN_TRACING_V2` is not.
+
+ Returns:
+ The configured callback manager.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import get_tracing_context # noqa: PLC0415
+
+ from langchain_core.tracers.context import ( # noqa: PLC0415
+ _configure_hooks,
+ _get_tracer_project,
+ _tracing_v2_is_enabled,
+ tracing_v2_callback_var,
+ )
+ from langchain_core.tracers.langchain import LangChainTracer # noqa: PLC0415
+ from langchain_core.tracers.stdout import ConsoleCallbackHandler # noqa: PLC0415
+
+ tracing_context = get_tracing_context()
+ tracing_metadata = tracing_context["metadata"]
+ tracing_tags = tracing_context["tags"]
+ run_tree: Run | None = tracing_context["parent"]
+ parent_run_id = None if run_tree is None else run_tree.id
+ callback_manager = callback_manager_cls(
+ handlers=[],
+ parent_run_id=parent_run_id,
+ )
+ if inheritable_callbacks or local_callbacks:
+ if isinstance(inheritable_callbacks, list) or inheritable_callbacks is None:
+ inheritable_callbacks_ = inheritable_callbacks or []
+ callback_manager = callback_manager_cls(
+ handlers=inheritable_callbacks_.copy(),
+ inheritable_handlers=inheritable_callbacks_.copy(),
+ parent_run_id=parent_run_id,
+ )
+ else:
+ parent_run_id_ = inheritable_callbacks.parent_run_id
+ # Break ties between the external tracing context and inherited context
+ if parent_run_id is not None and (
+ parent_run_id_ is None
+ # If the LC parent has already been reflected
+ # in the run tree, we know the run_tree is either the
+ # same parent or a child of the parent.
+ or (run_tree and str(parent_run_id_) in run_tree.dotted_order)
+ ):
+ parent_run_id_ = parent_run_id
+ # Otherwise, we assume the LC context has progressed
+ # beyond the run tree and we should not inherit the parent.
+ callback_manager = callback_manager_cls(
+ handlers=inheritable_callbacks.handlers.copy(),
+ inheritable_handlers=inheritable_callbacks.inheritable_handlers.copy(),
+ parent_run_id=parent_run_id_,
+ tags=inheritable_callbacks.tags.copy(),
+ inheritable_tags=inheritable_callbacks.inheritable_tags.copy(),
+ metadata=inheritable_callbacks.metadata.copy(),
+ inheritable_metadata=inheritable_callbacks.inheritable_metadata.copy(),
+ )
+ local_handlers_ = (
+ local_callbacks
+ if isinstance(local_callbacks, list)
+ else (local_callbacks.handlers if local_callbacks else [])
+ )
+ for handler in local_handlers_:
+ callback_manager.add_handler(handler, inherit=False)
+ if inheritable_tags or local_tags:
+ callback_manager.add_tags(inheritable_tags or [])
+ callback_manager.add_tags(local_tags or [], inherit=False)
+ if inheritable_metadata or local_metadata:
+ callback_manager.add_metadata(inheritable_metadata or {})
+ callback_manager.add_metadata(local_metadata or {}, inherit=False)
+ if tracing_tags:
+ callback_manager.add_tags(tracing_tags.copy())
+
+ v1_tracing_enabled_ = env_var_is_set("LANGCHAIN_TRACING") or env_var_is_set(
+ "LANGCHAIN_HANDLER"
+ )
+
+ tracer_v2 = tracing_v2_callback_var.get()
+ tracing_v2_enabled_ = _tracing_v2_is_enabled()
+
+ if v1_tracing_enabled_ and not tracing_v2_enabled_:
+ # if both are enabled, can silently ignore the v1 tracer
+ msg = (
+ "Tracing using LangChainTracerV1 is no longer supported. "
+ "Please set the LANGCHAIN_TRACING_V2 environment variable to enable "
+ "tracing instead."
+ )
+ raise RuntimeError(msg)
+
+ tracer_project = _get_tracer_project()
+ debug = _get_debug()
+ if verbose or debug or tracing_v2_enabled_:
+ if verbose and not any(
+ isinstance(handler, StdOutCallbackHandler)
+ for handler in callback_manager.handlers
+ ):
+ if debug:
+ pass
+ else:
+ callback_manager.add_handler(StdOutCallbackHandler(), inherit=False)
+ if debug and not any(
+ isinstance(handler, ConsoleCallbackHandler)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(ConsoleCallbackHandler())
+ if tracing_v2_enabled_ and not any(
+ isinstance(handler, LangChainTracer)
+ for handler in callback_manager.handlers
+ ):
+ if tracer_v2:
+ callback_manager.add_handler(tracer_v2)
+ else:
+ try:
+ handler = LangChainTracer(
+ project_name=tracer_project,
+ client=(
+ run_tree.client
+ if run_tree is not None
+ else tracing_context["client"]
+ ),
+ tags=tracing_tags,
+ metadata=tracing_metadata,
+ )
+ callback_manager.add_handler(handler)
+ except Exception as e:
+ logger.warning(
+ "Unable to load requested LangChainTracer."
+ " To disable this warning,"
+ " unset the LANGCHAIN_TRACING_V2 environment variables.\n"
+ "%s",
+ repr(e),
+ )
+ if run_tree is not None:
+ for handler in callback_manager.handlers:
+ if isinstance(handler, LangChainTracer):
+ handler.order_map[run_tree.id] = (
+ run_tree.trace_id,
+ run_tree.dotted_order,
+ )
+ run_id_str = str(run_tree.id)
+ if run_id_str not in handler.run_map:
+ handler.run_map[run_id_str] = run_tree
+ handler._external_run_ids.setdefault( # noqa: SLF001
+ run_id_str, 0
+ )
+ for var, inheritable, handler_class, env_var in _configure_hooks:
+ create_one = (
+ env_var is not None
+ and env_var_is_set(env_var)
+ and handler_class is not None
+ )
+ if var.get() is not None or create_one:
+ var_handler = (
+ var.get() or cast("type[BaseCallbackHandler]", handler_class)()
+ )
+ if handler_class is None:
+ if not any(
+ handler is var_handler # direct pointer comparison
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(var_handler, inheritable)
+ elif not any(
+ isinstance(handler, handler_class)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(var_handler, inheritable)
+
+ if tracing_metadata:
+ langsmith_inheritable_metadata = {
+ **tracing_metadata,
+ **(langsmith_inheritable_metadata or {}),
+ }
+
+ if langsmith_inheritable_metadata or langsmith_inheritable_tags:
+ callback_manager.handlers = [
+ handler.copy_with_metadata_defaults(
+ metadata=langsmith_inheritable_metadata,
+ tags=langsmith_inheritable_tags,
+ )
+ if isinstance(handler, LangChainTracer)
+ else handler
+ for handler in callback_manager.handlers
+ ]
+ callback_manager.inheritable_handlers = [
+ handler.copy_with_metadata_defaults(
+ metadata=langsmith_inheritable_metadata,
+ tags=langsmith_inheritable_tags,
+ )
+ if isinstance(handler, LangChainTracer)
+ else handler
+ for handler in callback_manager.inheritable_handlers
+ ]
+ return callback_manager
+
+
+async def adispatch_custom_event(
+ name: str, data: Any, *, config: RunnableConfig | None = None
+) -> None:
+ """Dispatch an adhoc event to the handlers.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+
+ Free form data. Ideally should be JSON serializable to avoid serialization
+ issues downstream, but this is not enforced.
+ config: Optional config object.
+
+ Mirrors the async API but not strictly needed.
+
+ Raises:
+ RuntimeError: If there is no parent run ID available to associate the event
+ with.
+
+ Example:
+ ```python
+ from langchain_core.callbacks import (
+ AsyncCallbackHandler,
+ adispatch_custom_event
+ )
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(AsyncCallbackHandler):
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ callback = CustomCallbackManager()
+
+ async def foo(inputs):
+ await adispatch_custom_event("my_event", {"bar": "buzz})
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+ await foo_.ainvoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
+ ```
+
+ Example: Use with astream events
+
+ ```python
+ from langchain_core.callbacks import (
+ AsyncCallbackHandler,
+ adispatch_custom_event
+ )
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(AsyncCallbackHandler):
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ callback = CustomCallbackManager()
+
+ async def foo(inputs):
+ await adispatch_custom_event("event_type_1", {"bar": "buzz})
+ await adispatch_custom_event("event_type_2", 5)
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+
+ async for event in foo_.ainvoke_stream(
+ {"a": "1"},
+ version="v2",
+ config={"callbacks": [CustomCallbackManager()]}
+ ):
+ print(event)
+ ```
+
+ !!! warning
+
+ If using python 3.10 and async, you MUST specify the `config` parameter or the
+ function will raise an error. This is due to a limitation in asyncio for python
+ 3.10 that prevents LangChain from automatically propagating the config object on
+ the user's behalf.
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.runnables.config import ( # noqa: PLC0415
+ ensure_config,
+ get_async_callback_manager_for_config,
+ )
+
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # We want to get the callback manager for the parent run.
+ # This is a work-around for now to be able to dispatch adhoc events from
+ # within a tool or a lambda and have the metadata events associated
+ # with the parent run rather than have a new run id generated for each.
+ if callback_manager.parent_run_id is None:
+ msg = (
+ "Unable to dispatch an adhoc event without a parent run id."
+ "This function can only be called from within an existing run (e.g.,"
+ "inside a tool or a RunnableLambda or a RunnableGenerator.)"
+ "If you are doing that and still seeing this error, try explicitly"
+ "passing the config parameter to this function."
+ )
+ raise RuntimeError(msg)
+
+ await callback_manager.on_custom_event(
+ name,
+ data,
+ run_id=callback_manager.parent_run_id,
+ )
+
+
+def dispatch_custom_event(
+ name: str, data: Any, *, config: RunnableConfig | None = None
+) -> None:
+ """Dispatch an adhoc event.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+
+ Free form data. Ideally should be JSON serializable to avoid serialization
+ issues downstream, but this is not enforced.
+ config: Optional config object.
+
+ Mirrors the async API but not strictly needed.
+
+ Raises:
+ RuntimeError: If there is no parent run ID available to associate the event
+ with.
+
+ Example:
+ ```python
+ from langchain_core.callbacks import BaseCallbackHandler
+ from langchain_core.callbacks import dispatch_custom_event
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(BaseCallbackHandler):
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ def foo(inputs):
+ dispatch_custom_event("my_event", {"bar": "buzz})
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+ foo_.invoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
+ ```
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.runnables.config import ( # noqa: PLC0415
+ ensure_config,
+ get_callback_manager_for_config,
+ )
+
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # We want to get the callback manager for the parent run.
+ # This is a work-around for now to be able to dispatch adhoc events from
+ # within a tool or a lambda and have the metadata events associated
+ # with the parent run rather than have a new run id generated for each.
+ if callback_manager.parent_run_id is None:
+ msg = (
+ "Unable to dispatch an adhoc event without a parent run id."
+ "This function can only be called from within an existing run (e.g.,"
+ "inside a tool or a RunnableLambda or a RunnableGenerator.)"
+ "If you are doing that and still seeing this error, try explicitly"
+ "passing the config parameter to this function."
+ )
+ raise RuntimeError(msg)
+ callback_manager.on_custom_event(
+ name,
+ data,
+ run_id=callback_manager.parent_run_id,
+ )
+
+
+@functools.lru_cache(maxsize=1)
+def _executor() -> ThreadPoolExecutor:
+ # If the user is specifying ASYNC callback handlers to be run from a
+ # SYNC context, and an event loop is already running,
+ # we cannot submit the coroutine to the running loop, because it
+ # would result in a deadlock. Instead we have to schedule them
+ # on a background thread. To avoid creating & shutting down
+ # a new executor every time, we use a lazily-created, shared
+ # executor. If you're using regular langgchain parallelism (batch, etc.)
+ # you'd only ever need 1 worker, but we permit more for now to reduce the chance
+ # of slowdown if you are mixing with your own executor.
+ cutie = ThreadPoolExecutor(max_workers=10)
+ atexit.register(cutie.shutdown, wait=True)
+ return cutie
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/stdout.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cfce2ce7c4c1184a741cde813c7e21a1cd54df7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/stdout.py
@@ -0,0 +1,123 @@
+"""Callback handler that prints to std out."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import BaseCallbackHandler
+from langchain_core.utils import print_text
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+
+
+class StdOutCallbackHandler(BaseCallbackHandler):
+ """Callback handler that prints to std out."""
+
+ def __init__(self, color: str | None = None) -> None:
+ """Initialize callback handler.
+
+ Args:
+ color: The color to use for the text.
+ """
+ self.color = color
+
+ @override
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print out that we are entering a chain.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ if "name" in kwargs:
+ name = kwargs["name"]
+ elif serialized:
+ name = serialized.get("name", serialized.get("id", [""])[-1])
+ else:
+ name = ""
+ print(f"\n\n\033[1m> Entering new {name} chain...\033[0m") # noqa: T201
+
+ @override
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Print out that we finished a chain.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ print("\n\033[1m> Finished chain.\033[0m") # noqa: T201
+
+ @override
+ def on_agent_action(
+ self, action: AgentAction, color: str | None = None, **kwargs: Any
+ ) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ color: The color to use for the text.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(action.log, color=color or self.color)
+
+ @override
+ def on_tool_end(
+ self,
+ output: Any,
+ color: str | None = None,
+ observation_prefix: str | None = None,
+ llm_prefix: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """If not the final action, print out observation.
+
+ Args:
+ output: The output to print.
+ color: The color to use for the text.
+ observation_prefix: The observation prefix.
+ llm_prefix: The LLM prefix.
+ **kwargs: Additional keyword arguments.
+ """
+ output = str(output)
+ if observation_prefix is not None:
+ print_text(f"\n{observation_prefix}")
+ print_text(output, color=color or self.color)
+ if llm_prefix is not None:
+ print_text(f"\n{llm_prefix}")
+
+ @override
+ def on_text(
+ self,
+ text: str,
+ color: str | None = None,
+ end: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when the agent ends.
+
+ Args:
+ text: The text to print.
+ color: The color to use for the text.
+ end: The end character to use.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(text, color=color or self.color, end=end)
+
+ @override
+ def on_agent_finish(
+ self, finish: AgentFinish, color: str | None = None, **kwargs: Any
+ ) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ color: The color to use for the text.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(finish.log, color=color or self.color, end="\n")
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/streaming_stdout.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/streaming_stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..920fef80bde70e6ca3cfe4912920263c4bf3b335
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/streaming_stdout.py
@@ -0,0 +1,152 @@
+"""Callback Handler streams to stdout on new llm token."""
+
+from __future__ import annotations
+
+import sys
+from typing import TYPE_CHECKING, Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import BaseCallbackHandler
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import LLMResult
+
+
+class StreamingStdOutCallbackHandler(BaseCallbackHandler):
+ """Callback handler for streaming.
+
+ !!! warning "Only works with LLMs that support streaming."
+ """
+
+ def on_llm_start(
+ self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts to run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The messages to run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ @override
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run on new LLM token. Only available when streaming is enabled.
+
+ Args:
+ token: The new token.
+ **kwargs: Additional keyword arguments.
+ """
+ sys.stdout.write(token)
+ sys.stdout.flush()
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The response from the LLM.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_start(
+ self, serialized: dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text to print.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
diff --git a/python/user_packages/Python313/site-packages/langchain_core/callbacks/usage.py b/python/user_packages/Python313/site-packages/langchain_core/callbacks/usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef1dd78e600645a7019844923b36993ff21de691
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/callbacks/usage.py
@@ -0,0 +1,149 @@
+"""Callback Handler that tracks `AIMessage.usage_metadata`."""
+
+import threading
+from collections.abc import Generator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import AIMessage
+from langchain_core.messages.ai import UsageMetadata, add_usage
+from langchain_core.outputs import ChatGeneration, LLMResult
+from langchain_core.tracers.context import register_configure_hook
+
+
+class UsageMetadataCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that tracks `AIMessage.usage_metadata`.
+
+ Example:
+ ```python
+ from langchain.chat_models import init_chat_model
+ from langchain_core.callbacks import UsageMetadataCallbackHandler
+
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
+ llm_2 = init_chat_model(model="anthropic:claude-haiku-4-5-20251001")
+
+ callback = UsageMetadataCallbackHandler()
+ result_1 = llm_1.invoke("Hello", config={"callbacks": [callback]})
+ result_2 = llm_2.invoke("Hello", config={"callbacks": [callback]})
+ callback.usage_metadata
+ ```
+
+ ```txt
+ {'gpt-4o-mini-2024-07-18': {'input_tokens': 8,
+ 'output_tokens': 10,
+ 'total_tokens': 18,
+ 'input_token_details': {'audio': 0, 'cache_read': 0},
+ 'output_token_details': {'audio': 0, 'reasoning': 0}},
+ 'claude-haiku-4-5-20251001': {'input_tokens': 8,
+ 'output_tokens': 21,
+ 'total_tokens': 29,
+ 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.49"
+
+ """
+
+ def __init__(self) -> None:
+ """Initialize the `UsageMetadataCallbackHandler`."""
+ super().__init__()
+ self._lock = threading.Lock()
+ self.usage_metadata: dict[str, UsageMetadata] = {}
+
+ @override
+ def __repr__(self) -> str:
+ return str(self.usage_metadata)
+
+ @override
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Collect token usage."""
+ # Check for usage_metadata (langchain-core >= 0.2.2)
+ try:
+ generation = response.generations[0][0]
+ except IndexError:
+ generation = None
+
+ usage_metadata = None
+ model_name = None
+ if isinstance(generation, ChatGeneration):
+ try:
+ message = generation.message
+ if isinstance(message, AIMessage):
+ usage_metadata = message.usage_metadata
+ model_name = message.response_metadata.get("model_name")
+ except AttributeError:
+ pass
+
+ # update shared state behind lock
+ if usage_metadata and model_name:
+ with self._lock:
+ if model_name not in self.usage_metadata:
+ self.usage_metadata[model_name] = usage_metadata
+ else:
+ self.usage_metadata[model_name] = add_usage(
+ self.usage_metadata[model_name], usage_metadata
+ )
+
+
+@contextmanager
+def get_usage_metadata_callback(
+ name: str = "usage_metadata_callback",
+) -> Generator[UsageMetadataCallbackHandler, None, None]:
+ """Get usage metadata callback.
+
+ Get context manager for tracking usage metadata across chat model calls using
+ [`AIMessage.usage_metadata`][langchain.messages.AIMessage.usage_metadata].
+
+ Args:
+ name: The name of the context variable.
+
+ Yields:
+ The usage metadata callback.
+
+ Example:
+ ```python
+ from langchain.chat_models import init_chat_model
+ from langchain_core.callbacks import get_usage_metadata_callback
+
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
+ llm_2 = init_chat_model(model="anthropic:claude-haiku-4-5-20251001")
+
+ with get_usage_metadata_callback() as cb:
+ llm_1.invoke("Hello")
+ llm_2.invoke("Hello")
+ print(cb.usage_metadata)
+ ```
+
+ ```txt
+ {
+ "gpt-4o-mini-2024-07-18": {
+ "input_tokens": 8,
+ "output_tokens": 10,
+ "total_tokens": 18,
+ "input_token_details": {"audio": 0, "cache_read": 0},
+ "output_token_details": {"audio": 0, "reasoning": 0},
+ },
+ "claude-haiku-4-5-20251001": {
+ "input_tokens": 8,
+ "output_tokens": 21,
+ "total_tokens": 29,
+ "input_token_details": {"cache_read": 0, "cache_creation": 0},
+ },
+ }
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.49"
+
+ """
+ usage_metadata_callback_var: ContextVar[UsageMetadataCallbackHandler | None] = (
+ ContextVar(name, default=None)
+ )
+ register_configure_hook(usage_metadata_callback_var, inheritable=True)
+ cb = UsageMetadataCallbackHandler()
+ usage_metadata_callback_var.set(cb)
+ yield cb
+ usage_metadata_callback_var.set(None)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e591df947483c4c77630182906575fe5411a5dd4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__init__.py
@@ -0,0 +1,39 @@
+"""Document loaders."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.document_loaders.base import BaseBlobParser, BaseLoader
+ from langchain_core.document_loaders.blob_loaders import Blob, BlobLoader, PathLike
+ from langchain_core.document_loaders.langsmith import LangSmithLoader
+
+__all__ = (
+ "BaseBlobParser",
+ "BaseLoader",
+ "Blob",
+ "BlobLoader",
+ "LangSmithLoader",
+ "PathLike",
+)
+
+_dynamic_imports = {
+ "BaseBlobParser": "base",
+ "BaseLoader": "base",
+ "Blob": "blob_loaders",
+ "BlobLoader": "blob_loaders",
+ "PathLike": "blob_loaders",
+ "LangSmithLoader": "langsmith",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5b0d1c2267be686972dcfb35e3dc0e37eda171f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..306e7f55b96556c0f4ff28ebd25f22bcd4fc257f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b68bbf03ee359c6fccfb6dadc37cd0bd90b05f5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63edf76dca08f459fad50caa9619030734238b45
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/base.py b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..448c85988dc97b398e2150093e6c43a26a3065ea
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/base.py
@@ -0,0 +1,155 @@
+"""Abstract interface for document loader implementations."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_text_splitters import TextSplitter
+
+ from langchain_core.documents import Document
+ from langchain_core.documents.base import Blob
+
+try:
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
+
+ _HAS_TEXT_SPLITTERS = True
+except ImportError:
+ _HAS_TEXT_SPLITTERS = False
+
+
+class BaseLoader(ABC): # noqa: B024
+ """Interface for document loader.
+
+ Implementations should implement the lazy-loading method using generators to avoid
+ loading all documents into memory at once.
+
+ `load` is provided just for user convenience and should not be overridden.
+ """
+
+ # Sub-classes should not implement this method directly. Instead, they
+ # should implement the lazy load method.
+ def load(self) -> list[Document]:
+ """Load data into `Document` objects.
+
+ Returns:
+ The documents.
+ """
+ return list(self.lazy_load())
+
+ async def aload(self) -> list[Document]:
+ """Load data into `Document` objects.
+
+ Returns:
+ The documents.
+ """
+ return [document async for document in self.alazy_load()]
+
+ def load_and_split(
+ self, text_splitter: TextSplitter | None = None
+ ) -> list[Document]:
+ """Load `Document` and split into chunks. Chunks are returned as `Document`.
+
+ !!! danger
+
+ Do not override this method. It should be considered to be deprecated!
+
+ Args:
+ text_splitter: `TextSplitter` instance to use for splitting documents.
+
+ Defaults to `RecursiveCharacterTextSplitter`.
+
+ Raises:
+ ImportError: If `langchain-text-splitters` is not installed and no
+ `text_splitter` is provided.
+
+ Returns:
+ List of `Document` objects.
+ """
+ if text_splitter is None:
+ if not _HAS_TEXT_SPLITTERS:
+ msg = (
+ "Unable to import from langchain_text_splitters. Please specify "
+ "text_splitter or install langchain_text_splitters with "
+ "`pip install -U langchain-text-splitters`."
+ )
+ raise ImportError(msg)
+
+ text_splitter_: TextSplitter = RecursiveCharacterTextSplitter()
+ else:
+ text_splitter_ = text_splitter
+ docs = self.load()
+ return text_splitter_.split_documents(docs)
+
+ # Attention: This method will be upgraded into an abstractmethod once it's
+ # implemented in all the existing subclasses.
+ def lazy_load(self) -> Iterator[Document]:
+ """A lazy loader for `Document`.
+
+ Yields:
+ The `Document` objects.
+ """
+ if type(self).load != BaseLoader.load:
+ return iter(self.load())
+ msg = f"{self.__class__.__name__} does not implement lazy_load()"
+ raise NotImplementedError(msg)
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """A lazy loader for `Document`.
+
+ Yields:
+ The `Document` objects.
+ """
+ iterator = await run_in_executor(None, self.lazy_load)
+ done = object()
+ while True:
+ doc = await run_in_executor(None, next, iterator, done)
+ if doc is done:
+ break
+ yield doc # type: ignore[misc]
+
+
+class BaseBlobParser(ABC):
+ """Abstract interface for blob parsers.
+
+ A blob parser provides a way to parse raw data stored in a blob into one or more
+ `Document` objects.
+
+ The parser can be composed with blob loaders, making it easy to reuse a parser
+ independent of how the blob was originally loaded.
+ """
+
+ @abstractmethod
+ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
+ """Lazy parsing interface.
+
+ Subclasses are required to implement this method.
+
+ Args:
+ blob: `Blob` instance
+
+ Returns:
+ Generator of `Document` objects
+ """
+
+ def parse(self, blob: Blob) -> list[Document]:
+ """Eagerly parse the blob into a `Document` or list of `Document` objects.
+
+ This is a convenience method for interactive development environment.
+
+ Production applications should favor the `lazy_parse` method instead.
+
+ Subclasses should generally not over-ride this parse method.
+
+ Args:
+ blob: `Blob` instance
+
+ Returns:
+ List of `Document` objects
+ """
+ return list(self.lazy_parse(blob))
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/blob_loaders.py b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/blob_loaders.py
new file mode 100644
index 0000000000000000000000000000000000000000..399cd4a91da3019f1753543f2056b7537d759256
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/blob_loaders.py
@@ -0,0 +1,38 @@
+"""Schema for Blobs and Blob Loaders.
+
+The goal is to facilitate decoupling of content loading from content parsing code. In
+addition, content loading code should provide a lazy loading interface by default.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+# Re-export Blob and PathLike for backwards compatibility
+from langchain_core.documents.base import Blob, PathLike
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+
+class BlobLoader(ABC):
+ """Abstract interface for blob loaders implementation.
+
+ Implementer should be able to load raw content from a storage system according to
+ some criteria and return the raw content lazily as a stream of blobs.
+ """
+
+ @abstractmethod
+ def yield_blobs(
+ self,
+ ) -> Iterator[Blob]:
+ """A lazy loader for raw data represented by LangChain's `Blob` object.
+
+ Yields:
+ `Blob` objects.
+ """
+
+
+# Re-export Blob and Pathlike for backwards compatibility
+__all__ = ["Blob", "BlobLoader", "PathLike"]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/document_loaders/langsmith.py b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/langsmith.py
new file mode 100644
index 0000000000000000000000000000000000000000..23a44e05d40e58d76c46d44566ec9064eda68f4d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/document_loaders/langsmith.py
@@ -0,0 +1,143 @@
+"""LangSmith document loader."""
+
+import datetime
+import json
+import uuid
+from collections.abc import Callable, Iterator, Sequence
+from typing import Any
+
+from langsmith import Client as LangSmithClient
+from typing_extensions import override
+
+from langchain_core.document_loaders.base import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.tracers._compat import pydantic_to_dict
+
+
+class LangSmithLoader(BaseLoader):
+ """Load LangSmith Dataset examples as `Document` objects.
+
+ Loads the example inputs as the `Document` page content and places the entire
+ example into the `Document` metadata. This allows you to easily create few-shot
+ example retrievers from the loaded documents.
+
+ ??? example "Lazy loading"
+
+ ```python
+ from langchain_core.document_loaders import LangSmithLoader
+
+ loader = LangSmithLoader(dataset_id="...", limit=100)
+ docs = []
+ for doc in loader.lazy_load():
+ docs.append(doc)
+ ```
+
+ ```python
+ # -> [Document("...", metadata={"inputs": {...}, "outputs": {...}, ...}), ...]
+ ```
+ """
+
+ def __init__(
+ self,
+ *,
+ dataset_id: uuid.UUID | str | None = None,
+ dataset_name: str | None = None,
+ example_ids: Sequence[uuid.UUID | str] | None = None,
+ as_of: datetime.datetime | str | None = None,
+ splits: Sequence[str] | None = None,
+ inline_s3_urls: bool = True,
+ offset: int = 0,
+ limit: int | None = None,
+ metadata: dict | None = None,
+ filter: str | None = None, # noqa: A002
+ content_key: str = "",
+ format_content: Callable[..., str] | None = None,
+ client: LangSmithClient | None = None,
+ **client_kwargs: Any,
+ ) -> None:
+ """Create a LangSmith loader.
+
+ Args:
+ dataset_id: The ID of the dataset to filter by.
+ dataset_name: The name of the dataset to filter by.
+ content_key: The inputs key to set as `Document` page content.
+
+ `'.'` characters are interpreted as nested keys, e.g.
+ `content_key="first.second"` will result in
+ `Document(page_content=format_content(example.inputs["first"]["second"]))`
+ format_content: Function for converting the content extracted from the example
+ inputs into a string.
+
+ Defaults to JSON-encoding the contents.
+ example_ids: The IDs of the examples to filter by.
+ as_of: The dataset version tag or timestamp to retrieve the examples as of.
+
+ Response examples will only be those that were present at the time of
+ the tagged (or timestamped) version.
+ splits: A list of dataset splits, which are divisions of your dataset such
+ as `train`, `test`, or `validation`.
+
+ Returns examples only from the specified splits.
+ inline_s3_urls: Whether to inline S3 URLs.
+ offset: The offset to start from.
+ limit: The maximum number of examples to return.
+ metadata: Metadata to filter by.
+ filter: A structured filter string to apply to the examples.
+ client: LangSmith Client.
+
+ If not provided will be initialized from below args.
+ client_kwargs: Keyword args to pass to LangSmith client init.
+
+ Should only be specified if `client` isn't.
+
+ Raises:
+ ValueError: If both `client` and `client_kwargs` are provided.
+ """ # noqa: E501
+ if client and client_kwargs:
+ raise ValueError
+ self._client = client or LangSmithClient(**client_kwargs)
+ self.content_key = list(content_key.split(".")) if content_key else []
+ self.format_content = format_content or _stringify
+ self.dataset_id = dataset_id
+ self.dataset_name = dataset_name
+ self.example_ids = example_ids
+ self.as_of = as_of
+ self.splits = splits
+ self.inline_s3_urls = inline_s3_urls
+ self.offset = offset
+ self.limit = limit
+ self.metadata = metadata
+ self.filter = filter
+
+ @override
+ def lazy_load(self) -> Iterator[Document]:
+ for example in self._client.list_examples(
+ dataset_id=self.dataset_id,
+ dataset_name=self.dataset_name,
+ example_ids=self.example_ids,
+ as_of=self.as_of,
+ splits=self.splits,
+ inline_s3_urls=self.inline_s3_urls,
+ offset=self.offset,
+ limit=self.limit,
+ metadata=self.metadata,
+ filter=self.filter,
+ ):
+ content: Any = example.inputs
+ for key in self.content_key:
+ content = content[key]
+ content_str = self.format_content(content)
+ metadata = pydantic_to_dict(example)
+ # Stringify datetime and UUID types.
+ for k in ("dataset_id", "created_at", "modified_at", "source_run_id", "id"):
+ metadata[k] = str(metadata[k]) if metadata[k] else metadata[k]
+ yield Document(content_str, metadata=metadata)
+
+
+def _stringify(x: str | dict[str, Any]) -> str:
+ if isinstance(x, str):
+ return x
+ try:
+ return json.dumps(x, indent=2)
+ except Exception:
+ return str(x)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/documents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..128a9dcfba68b2fcf4389588a318eef7a129c5e3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/documents/__init__.py
@@ -0,0 +1,55 @@
+"""Documents module for data retrieval and processing workflows.
+
+This module provides core abstractions for handling data in retrieval-augmented
+generation (RAG) pipelines, vector stores, and document processing workflows.
+
+!!! warning "Documents vs. message content"
+
+ This module is distinct from `langchain_core.messages.content`, which provides
+ multimodal content blocks for **LLM chat I/O** (text, images, audio, etc. within
+ messages).
+
+ **Key distinction:**
+
+ - **Documents** (this module): For **data retrieval and processing workflows**
+ - Vector stores, retrievers, RAG pipelines
+ - Text chunking, embedding, and semantic search
+ - Example: Chunks of a PDF stored in a vector database
+
+ - **Content Blocks** (`messages.content`): For **LLM conversational I/O**
+ - Multimodal message content sent to/from models
+ - Tool calls, reasoning, citations within chat
+ - Example: An image sent to a vision model in a chat message (via
+ [`ImageContentBlock`][langchain.messages.ImageContentBlock])
+
+ While both can represent similar data types (text, files), they serve different
+ architectural purposes in LangChain applications.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.documents.base import Document
+ from langchain_core.documents.compressor import BaseDocumentCompressor
+ from langchain_core.documents.transformers import BaseDocumentTransformer
+
+__all__ = ("BaseDocumentCompressor", "BaseDocumentTransformer", "Document")
+
+_dynamic_imports = {
+ "Document": "base",
+ "BaseDocumentCompressor": "compressor",
+ "BaseDocumentTransformer": "transformers",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a83523af4184bdf95c61b6cd485c19991bb43894
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a99a5362e995a8d7f61d696480351ca4fbcc4bcd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/compressor.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/compressor.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acca30def362d9fc49f8b91f984094a730f35138
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/compressor.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/transformers.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/transformers.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21c07c8b5ee8b33396d5cf5cd112b91f42ae51e0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/documents/__pycache__/transformers.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/base.py b/python/user_packages/Python313/site-packages/langchain_core/documents/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..969ee49a174661eb07046a4a7ebd3d1a7ee5f820
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/documents/base.py
@@ -0,0 +1,347 @@
+"""Base classes for media and documents.
+
+This module contains core abstractions for **data retrieval and processing workflows**:
+
+- `BaseMedia`: Base class providing `id` and `metadata` fields
+- `Blob`: Raw data loading (files, binary data) - used by document loaders
+- `Document`: Text content for retrieval (RAG, vector stores, semantic search)
+
+!!! note "Not for LLM chat messages"
+
+ These classes are for data processing pipelines, not LLM I/O. For multimodal
+ content in chat messages (images, audio in conversations), see
+ `langchain.messages` content blocks instead.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import mimetypes
+from io import BufferedReader, BytesIO
+from pathlib import Path, PurePath
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from pydantic import ConfigDict, Field, model_validator
+
+from langchain_core.load.serializable import Serializable
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+PathLike = str | PurePath
+
+
+class BaseMedia(Serializable):
+ """Base class for content used in retrieval and data processing workflows.
+
+ Provides common fields for content that needs to be stored, indexed, or searched.
+
+ !!! note
+
+ For multimodal content in **chat messages** (images, audio sent to/from LLMs),
+ use `langchain.messages` content blocks instead.
+ """
+
+ # The ID field is optional at the moment.
+ # It will likely become required in a future major release after
+ # it has been adopted by enough VectorStore implementations.
+ id: str | None = Field(default=None, coerce_numbers_to_str=True)
+ """An optional identifier for the document.
+
+ Ideally this should be unique across the document collection and formatted
+ as a UUID, but this will not be enforced.
+ """
+
+ metadata: dict = Field(default_factory=dict)
+ """Arbitrary metadata associated with the content."""
+
+
+class Blob(BaseMedia):
+ """Raw data abstraction for document loading and file processing.
+
+ Represents raw bytes or text, either in-memory or by file reference. Used
+ primarily by document loaders to decouple data loading from parsing.
+
+ Inspired by [Mozilla's `Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
+
+ ???+ example "Initialize a blob from in-memory data"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_data("Hello, world!")
+
+ # Read the blob as a string
+ print(blob.as_string())
+
+ # Read the blob as bytes
+ print(blob.as_bytes())
+
+ # Read the blob as a byte stream
+ with blob.as_bytes_io() as f:
+ print(f.read())
+ ```
+
+ ??? example "Load from memory and specify MIME type and metadata"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_data(
+ data="Hello, world!",
+ mime_type="text/plain",
+ metadata={"source": "https://example.com"},
+ )
+ ```
+
+ ??? example "Load the blob from a file"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_path("path/to/file.txt")
+
+ # Read the blob as a string
+ print(blob.as_string())
+
+ # Read the blob as bytes
+ print(blob.as_bytes())
+
+ # Read the blob as a byte stream
+ with blob.as_bytes_io() as f:
+ print(f.read())
+ ```
+ """
+
+ data: bytes | str | None = None
+ """Raw data associated with the `Blob`."""
+
+ mimetype: str | None = None
+ """MIME type, not to be confused with a file extension."""
+
+ encoding: str = "utf-8"
+ """Encoding to use if decoding the bytes into a string.
+
+ Uses `utf-8` as default encoding if decoding to string.
+ """
+
+ path: PathLike | None = None
+ """Location where the original content was found."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ frozen=True,
+ )
+
+ @property
+ def source(self) -> str | None:
+ """The source location of the blob as string if known otherwise none.
+
+ If a path is associated with the `Blob`, it will default to the path location.
+
+ Unless explicitly set via a metadata field called `'source'`, in which
+ case that value will be used instead.
+ """
+ if self.metadata and "source" in self.metadata:
+ return cast("str | None", self.metadata["source"])
+ return str(self.path) if self.path else None
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_blob_is_valid(cls, values: dict[str, Any]) -> Any:
+ """Verify that either data or path is provided."""
+ if "data" not in values and "path" not in values:
+ msg = "Either data or path must be provided"
+ raise ValueError(msg)
+ return values
+
+ def as_string(self) -> str:
+ """Read data as a string.
+
+ Raises:
+ ValueError: If the blob cannot be represented as a string.
+
+ Returns:
+ The data as a string.
+ """
+ if self.data is None and self.path:
+ return Path(self.path).read_text(encoding=self.encoding)
+ if isinstance(self.data, bytes):
+ return self.data.decode(self.encoding)
+ if isinstance(self.data, str):
+ return self.data
+ msg = f"Unable to get string for blob {self}"
+ raise ValueError(msg)
+
+ def as_bytes(self) -> bytes:
+ """Read data as bytes.
+
+ Raises:
+ ValueError: If the blob cannot be represented as bytes.
+
+ Returns:
+ The data as bytes.
+ """
+ if isinstance(self.data, bytes):
+ return self.data
+ if isinstance(self.data, str):
+ return self.data.encode(self.encoding)
+ if self.data is None and self.path:
+ return Path(self.path).read_bytes()
+ msg = f"Unable to get bytes for blob {self}"
+ raise ValueError(msg)
+
+ @contextlib.contextmanager
+ def as_bytes_io(self) -> Generator[BytesIO | BufferedReader, None, None]:
+ """Read data as a byte stream.
+
+ Raises:
+ NotImplementedError: If the blob cannot be represented as a byte stream.
+
+ Yields:
+ The data as a byte stream.
+ """
+ if isinstance(self.data, bytes):
+ yield BytesIO(self.data)
+ elif self.data is None and self.path:
+ with Path(self.path).open("rb") as f:
+ yield f
+ else:
+ msg = f"Unable to convert blob {self}"
+ raise NotImplementedError(msg)
+
+ @classmethod
+ def from_path(
+ cls,
+ path: PathLike,
+ *,
+ encoding: str = "utf-8",
+ mime_type: str | None = None,
+ guess_type: bool = True,
+ metadata: dict | None = None,
+ ) -> Blob:
+ """Load the blob from a path like object.
+
+ Args:
+ path: Path-like object to file to be read
+ encoding: Encoding to use if decoding the bytes into a string
+ mime_type: If provided, will be set as the MIME type of the data
+ guess_type: If `True`, the MIME type will be guessed from the file
+ extension, if a MIME type was not provided
+ metadata: Metadata to associate with the `Blob`
+
+ Returns:
+ `Blob` instance
+ """
+ if mime_type is None and guess_type:
+ mimetype = mimetypes.guess_type(path)[0]
+ else:
+ mimetype = mime_type
+ # We do not load the data immediately, instead we treat the blob as a
+ # reference to the underlying data.
+ return cls(
+ data=None,
+ mimetype=mimetype,
+ encoding=encoding,
+ path=path,
+ metadata=metadata if metadata is not None else {},
+ )
+
+ @classmethod
+ def from_data(
+ cls,
+ data: str | bytes,
+ *,
+ encoding: str = "utf-8",
+ mime_type: str | None = None,
+ path: str | None = None,
+ metadata: dict | None = None,
+ ) -> Blob:
+ """Initialize the `Blob` from in-memory data.
+
+ Args:
+ data: The in-memory data associated with the `Blob`
+ encoding: Encoding to use if decoding the bytes into a string
+ mime_type: If provided, will be set as the MIME type of the data
+ path: If provided, will be set as the source from which the data came
+ metadata: Metadata to associate with the `Blob`
+
+ Returns:
+ `Blob` instance
+ """
+ return cls(
+ data=data,
+ mimetype=mime_type,
+ encoding=encoding,
+ path=path,
+ metadata=metadata if metadata is not None else {},
+ )
+
+ def __repr__(self) -> str:
+ """Return the blob representation."""
+ str_repr = f"Blob {id(self)}"
+ if self.source:
+ str_repr += f" {self.source}"
+ return str_repr
+
+
+class Document(BaseMedia):
+ """Class for storing a piece of text and associated metadata.
+
+ !!! note
+
+ `Document` is for **retrieval workflows**, not chat I/O. For sending text
+ to an LLM in a conversation, use message types from `langchain.messages`.
+
+ Example:
+ ```python
+ from langchain_core.documents import Document
+
+ document = Document(
+ page_content="Hello, world!", metadata={"source": "https://example.com"}
+ )
+ ```
+ """
+
+ page_content: str
+ """String text."""
+
+ type: Literal["Document"] = "Document"
+
+ def __init__(self, page_content: str, **kwargs: Any) -> None:
+ """Pass page_content in as positional or named arg."""
+ # my-py is complaining that page_content is not defined on the base class.
+ # Here, we're relying on pydantic base class to handle the validation.
+ super().__init__(page_content=page_content, **kwargs) # type: ignore[call-arg,unused-ignore]
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "document"]`
+ """
+ return ["langchain", "schema", "document"]
+
+ def __str__(self) -> str:
+ """Override `__str__` to restrict it to page_content and metadata.
+
+ Returns:
+ A string representation of the `Document`.
+ """
+ # The format matches pydantic format for __str__.
+ #
+ # The purpose of this change is to make sure that user code that feeds
+ # Document objects directly into prompts remains unchanged due to the addition
+ # of the id field (or any other fields in the future).
+ #
+ # This override will likely be removed in the future in favor of a more general
+ # solution of formatting content directly inside the prompts.
+ if self.metadata:
+ return f"page_content='{self.page_content}' metadata={self.metadata}"
+ return f"page_content='{self.page_content}'"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/compressor.py b/python/user_packages/Python313/site-packages/langchain_core/documents/compressor.py
new file mode 100644
index 0000000000000000000000000000000000000000..c765b378bb1f7bbdfc19cd74b1f9ede08029315a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/documents/compressor.py
@@ -0,0 +1,74 @@
+"""Document compressor."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+from pydantic import BaseModel
+
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.callbacks import Callbacks
+ from langchain_core.documents import Document
+
+
+class BaseDocumentCompressor(BaseModel, ABC):
+ """Base class for document compressors.
+
+ This abstraction is primarily used for post-processing of retrieved documents.
+
+ `Document` objects matching a given query are first retrieved.
+
+ Then the list of documents can be further processed.
+
+ For example, one could re-rank the retrieved documents using an LLM.
+
+ !!! note
+ Users should favor using a `RunnableLambda` instead of sub-classing from this
+ interface.
+
+ """
+
+ @abstractmethod
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Callbacks | None = None,
+ ) -> Sequence[Document]:
+ """Compress retrieved documents given the query context.
+
+ Args:
+ documents: The retrieved `Document` objects.
+ query: The query context.
+ callbacks: Optional `Callbacks` to run during compression.
+
+ Returns:
+ The compressed documents.
+
+ """
+
+ async def acompress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Callbacks | None = None,
+ ) -> Sequence[Document]:
+ """Async compress retrieved documents given the query context.
+
+ Args:
+ documents: The retrieved `Document` objects.
+ query: The query context.
+ callbacks: Optional `Callbacks` to run during compression.
+
+ Returns:
+ The compressed documents.
+
+ """
+ return await run_in_executor(
+ None, self.compress_documents, documents, query, callbacks
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/documents/transformers.py b/python/user_packages/Python313/site-packages/langchain_core/documents/transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c05fa29a23953a73775895ddda3c03cb0fea946d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/documents/transformers.py
@@ -0,0 +1,79 @@
+"""Document transformers."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.documents import Document
+
+
+class BaseDocumentTransformer(ABC):
+ """Abstract base class for document transformation.
+
+ A document transformation takes a sequence of `Document` objects and returns a
+ sequence of transformed `Document` objects.
+
+ Example:
+ ```python
+ class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):
+ embeddings: Embeddings
+ similarity_fn: Callable = cosine_similarity
+ similarity_threshold: float = 0.95
+
+ class Config:
+ arbitrary_types_allowed = True
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ stateful_documents = get_stateful_documents(documents)
+ embedded_documents = _get_embeddings_from_stateful_docs(
+ self.embeddings, stateful_documents
+ )
+ included_idxs = _filter_similar_embeddings(
+ embedded_documents,
+ self.similarity_fn,
+ self.similarity_threshold,
+ )
+ return [stateful_documents[i] for i in sorted(included_idxs)]
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+ ```
+ """
+
+ @abstractmethod
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Transform a list of documents.
+
+ Args:
+ documents: A sequence of `Document` objects to be transformed.
+
+ Returns:
+ A sequence of transformed `Document` objects.
+ """
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Asynchronously transform a list of documents.
+
+ Args:
+ documents: A sequence of `Document` objects to be transformed.
+
+ Returns:
+ A sequence of transformed `Document` objects.
+ """
+ return await run_in_executor(
+ None, self.transform_documents, documents, **kwargs
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..66acae126fc1aa199fe9c24d899c325bdc431692
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__init__.py
@@ -0,0 +1,31 @@
+"""Embeddings."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.embeddings.embeddings import Embeddings
+ from langchain_core.embeddings.fake import (
+ DeterministicFakeEmbedding,
+ FakeEmbeddings,
+ )
+
+__all__ = ("DeterministicFakeEmbedding", "Embeddings", "FakeEmbeddings")
+
+_dynamic_imports = {
+ "Embeddings": "embeddings",
+ "DeterministicFakeEmbedding": "fake",
+ "FakeEmbeddings": "fake",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d0ccd4b328ba59627b186f320e1b41ef19a4e72
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f77e836702820394d2e3eaee6edc30cfdee91c33
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2c7772f9026193ca9623919a5314d60083a92bc
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/embeddings.py b/python/user_packages/Python313/site-packages/langchain_core/embeddings/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..39c0eb42a89532a7b57aec779a6c85e0a0c1f0d6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/embeddings/embeddings.py
@@ -0,0 +1,78 @@
+"""**Embeddings** interface."""
+
+from abc import ABC, abstractmethod
+
+from langchain_core.runnables.config import run_in_executor
+
+
+class Embeddings(ABC):
+ """Interface for embedding models.
+
+ This is an interface meant for implementing text embedding models.
+
+ Text embedding models are used to map text to a vector (a point in n-dimensional
+ space).
+
+ Texts that are similar will usually be mapped to points that are close to each
+ other in this space. The exact details of what's considered "similar" and how
+ "distance" is measured in this space are dependent on the specific embedding model.
+
+ This abstraction contains a method for embedding a list of documents and a method
+ for embedding a query text. The embedding of a query text is expected to be a single
+ vector, while the embedding of a list of documents is expected to be a list of
+ vectors.
+
+ Usually the query embedding is identical to the document embedding, but the
+ abstraction allows treating them independently.
+
+ In addition to the synchronous methods, this interface also provides asynchronous
+ versions of the methods.
+
+ By default, the asynchronous methods are implemented using the synchronous methods;
+ however, implementations may choose to override the asynchronous methods with
+ an async native implementation for performance reasons.
+ """
+
+ @abstractmethod
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Embed search docs.
+
+ Args:
+ texts: List of text to embed.
+
+ Returns:
+ List of embeddings.
+ """
+
+ @abstractmethod
+ def embed_query(self, text: str) -> list[float]:
+ """Embed query text.
+
+ Args:
+ text: Text to embed.
+
+ Returns:
+ Embedding.
+ """
+
+ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Asynchronous Embed search docs.
+
+ Args:
+ texts: List of text to embed.
+
+ Returns:
+ List of embeddings.
+ """
+ return await run_in_executor(None, self.embed_documents, texts)
+
+ async def aembed_query(self, text: str) -> list[float]:
+ """Asynchronous Embed query text.
+
+ Args:
+ text: Text to embed.
+
+ Returns:
+ Embedding.
+ """
+ return await run_in_executor(None, self.embed_query, text)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/embeddings/fake.py b/python/user_packages/Python313/site-packages/langchain_core/embeddings/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a252efc194eff881919bc1bbec976e0adbe5704
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/embeddings/fake.py
@@ -0,0 +1,129 @@
+"""Module contains a few fake embedding models for testing purposes."""
+
+# Please do not add additional fake embedding model implementations here.
+import contextlib
+import hashlib
+
+from pydantic import BaseModel
+from typing_extensions import override
+
+from langchain_core.embeddings import Embeddings
+
+with contextlib.suppress(ImportError):
+ import numpy as np
+
+
+class FakeEmbeddings(Embeddings, BaseModel):
+ """Fake embedding model for unit testing purposes.
+
+ This embedding model creates embeddings by sampling from a normal distribution.
+
+ !!! danger "Toy model"
+ Do not use this outside of testing, as it is not a real embedding model.
+
+ Instantiate:
+ ```python
+ from langchain_core.embeddings import FakeEmbeddings
+
+ embed = FakeEmbeddings(size=100)
+ ```
+
+ Embed single text:
+ ```python
+ input_text = "The meaning of life is 42"
+ vector = embed.embed_query(input_text)
+ print(vector[:3])
+ ```
+ ```python
+ [-0.700234640213188, -0.581266257710429, -1.1328482266445354]
+ ```
+
+ Embed multiple texts:
+ ```python
+ input_texts = ["Document 1...", "Document 2..."]
+ vectors = embed.embed_documents(input_texts)
+ print(len(vectors))
+ # The first 3 coordinates for the first vector
+ print(vectors[0][:3])
+ ```
+ ```python
+ 2
+ [-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
+ ```
+ """
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self) -> list[float]:
+ return list(np.random.default_rng().normal(size=self.size))
+
+ @override
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ return [self._get_embedding() for _ in texts]
+
+ @override
+ def embed_query(self, text: str) -> list[float]:
+ return self._get_embedding()
+
+
+class DeterministicFakeEmbedding(Embeddings, BaseModel):
+ """Deterministic fake embedding model for unit testing purposes.
+
+ This embedding model creates embeddings by sampling from a normal distribution
+ with a seed based on the hash of the text.
+
+ !!! danger "Toy model"
+ Do not use this outside of testing, as it is not a real embedding model.
+
+ Instantiate:
+ ```python
+ from langchain_core.embeddings import DeterministicFakeEmbedding
+
+ embed = DeterministicFakeEmbedding(size=100)
+ ```
+
+ Embed single text:
+ ```python
+ input_text = "The meaning of life is 42"
+ vector = embed.embed_query(input_text)
+ print(vector[:3])
+ ```
+ ```python
+ [-0.700234640213188, -0.581266257710429, -1.1328482266445354]
+ ```
+
+ Embed multiple texts:
+ ```python
+ input_texts = ["Document 1...", "Document 2..."]
+ vectors = embed.embed_documents(input_texts)
+ print(len(vectors))
+ # The first 3 coordinates for the first vector
+ print(vectors[0][:3])
+ ```
+ ```python
+ 2
+ [-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
+ ```
+ """
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self, seed: int) -> list[float]:
+ # set the seed for the random generator
+ rng = np.random.default_rng(seed)
+ return list(rng.normal(size=self.size))
+
+ @staticmethod
+ def _get_seed(text: str) -> int:
+ """Get a seed for the random generator, using the hash of the text."""
+ return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8
+
+ @override
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ return [self._get_embedding(seed=self._get_seed(_)) for _ in texts]
+
+ @override
+ def embed_query(self, text: str) -> list[float]:
+ return self._get_embedding(seed=self._get_seed(text))
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db079c9f91f11cc88d3e296f16d46dd73f7a4fd3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__init__.py
@@ -0,0 +1,47 @@
+"""Example selectors.
+
+**Example selector** implements logic for selecting examples to include them in prompts.
+This allows us to select examples that are most relevant to the input.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.example_selectors.base import BaseExampleSelector
+ from langchain_core.example_selectors.length_based import (
+ LengthBasedExampleSelector,
+ )
+ from langchain_core.example_selectors.semantic_similarity import (
+ MaxMarginalRelevanceExampleSelector,
+ SemanticSimilarityExampleSelector,
+ sorted_values,
+ )
+
+__all__ = (
+ "BaseExampleSelector",
+ "LengthBasedExampleSelector",
+ "MaxMarginalRelevanceExampleSelector",
+ "SemanticSimilarityExampleSelector",
+ "sorted_values",
+)
+
+_dynamic_imports = {
+ "BaseExampleSelector": "base",
+ "LengthBasedExampleSelector": "length_based",
+ "MaxMarginalRelevanceExampleSelector": "semantic_similarity",
+ "SemanticSimilarityExampleSelector": "semantic_similarity",
+ "sorted_values": "semantic_similarity",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b479571b55594922de4d69fd76c7b453e520ff6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be09bd58f96d995241e5bca133fccaf68effc3c5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d091f8a518b99b5ffa38fb928859f34cbb12ed4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56eeb507d1ec5dbab0deb39e11cf9cfb8425cd69
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/base.py b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec845cfc2e942a3e181b92c9c8bc0ea8ae0db8a9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/base.py
@@ -0,0 +1,58 @@
+"""Interface for selecting examples to include in prompts."""
+
+from abc import ABC, abstractmethod
+from typing import Any
+
+from langchain_core.runnables import run_in_executor
+
+
+class BaseExampleSelector(ABC):
+ """Interface for selecting examples to include in prompts."""
+
+ @abstractmethod
+ def add_example(self, example: dict[str, str]) -> Any:
+ """Add new example to store.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ Any return value.
+ """
+
+ async def aadd_example(self, example: dict[str, str]) -> Any:
+ """Async add new example to store.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ Any return value.
+ """
+ return await run_in_executor(None, self.add_example, example)
+
+ @abstractmethod
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select which examples to use based on the inputs.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples.
+ """
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Async select which examples to use based on the inputs.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples.
+ """
+ return await run_in_executor(None, self.select_examples, input_variables)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/length_based.py b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/length_based.py
new file mode 100644
index 0000000000000000000000000000000000000000..e60e47e891d3d8aea2d808060ff9d1120887c89a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/length_based.py
@@ -0,0 +1,128 @@
+"""Select examples based on length."""
+
+import re
+from collections.abc import Callable
+
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import Self
+
+from langchain_core.example_selectors.base import BaseExampleSelector
+from langchain_core.prompts.prompt import PromptTemplate
+
+
+def _get_length_based(text: str) -> int:
+ return len(re.split(r"\n| ", text))
+
+
+class LengthBasedExampleSelector(BaseExampleSelector, BaseModel):
+ r"""Select examples based on length.
+
+ Example:
+ ```python
+ from langchain_core.example_selectors import LengthBasedExampleSelector
+ from langchain_core.prompts import PromptTemplate
+
+ # Define examples
+ examples = [
+ {"input": "happy", "output": "sad"},
+ {"input": "tall", "output": "short"},
+ {"input": "fast", "output": "slow"},
+ ]
+
+ # Create prompt template
+ example_prompt = PromptTemplate(
+ input_variables=["input", "output"],
+ template="Input: {input}\nOutput: {output}",
+ )
+
+ # Create selector with max length constraint
+ selector = LengthBasedExampleSelector(
+ examples=examples,
+ example_prompt=example_prompt,
+ max_length=50, # Maximum prompt length
+ )
+
+ # Select examples for a new input
+ selected = selector.select_examples({"input": "large", "output": "tiny"})
+ # Returns examples that fit within max_length constraint
+ ```
+ """
+
+ examples: list[dict]
+ """A list of the examples that the prompt template expects."""
+
+ example_prompt: PromptTemplate
+ """Prompt template used to format the examples."""
+
+ get_text_length: Callable[[str], int] = _get_length_based
+ """Function to measure prompt length. Defaults to word count."""
+
+ max_length: int = 2048
+ """Max length for the prompt, beyond which examples are cut."""
+
+ example_text_lengths: list[int] = Field(default_factory=list)
+ """Length of each example."""
+
+ def add_example(self, example: dict[str, str]) -> None:
+ """Add new example to list.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+ """
+ self.examples.append(example)
+ string_example = self.example_prompt.format(**example)
+ self.example_text_lengths.append(self.get_text_length(string_example))
+
+ async def aadd_example(self, example: dict[str, str]) -> None:
+ """Async add new example to list.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+ """
+ self.add_example(example)
+
+ @model_validator(mode="after")
+ def post_init(self) -> Self:
+ """Validate that the examples are formatted correctly."""
+ if self.example_text_lengths:
+ return self
+ string_examples = [self.example_prompt.format(**eg) for eg in self.examples]
+ self.example_text_lengths = [self.get_text_length(eg) for eg in string_examples]
+ return self
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select which examples to use based on the input lengths.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples to include in the prompt.
+ """
+ inputs = " ".join(input_variables.values())
+ remaining_length = self.max_length - self.get_text_length(inputs)
+ i = 0
+ examples = []
+ while remaining_length > 0 and i < len(self.examples):
+ new_length = remaining_length - self.example_text_lengths[i]
+ if new_length < 0:
+ break
+ examples.append(self.examples[i])
+ remaining_length = new_length
+ i += 1
+ return examples
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Async select which examples to use based on the input lengths.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples to include in the prompt.
+ """
+ return self.select_examples(input_variables)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/example_selectors/semantic_similarity.py b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/semantic_similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e7491a2eb79cc850f66748e52e85dc7cdece394
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/example_selectors/semantic_similarity.py
@@ -0,0 +1,358 @@
+"""Example selector that selects examples based on SemanticSimilarity."""
+
+from __future__ import annotations
+
+from abc import ABC
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel, ConfigDict
+
+from langchain_core.example_selectors.base import BaseExampleSelector
+from langchain_core.vectorstores import VectorStore
+
+if TYPE_CHECKING:
+ from langchain_core.documents import Document
+ from langchain_core.embeddings import Embeddings
+
+
+def sorted_values(values: dict[str, str]) -> list[Any]:
+ """Return a list of values in dict sorted by key.
+
+ Args:
+ values: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of values in dict sorted by key.
+ """
+ return [values[val] for val in sorted(values)]
+
+
+class _VectorStoreExampleSelector(BaseExampleSelector, BaseModel, ABC):
+ """Example selector that selects examples based on SemanticSimilarity."""
+
+ vectorstore: VectorStore
+ """VectorStore that contains information about examples."""
+ k: int = 4
+ """Number of examples to select."""
+ example_keys: list[str] | None = None
+ """Optional keys to filter examples to."""
+ input_keys: list[str] | None = None
+ """Optional keys to filter input to. If provided, the search is based on
+ the input variables instead of all variables."""
+ vectorstore_kwargs: dict[str, Any] | None = None
+ """Extra arguments passed to similarity_search function of the `VectorStore`."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @staticmethod
+ def _example_to_text(example: dict[str, str], input_keys: list[str] | None) -> str:
+ if input_keys:
+ return " ".join(sorted_values({key: example[key] for key in input_keys}))
+ return " ".join(sorted_values(example))
+
+ def _documents_to_examples(self, documents: list[Document]) -> list[dict]:
+ # Get the examples from the metadata.
+ # This assumes that examples are stored in metadata.
+ examples = [dict(e.metadata) for e in documents]
+ # If example keys are provided, filter examples to those keys.
+ if self.example_keys:
+ examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
+ return examples
+
+ def add_example(self, example: dict[str, str]) -> str:
+ """Add a new example to vectorstore.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ The ID of the added example.
+ """
+ ids = self.vectorstore.add_texts(
+ [self._example_to_text(example, self.input_keys)], metadatas=[example]
+ )
+ return ids[0]
+
+ async def aadd_example(self, example: dict[str, str]) -> str:
+ """Async add new example to vectorstore.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ The ID of the added example.
+ """
+ ids = await self.vectorstore.aadd_texts(
+ [self._example_to_text(example, self.input_keys)], metadatas=[example]
+ )
+ return ids[0]
+
+
+class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
+ """Select examples based on semantic similarity."""
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select examples based on semantic similarity.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ # Get the docs with the highest similarity.
+ vectorstore_kwargs = self.vectorstore_kwargs or {}
+ example_docs = self.vectorstore.similarity_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ **vectorstore_kwargs,
+ )
+ return self._documents_to_examples(example_docs)
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Asynchronously select examples based on semantic similarity.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ # Get the docs with the highest similarity.
+ vectorstore_kwargs = self.vectorstore_kwargs or {}
+ example_docs = await self.vectorstore.asimilarity_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ **vectorstore_kwargs,
+ )
+ return self._documents_to_examples(example_docs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ *,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> SemanticSimilarityExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on query similarity.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = vectorstore_cls.from_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+ @classmethod
+ async def afrom_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ *,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> SemanticSimilarityExampleSelector:
+ """Async create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on query similarity.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = await vectorstore_cls.afrom_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+
+class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
+ """Select examples based on Max Marginal Relevance.
+
+ This was shown to improve performance in this paper:
+ https://arxiv.org/pdf/2211.13892.pdf
+ """
+
+ fetch_k: int = 20
+ """Number of examples to fetch to rerank."""
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select examples based on Max Marginal Relevance.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ example_docs = self.vectorstore.max_marginal_relevance_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ fetch_k=self.fetch_k,
+ )
+ return self._documents_to_examples(example_docs)
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Asynchronously select examples based on Max Marginal Relevance.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ example_docs = await self.vectorstore.amax_marginal_relevance_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ fetch_k=self.fetch_k,
+ )
+ return self._documents_to_examples(example_docs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ fetch_k: int = 20,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> MaxMarginalRelevanceExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on Max Marginal Relevance.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = vectorstore_cls.from_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ fetch_k=fetch_k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+ @classmethod
+ async def afrom_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ *,
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ fetch_k: int = 20,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> MaxMarginalRelevanceExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on Max Marginal Relevance.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = await vectorstore_cls.afrom_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ fetch_k=fetch_k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/indexing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceb25d2d074d1e8fb416dbfd78ce40df9cf2c0f3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/indexing/__init__.py
@@ -0,0 +1,53 @@
+"""Code to help indexing data into a vectorstore.
+
+This package contains helper logic to help deal with indexing data into
+a `VectorStore` while avoiding duplicated content and over-writing content
+if it's unchanged.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.indexing.api import IndexingResult, aindex, index
+ from langchain_core.indexing.base import (
+ DeleteResponse,
+ DocumentIndex,
+ InMemoryRecordManager,
+ RecordManager,
+ UpsertResponse,
+ )
+
+__all__ = (
+ "DeleteResponse",
+ "DocumentIndex",
+ "InMemoryRecordManager",
+ "IndexingResult",
+ "RecordManager",
+ "UpsertResponse",
+ "aindex",
+ "index",
+)
+
+_dynamic_imports = {
+ "aindex": "api",
+ "index": "api",
+ "IndexingResult": "api",
+ "DeleteResponse": "base",
+ "DocumentIndex": "base",
+ "InMemoryRecordManager": "base",
+ "RecordManager": "base",
+ "UpsertResponse": "base",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..874d1205b3de26c2b80c7cc3531ae650d5cb2b4d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/api.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/api.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d98f4efb9832a20268bbf4b0f66188688047dd7a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/api.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da594faaf116368eaf89433c0fbe8ed41514c869
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34f7e7f3c6c81f0a80f349941f9a0418aa344436
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/api.py b/python/user_packages/Python313/site-packages/langchain_core/indexing/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4af08b8b54e8dcb157eda4941836d11236ac09e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/indexing/api.py
@@ -0,0 +1,954 @@
+"""Module contains logic for indexing documents into vector stores."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+import warnings
+from itertools import islice
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypedDict,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.document_loaders.base import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.exceptions import LangChainException
+from langchain_core.indexing.base import DocumentIndex, RecordManager
+from langchain_core.vectorstores import VectorStore
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ AsyncIterable,
+ AsyncIterator,
+ Callable,
+ Iterable,
+ Iterator,
+ Sequence,
+ )
+
+# Magic UUID to use as a namespace for hashing.
+# Used to try and generate a unique UUID for each document
+# from hashing the document content and metadata.
+NAMESPACE_UUID = uuid.UUID(int=1984)
+
+
+T = TypeVar("T")
+
+
+def _hash_string_to_uuid(input_string: str) -> str:
+ """Hashes a string and returns the corresponding UUID."""
+ hash_value = hashlib.sha1(
+ input_string.encode("utf-8"), usedforsecurity=False
+ ).hexdigest()
+ return str(uuid.uuid5(NAMESPACE_UUID, hash_value))
+
+
+_WARNED_ABOUT_SHA1: bool = False
+
+
+def _warn_about_sha1() -> None:
+ """Emit a one-time warning about SHA-1 collision weaknesses."""
+ # Global variable OK in this case
+ global _WARNED_ABOUT_SHA1 # noqa: PLW0603
+ if not _WARNED_ABOUT_SHA1:
+ warnings.warn(
+ "Using SHA-1 for document hashing. SHA-1 is *not* "
+ "collision-resistant; a motivated attacker can construct distinct inputs "
+ "that map to the same fingerprint. If this matters in your "
+ "threat model, switch to a stronger algorithm such "
+ "as 'blake2b', 'sha256', or 'sha512' by specifying "
+ " `key_encoder` parameter in the `index` or `aindex` function. ",
+ category=UserWarning,
+ stacklevel=2,
+ )
+ _WARNED_ABOUT_SHA1 = True
+
+
+def _hash_string(
+ input_string: str, *, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> uuid.UUID:
+ """Hash *input_string* to a deterministic UUID using the configured algorithm."""
+ if algorithm == "sha1":
+ _warn_about_sha1()
+ hash_value = _calculate_hash(input_string, algorithm)
+ return uuid.uuid5(NAMESPACE_UUID, hash_value)
+
+
+def _hash_nested_dict(
+ data: dict[Any, Any], *, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> uuid.UUID:
+ """Hash a nested dictionary to a UUID using the configured algorithm."""
+ serialized_data = json.dumps(data, sort_keys=True)
+ return _hash_string(serialized_data, algorithm=algorithm)
+
+
+def _batch(size: int, iterable: Iterable[T]) -> Iterator[list[T]]:
+ """Utility batching function."""
+ if size <= 0:
+ msg = f"Batch size must be a positive integer, got {size}."
+ raise ValueError(msg)
+ it = iter(iterable)
+ while True:
+ chunk = list(islice(it, size))
+ if not chunk:
+ return
+ yield chunk
+
+
+async def _abatch(size: int, iterable: AsyncIterable[T]) -> AsyncIterator[list[T]]:
+ """Utility batching function."""
+ if size <= 0:
+ msg = f"Batch size must be a positive integer, got {size}."
+ raise ValueError(msg)
+ batch: list[T] = []
+ async for element in iterable:
+ if len(batch) < size:
+ batch.append(element)
+
+ if len(batch) >= size:
+ yield batch
+ batch = []
+
+ if batch:
+ yield batch
+
+
+def _get_source_id_assigner(
+ source_id_key: str | Callable[[Document], str] | None,
+) -> Callable[[Document], str | None]:
+ """Get the source id from the document."""
+ if source_id_key is None:
+ return lambda _doc: None
+ if isinstance(source_id_key, str):
+ return lambda doc: doc.metadata[source_id_key]
+ if callable(source_id_key):
+ return source_id_key
+ msg = (
+ f"source_id_key should be either None, a string or a callable. "
+ f"Got {source_id_key} of type {type(source_id_key)}."
+ )
+ raise ValueError(msg)
+
+
+def _deduplicate_in_order(
+ hashed_documents: Iterable[Document],
+) -> Iterator[Document]:
+ """Deduplicate a list of hashed documents while preserving order."""
+ seen: set[str] = set()
+
+ for hashed_doc in hashed_documents:
+ if hashed_doc.id not in seen:
+ # At this stage, the id is guaranteed to be a string.
+ # Avoiding unnecessary run time checks.
+ seen.add(cast("str", hashed_doc.id))
+ yield hashed_doc
+
+
+class IndexingException(LangChainException):
+ """Raised when an indexing operation fails."""
+
+
+def _calculate_hash(
+ text: str, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> str:
+ """Return a hexadecimal digest of *text* using *algorithm*."""
+ if algorithm == "sha1":
+ # Calculate the SHA-1 hash and return it as a UUID.
+ digest = hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()
+ return str(uuid.uuid5(NAMESPACE_UUID, digest))
+ if algorithm == "blake2b":
+ return hashlib.blake2b(text.encode("utf-8")).hexdigest()
+ if algorithm == "sha256":
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+ if algorithm == "sha512":
+ return hashlib.sha512(text.encode("utf-8")).hexdigest()
+ msg = f"Unsupported hashing algorithm: {algorithm}"
+ raise ValueError(msg)
+
+
+def _get_document_with_hash(
+ document: Document,
+ *,
+ key_encoder: Callable[[Document], str]
+ | Literal["sha1", "sha256", "sha512", "blake2b"],
+) -> Document:
+ """Calculate a hash of the document, and assign it to the uid.
+
+ When using one of the predefined hashing algorithms, the hash is calculated
+ by hashing the content and the metadata of the document.
+
+ Args:
+ document: Document to hash.
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+
+ Raises:
+ ValueError: If the metadata cannot be serialized using json.
+
+ Returns:
+ Document with a unique identifier based on the hash of the content and metadata.
+ """
+ metadata: dict[str, Any] = dict(document.metadata or {})
+
+ if callable(key_encoder):
+ # If key_encoder is a callable, we use it to generate the hash.
+ hash_ = key_encoder(document)
+ else:
+ # The hashes are calculated separate for the content and the metadata.
+ content_hash = _calculate_hash(document.page_content, algorithm=key_encoder)
+ try:
+ serialized_meta = json.dumps(metadata, sort_keys=True)
+ except Exception as e:
+ msg = (
+ f"Failed to hash metadata: {e}. "
+ f"Please use a dict that can be serialized using json."
+ )
+ raise ValueError(msg) from e
+ metadata_hash = _calculate_hash(serialized_meta, algorithm=key_encoder)
+ hash_ = _calculate_hash(content_hash + metadata_hash, algorithm=key_encoder)
+
+ return Document(
+ # Assign a unique identifier based on the hash.
+ id=hash_,
+ page_content=document.page_content,
+ metadata=document.metadata,
+ )
+
+
+# This internal abstraction was imported by the langchain package internally, so
+# we keep it here for backwards compatibility.
+class _HashedDocument:
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Raise an error if this class is instantiated."""
+ msg = (
+ "_HashedDocument is an internal abstraction that was deprecated in "
+ " langchain-core 0.3.63. This abstraction is marked as private and "
+ " should not have been used directly. If you are seeing this error, please "
+ " update your code appropriately."
+ )
+ raise NotImplementedError(msg)
+
+
+def _delete(
+ vector_store: VectorStore | DocumentIndex,
+ ids: list[str],
+) -> None:
+ """Delete documents from a vector store or document index by their IDs.
+
+ Args:
+ vector_store: The vector store or document index to delete from.
+ ids: List of document IDs to delete.
+
+ Raises:
+ IndexingException: If the delete operation fails.
+ TypeError: If the `vector_store` is neither a `VectorStore` nor a
+ `DocumentIndex`.
+ """
+ if isinstance(vector_store, VectorStore):
+ delete_ok = vector_store.delete(ids)
+ if delete_ok is not None and delete_ok is False:
+ msg = "The delete operation to VectorStore failed."
+ raise IndexingException(msg)
+ elif isinstance(vector_store, DocumentIndex):
+ delete_response = vector_store.delete(ids)
+ if "num_failed" in delete_response and delete_response["num_failed"] > 0:
+ msg = "The delete operation to DocumentIndex failed."
+ raise IndexingException(msg)
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(vector_store)}."
+ )
+ raise TypeError(msg)
+
+
+# PUBLIC API
+
+
+class IndexingResult(TypedDict):
+ """Return a detailed a breakdown of the result of the indexing operation."""
+
+ num_added: int
+ """Number of added documents."""
+ num_updated: int
+ """Number of updated documents because they were not up to date."""
+ num_deleted: int
+ """Number of deleted documents."""
+ num_skipped: int
+ """Number of skipped documents because they were already up to date."""
+
+
+def index(
+ docs_source: BaseLoader | Iterable[Document],
+ record_manager: RecordManager,
+ vector_store: VectorStore | DocumentIndex,
+ *,
+ batch_size: int = 100,
+ cleanup: Literal["incremental", "full", "scoped_full"] | None = None,
+ source_id_key: str | Callable[[Document], str] | None = None,
+ cleanup_batch_size: int = 1_000,
+ force_update: bool = False,
+ key_encoder: Literal["sha1", "sha256", "sha512", "blake2b"]
+ | Callable[[Document], str] = "sha1",
+ upsert_kwargs: dict[str, Any] | None = None,
+) -> IndexingResult:
+ """Index data from the loader into the vector store.
+
+ Indexing functionality uses a manager to keep track of which documents
+ are in the vector store.
+
+ This allows us to keep track of which documents were updated, and which
+ documents were deleted, which documents should be skipped.
+
+ For the time being, documents are indexed using their hashes, and users
+ are not able to specify the uid of the document.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.25"
+
+ Added `scoped_full` cleanup mode.
+
+ !!! warning
+
+ * In full mode, the loader should be returning
+ the entire dataset, and not just a subset of the dataset.
+ Otherwise, the auto_cleanup will remove documents that it is not
+ supposed to.
+ * In incremental mode, if documents associated with a particular
+ source id appear across different batches, the indexing API
+ will do some redundant work. This will still result in the
+ correct end state of the index, but will unfortunately not be
+ 100% efficient. For example, if a given document is split into 15
+ chunks, and we index them using a batch size of 5, we'll have 3 batches
+ all with the same source id. In general, to avoid doing too much
+ redundant work select as big a batch size as possible.
+ * The `scoped_full` mode is suitable if determining an appropriate batch size
+ is challenging or if your data loader cannot return the entire dataset at
+ once. This mode keeps track of source IDs in memory, which should be fine
+ for most use cases. If your dataset is large (10M+ docs), you will likely
+ need to parallelize the indexing process regardless.
+
+ Args:
+ docs_source: Data loader or iterable of documents to index.
+ record_manager: Timestamped set to keep track of which documents were
+ updated.
+ vector_store: `VectorStore` or DocumentIndex to index the documents into.
+ batch_size: Batch size to use when indexing.
+ cleanup: How to handle clean up of documents.
+
+ - incremental: Cleans up all documents that haven't been updated AND
+ that are associated with source IDs that were seen during indexing.
+ Clean up is done continuously during indexing helping to minimize the
+ probability of users seeing duplicated content.
+ - full: Delete all documents that have not been returned by the loader
+ during this run of indexing.
+ Clean up runs after all documents have been indexed.
+ This means that users may see duplicated content during indexing.
+ - scoped_full: Similar to Full, but only deletes all documents
+ that haven't been updated AND that are associated with
+ source IDs that were seen during indexing.
+ - None: Do not delete any documents.
+ source_id_key: Optional key that helps identify the original source
+ of the document.
+ cleanup_batch_size: Batch size to use when cleaning up documents.
+ force_update: Force update documents even if they are present in the
+ record manager. Useful if you are re-indexing with updated embeddings.
+ key_encoder: Hashing algorithm to use for hashing the document content and
+ metadata. Options include "blake2b", "sha256", and "sha512".
+
+ !!! version-added "Added in `langchain-core` 0.3.66"
+
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+ upsert_kwargs: Additional keyword arguments to pass to the add_documents
+ method of the `VectorStore` or the upsert method of the DocumentIndex.
+ For example, you can use this to specify a custom vector_field:
+ upsert_kwargs={"vector_field": "embedding"}
+ !!! version-added "Added in `langchain-core` 0.3.10"
+
+ Returns:
+ Indexing result which contains information about how many documents
+ were added, updated, deleted, or skipped.
+
+ Raises:
+ ValueError: If cleanup mode is not one of 'incremental', 'full' or None
+ ValueError: If cleanup mode is incremental and source_id_key is None.
+ ValueError: If `VectorStore` does not have
+ "delete" and "add_documents" required methods.
+ ValueError: If source_id_key is not None, but is not a string or callable.
+ TypeError: If `vectorstore` is not a `VectorStore` or a DocumentIndex.
+ AssertionError: If `source_id` is None when cleanup mode is incremental.
+ (should be unreachable code).
+ """
+ # Behavior is deprecated, but we keep it for backwards compatibility.
+ # # Warn only once per process.
+ if key_encoder == "sha1":
+ _warn_about_sha1()
+
+ if cleanup not in {"incremental", "full", "scoped_full", None}:
+ msg = (
+ f"cleanup should be one of 'incremental', 'full', 'scoped_full' or None. "
+ f"Got {cleanup}."
+ )
+ raise ValueError(msg)
+
+ if (cleanup in {"incremental", "scoped_full"}) and source_id_key is None:
+ msg = (
+ "Source id key is required when cleanup mode is incremental or scoped_full."
+ )
+ raise ValueError(msg)
+
+ destination = vector_store # Renaming internally for clarity
+
+ # If it's a vectorstore, let's check if it has the required methods.
+ if isinstance(destination, VectorStore):
+ # Check that the Vectorstore has required methods implemented
+ methods = ["delete", "add_documents"]
+
+ for method in methods:
+ if not hasattr(destination, method):
+ msg = (
+ f"Vectorstore {destination} does not have required method {method}"
+ )
+ raise ValueError(msg)
+
+ if type(destination).delete == VectorStore.delete:
+ # Checking if the VectorStore has overridden the default delete method
+ # implementation which just raises a NotImplementedError
+ msg = "Vectorstore has not implemented the delete method"
+ raise ValueError(msg)
+ elif isinstance(destination, DocumentIndex):
+ pass
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(destination)}."
+ )
+ raise TypeError(msg)
+
+ if isinstance(docs_source, BaseLoader):
+ try:
+ doc_iterator = docs_source.lazy_load()
+ except NotImplementedError:
+ doc_iterator = iter(docs_source.load())
+ else:
+ doc_iterator = iter(docs_source)
+
+ source_id_assigner = _get_source_id_assigner(source_id_key)
+
+ # Mark when the update started.
+ index_start_dt = record_manager.get_time()
+ num_added = 0
+ num_skipped = 0
+ num_updated = 0
+ num_deleted = 0
+ scoped_full_cleanup_source_ids: set[str] = set()
+
+ for doc_batch in _batch(batch_size, doc_iterator):
+ # Track original batch size before deduplication
+ original_batch_size = len(doc_batch)
+
+ hashed_docs = list(
+ _deduplicate_in_order(
+ [
+ _get_document_with_hash(doc, key_encoder=key_encoder)
+ for doc in doc_batch
+ ]
+ )
+ )
+ # Count documents removed by within-batch deduplication
+ num_skipped += original_batch_size - len(hashed_docs)
+
+ source_ids: Sequence[str | None] = [
+ source_id_assigner(hashed_doc) for hashed_doc in hashed_docs
+ ]
+
+ if cleanup in {"incremental", "scoped_full"}:
+ # Source IDs are required.
+ for source_id, hashed_doc in zip(source_ids, hashed_docs, strict=False):
+ if source_id is None:
+ msg = (
+ f"Source IDs are required when cleanup mode is "
+ f"incremental or scoped_full. "
+ f"Document that starts with "
+ f"content: {hashed_doc.page_content[:100]} "
+ f"was not assigned as source id."
+ )
+ raise ValueError(msg)
+ if cleanup == "scoped_full":
+ scoped_full_cleanup_source_ids.add(source_id)
+ # Source IDs cannot be None after for loop above.
+ source_ids = cast("Sequence[str]", source_ids)
+
+ exists_batch = record_manager.exists(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs])
+ )
+
+ # Filter out documents that already exist in the record store.
+ uids = []
+ docs_to_index = []
+ uids_to_refresh = []
+ seen_docs: set[str] = set()
+ for hashed_doc, doc_exists in zip(hashed_docs, exists_batch, strict=False):
+ hashed_id = cast("str", hashed_doc.id)
+ if doc_exists:
+ if force_update:
+ seen_docs.add(hashed_id)
+ else:
+ uids_to_refresh.append(hashed_id)
+ continue
+ uids.append(hashed_id)
+ docs_to_index.append(hashed_doc)
+
+ # Update refresh timestamp
+ if uids_to_refresh:
+ record_manager.update(uids_to_refresh, time_at_least=index_start_dt)
+ num_skipped += len(uids_to_refresh)
+
+ # Be pessimistic and assume that all vector store write will fail.
+ # First write to vector store
+ if docs_to_index:
+ if isinstance(destination, VectorStore):
+ destination.add_documents(
+ docs_to_index,
+ ids=uids,
+ batch_size=batch_size,
+ **(upsert_kwargs or {}),
+ )
+ elif isinstance(destination, DocumentIndex):
+ destination.upsert(
+ docs_to_index,
+ **(upsert_kwargs or {}),
+ )
+
+ num_added += len(docs_to_index) - len(seen_docs)
+ num_updated += len(seen_docs)
+
+ # And only then update the record store.
+ # Update ALL records, even if they already exist since we want to refresh
+ # their timestamp.
+ record_manager.update(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs]),
+ group_ids=source_ids,
+ time_at_least=index_start_dt,
+ )
+
+ # If source IDs are provided, we can do the deletion incrementally!
+ if cleanup == "incremental":
+ # Get the uids of the documents that were not returned by the loader.
+ # mypy isn't good enough to determine that source IDs cannot be None
+ # here due to a check that's happening above, so we check again.
+ for source_id in source_ids:
+ if source_id is None:
+ msg = (
+ "source_id cannot be None at this point. "
+ "Reached unreachable code."
+ )
+ raise AssertionError(msg)
+
+ source_ids_ = cast("Sequence[str]", source_ids)
+
+ while uids_to_delete := record_manager.list_keys(
+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # Then delete from vector store.
+ _delete(destination, uids_to_delete)
+ # First delete from record store.
+ record_manager.delete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ if cleanup == "full" or (
+ cleanup == "scoped_full" and scoped_full_cleanup_source_ids
+ ):
+ delete_group_ids: Sequence[str] | None = None
+ if cleanup == "scoped_full":
+ delete_group_ids = list(scoped_full_cleanup_source_ids)
+ while uids_to_delete := record_manager.list_keys(
+ group_ids=delete_group_ids, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # First delete from record store.
+ _delete(destination, uids_to_delete)
+ # Then delete from record manager.
+ record_manager.delete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ return {
+ "num_added": num_added,
+ "num_updated": num_updated,
+ "num_skipped": num_skipped,
+ "num_deleted": num_deleted,
+ }
+
+
+# Define an asynchronous generator function
+async def _to_async_iterator(iterator: Iterable[T]) -> AsyncIterator[T]:
+ """Convert an iterable to an async iterator."""
+ for item in iterator:
+ yield item
+
+
+async def _adelete(
+ vector_store: VectorStore | DocumentIndex,
+ ids: list[str],
+) -> None:
+ if isinstance(vector_store, VectorStore):
+ delete_ok = await vector_store.adelete(ids)
+ if delete_ok is not None and delete_ok is False:
+ msg = "The delete operation to VectorStore failed."
+ raise IndexingException(msg)
+ elif isinstance(vector_store, DocumentIndex):
+ delete_response = await vector_store.adelete(ids)
+ if "num_failed" in delete_response and delete_response["num_failed"] > 0:
+ msg = "The delete operation to DocumentIndex failed."
+ raise IndexingException(msg)
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(vector_store)}."
+ )
+ raise TypeError(msg)
+
+
+async def aindex(
+ docs_source: BaseLoader | Iterable[Document] | AsyncIterator[Document],
+ record_manager: RecordManager,
+ vector_store: VectorStore | DocumentIndex,
+ *,
+ batch_size: int = 100,
+ cleanup: Literal["incremental", "full", "scoped_full"] | None = None,
+ source_id_key: str | Callable[[Document], str] | None = None,
+ cleanup_batch_size: int = 1_000,
+ force_update: bool = False,
+ key_encoder: Literal["sha1", "sha256", "sha512", "blake2b"]
+ | Callable[[Document], str] = "sha1",
+ upsert_kwargs: dict[str, Any] | None = None,
+) -> IndexingResult:
+ """Async index data from the loader into the vector store.
+
+ Indexing functionality uses a manager to keep track of which documents
+ are in the vector store.
+
+ This allows us to keep track of which documents were updated, and which
+ documents were deleted, which documents should be skipped.
+
+ For the time being, documents are indexed using their hashes, and users
+ are not able to specify the uid of the document.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.25"
+
+ Added `scoped_full` cleanup mode.
+
+ !!! warning
+
+ * In full mode, the loader should be returning
+ the entire dataset, and not just a subset of the dataset.
+ Otherwise, the auto_cleanup will remove documents that it is not
+ supposed to.
+ * In incremental mode, if documents associated with a particular
+ source id appear across different batches, the indexing API
+ will do some redundant work. This will still result in the
+ correct end state of the index, but will unfortunately not be
+ 100% efficient. For example, if a given document is split into 15
+ chunks, and we index them using a batch size of 5, we'll have 3 batches
+ all with the same source id. In general, to avoid doing too much
+ redundant work select as big a batch size as possible.
+ * The `scoped_full` mode is suitable if determining an appropriate batch size
+ is challenging or if your data loader cannot return the entire dataset at
+ once. This mode keeps track of source IDs in memory, which should be fine
+ for most use cases. If your dataset is large (10M+ docs), you will likely
+ need to parallelize the indexing process regardless.
+
+ Args:
+ docs_source: Data loader or iterable of documents to index.
+ record_manager: Timestamped set to keep track of which documents were
+ updated.
+ vector_store: `VectorStore` or DocumentIndex to index the documents into.
+ batch_size: Batch size to use when indexing.
+ cleanup: How to handle clean up of documents.
+
+ - incremental: Cleans up all documents that haven't been updated AND
+ that are associated with source IDs that were seen during indexing.
+ Clean up is done continuously during indexing helping to minimize the
+ probability of users seeing duplicated content.
+ - full: Delete all documents that have not been returned by the loader
+ during this run of indexing.
+ Clean up runs after all documents have been indexed.
+ This means that users may see duplicated content during indexing.
+ - scoped_full: Similar to Full, but only deletes all documents
+ that haven't been updated AND that are associated with
+ source IDs that were seen during indexing.
+ - None: Do not delete any documents.
+ source_id_key: Optional key that helps identify the original source
+ of the document.
+ cleanup_batch_size: Batch size to use when cleaning up documents.
+ force_update: Force update documents even if they are present in the
+ record manager. Useful if you are re-indexing with updated embeddings.
+ key_encoder: Hashing algorithm to use for hashing the document content and
+ metadata. Options include "blake2b", "sha256", and "sha512".
+
+ !!! version-added "Added in `langchain-core` 0.3.66"
+
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+ upsert_kwargs: Additional keyword arguments to pass to the add_documents
+ method of the `VectorStore` or the upsert method of the DocumentIndex.
+ For example, you can use this to specify a custom vector_field:
+ upsert_kwargs={"vector_field": "embedding"}
+ !!! version-added "Added in `langchain-core` 0.3.10"
+
+ Returns:
+ Indexing result which contains information about how many documents
+ were added, updated, deleted, or skipped.
+
+ Raises:
+ ValueError: If cleanup mode is not one of 'incremental', 'full' or None
+ ValueError: If cleanup mode is incremental and source_id_key is None.
+ ValueError: If `VectorStore` does not have
+ "adelete" and "aadd_documents" required methods.
+ ValueError: If source_id_key is not None, but is not a string or callable.
+ TypeError: If `vector_store` is not a `VectorStore` or DocumentIndex.
+ AssertionError: If `source_id_key` is None when cleanup mode is
+ incremental or `scoped_full` (should be unreachable).
+ """
+ # Behavior is deprecated, but we keep it for backwards compatibility.
+ # # Warn only once per process.
+ if key_encoder == "sha1":
+ _warn_about_sha1()
+
+ if cleanup not in {"incremental", "full", "scoped_full", None}:
+ msg = (
+ f"cleanup should be one of 'incremental', 'full', 'scoped_full' or None. "
+ f"Got {cleanup}."
+ )
+ raise ValueError(msg)
+
+ if (cleanup in {"incremental", "scoped_full"}) and source_id_key is None:
+ msg = (
+ "Source id key is required when cleanup mode is incremental or scoped_full."
+ )
+ raise ValueError(msg)
+
+ destination = vector_store # Renaming internally for clarity
+
+ # If it's a vectorstore, let's check if it has the required methods.
+ if isinstance(destination, VectorStore):
+ # Check that the Vectorstore has required methods implemented
+ # Check that the Vectorstore has required methods implemented
+ methods = ["adelete", "aadd_documents"]
+
+ for method in methods:
+ if not hasattr(destination, method):
+ msg = (
+ f"Vectorstore {destination} does not have required method {method}"
+ )
+ raise ValueError(msg)
+
+ if (
+ type(destination).adelete == VectorStore.adelete
+ and type(destination).delete == VectorStore.delete
+ ):
+ # Checking if the VectorStore has overridden the default adelete or delete
+ # methods implementation which just raises a NotImplementedError
+ msg = "Vectorstore has not implemented the adelete or delete method"
+ raise ValueError(msg)
+ elif isinstance(destination, DocumentIndex):
+ pass
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(destination)}."
+ )
+ raise TypeError(msg)
+ async_doc_iterator: AsyncIterator[Document]
+ if isinstance(docs_source, BaseLoader):
+ try:
+ async_doc_iterator = docs_source.alazy_load()
+ except NotImplementedError:
+ # Exception triggered when neither lazy_load nor alazy_load are implemented.
+ # * The default implementation of alazy_load uses lazy_load.
+ # * The default implementation of lazy_load raises NotImplementedError.
+ # In such a case, we use the load method and convert it to an async
+ # iterator.
+ async_doc_iterator = _to_async_iterator(docs_source.load())
+ elif hasattr(docs_source, "__aiter__"):
+ async_doc_iterator = docs_source # type: ignore[assignment]
+ else:
+ async_doc_iterator = _to_async_iterator(docs_source)
+
+ source_id_assigner = _get_source_id_assigner(source_id_key)
+
+ # Mark when the update started.
+ index_start_dt = await record_manager.aget_time()
+ num_added = 0
+ num_skipped = 0
+ num_updated = 0
+ num_deleted = 0
+ scoped_full_cleanup_source_ids: set[str] = set()
+
+ async for doc_batch in _abatch(batch_size, async_doc_iterator):
+ # Track original batch size before deduplication
+ original_batch_size = len(doc_batch)
+
+ hashed_docs = list(
+ _deduplicate_in_order(
+ [
+ _get_document_with_hash(doc, key_encoder=key_encoder)
+ for doc in doc_batch
+ ]
+ )
+ )
+ # Count documents removed by within-batch deduplication
+ num_skipped += original_batch_size - len(hashed_docs)
+
+ source_ids: Sequence[str | None] = [
+ source_id_assigner(doc) for doc in hashed_docs
+ ]
+
+ if cleanup in {"incremental", "scoped_full"}:
+ # If the cleanup mode is incremental, source IDs are required.
+ for source_id, hashed_doc in zip(source_ids, hashed_docs, strict=False):
+ if source_id is None:
+ msg = (
+ f"Source IDs are required when cleanup mode is "
+ f"incremental or scoped_full. "
+ f"Document that starts with "
+ f"content: {hashed_doc.page_content[:100]} "
+ f"was not assigned as source id."
+ )
+ raise ValueError(msg)
+ if cleanup == "scoped_full":
+ scoped_full_cleanup_source_ids.add(source_id)
+ # Source IDs cannot be None after for loop above.
+ source_ids = cast("Sequence[str]", source_ids)
+
+ exists_batch = await record_manager.aexists(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs])
+ )
+
+ # Filter out documents that already exist in the record store.
+ uids: list[str] = []
+ docs_to_index: list[Document] = []
+ uids_to_refresh = []
+ seen_docs: set[str] = set()
+ for hashed_doc, doc_exists in zip(hashed_docs, exists_batch, strict=False):
+ hashed_id = cast("str", hashed_doc.id)
+ if doc_exists:
+ if force_update:
+ seen_docs.add(hashed_id)
+ else:
+ uids_to_refresh.append(hashed_id)
+ continue
+ uids.append(hashed_id)
+ docs_to_index.append(hashed_doc)
+
+ if uids_to_refresh:
+ # Must be updated to refresh timestamp.
+ await record_manager.aupdate(uids_to_refresh, time_at_least=index_start_dt)
+ num_skipped += len(uids_to_refresh)
+
+ # Be pessimistic and assume that all vector store write will fail.
+ # First write to vector store
+ if docs_to_index:
+ if isinstance(destination, VectorStore):
+ await destination.aadd_documents(
+ docs_to_index,
+ ids=uids,
+ batch_size=batch_size,
+ **(upsert_kwargs or {}),
+ )
+ elif isinstance(destination, DocumentIndex):
+ await destination.aupsert(
+ docs_to_index,
+ **(upsert_kwargs or {}),
+ )
+ num_added += len(docs_to_index) - len(seen_docs)
+ num_updated += len(seen_docs)
+
+ # And only then update the record store.
+ # Update ALL records, even if they already exist since we want to refresh
+ # their timestamp.
+ await record_manager.aupdate(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs]),
+ group_ids=source_ids,
+ time_at_least=index_start_dt,
+ )
+
+ # If source IDs are provided, we can do the deletion incrementally!
+
+ if cleanup == "incremental":
+ # Get the uids of the documents that were not returned by the loader.
+
+ # mypy isn't good enough to determine that source IDs cannot be None
+ # here due to a check that's happening above, so we check again.
+ for source_id in source_ids:
+ if source_id is None:
+ msg = (
+ "source_id cannot be None at this point. "
+ "Reached unreachable code."
+ )
+ raise AssertionError(msg)
+
+ source_ids_ = cast("Sequence[str]", source_ids)
+
+ while uids_to_delete := await record_manager.alist_keys(
+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # Then delete from vector store.
+ await _adelete(destination, uids_to_delete)
+ # First delete from record store.
+ await record_manager.adelete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ if cleanup == "full" or (
+ cleanup == "scoped_full" and scoped_full_cleanup_source_ids
+ ):
+ delete_group_ids: Sequence[str] | None = None
+ if cleanup == "scoped_full":
+ delete_group_ids = list(scoped_full_cleanup_source_ids)
+ while uids_to_delete := await record_manager.alist_keys(
+ group_ids=delete_group_ids, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # First delete from record store.
+ await _adelete(destination, uids_to_delete)
+ # Then delete from record manager.
+ await record_manager.adelete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ return {
+ "num_added": num_added,
+ "num_updated": num_updated,
+ "num_skipped": num_skipped,
+ "num_deleted": num_deleted,
+ }
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/base.py b/python/user_packages/Python313/site-packages/langchain_core/indexing/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8a891ddf9ee400e1154e8c84a4eb76cf8b7911d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/indexing/base.py
@@ -0,0 +1,661 @@
+"""Base classes for indexing."""
+
+from __future__ import annotations
+
+import abc
+import time
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, TypedDict
+
+from typing_extensions import override
+
+from langchain_core._api import beta
+from langchain_core.retrievers import BaseRetriever
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.documents import Document
+
+
+class RecordManager(ABC):
+ """Abstract base class representing the interface for a record manager.
+
+ The record manager abstraction is used by the langchain indexing API.
+
+ The record manager keeps track of which documents have been
+ written into a `VectorStore` and when they were written.
+
+ The indexing API computes hashes for each document and stores the hash
+ together with the write time and the source id in the record manager.
+
+ On subsequent indexing runs, the indexing API can check the record manager
+ to determine which documents have already been indexed and which have not.
+
+ This allows the indexing API to avoid re-indexing documents that have
+ already been indexed, and to only index new documents.
+
+ The main benefit of this abstraction is that it works across many vectorstores.
+ To be supported, a `VectorStore` needs to only support the ability to add and
+ delete documents by ID. Using the record manager, the indexing API will
+ be able to delete outdated documents and avoid redundant indexing of documents
+ that have already been indexed.
+
+ The main constraints of this abstraction are:
+
+ 1. It relies on the time-stamps to determine which documents have been
+ indexed and which have not. This means that the time-stamps must be
+ monotonically increasing. The timestamp should be the timestamp
+ as measured by the server to minimize issues.
+ 2. The record manager is currently implemented separately from the
+ vectorstore, which means that the overall system becomes distributed
+ and may create issues with consistency. For example, writing to
+ record manager succeeds, but corresponding writing to `VectorStore` fails.
+ """
+
+ def __init__(
+ self,
+ namespace: str,
+ ) -> None:
+ """Initialize the record manager.
+
+ Args:
+ namespace: The namespace for the record manager.
+ """
+ self.namespace = namespace
+
+ @abstractmethod
+ def create_schema(self) -> None:
+ """Create the database schema for the record manager."""
+
+ @abstractmethod
+ async def acreate_schema(self) -> None:
+ """Asynchronously create the database schema for the record manager."""
+
+ @abstractmethod
+ def get_time(self) -> float:
+ """Get the current server time as a high resolution timestamp!
+
+ It's important to get this from the server to ensure a monotonic clock,
+ otherwise there may be data loss when cleaning up old documents!
+
+ Returns:
+ The current server time as a float timestamp.
+ """
+
+ @abstractmethod
+ async def aget_time(self) -> float:
+ """Asynchronously get the current server time as a high resolution timestamp.
+
+ It's important to get this from the server to ensure a monotonic clock,
+ otherwise there may be data loss when cleaning up old documents!
+
+ Returns:
+ The current server time as a float timestamp.
+ """
+
+ @abstractmethod
+ def update(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores the data.
+
+ e.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group_ids.
+ """
+
+ @abstractmethod
+ async def aupdate(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Asynchronously upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores the data.
+
+ e.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group_ids.
+ """
+
+ @abstractmethod
+ def exists(self, keys: Sequence[str]) -> list[bool]:
+ """Check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+
+ @abstractmethod
+ async def aexists(self, keys: Sequence[str]) -> list[bool]:
+ """Asynchronously check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+
+ @abstractmethod
+ def list_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """List records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+ after: Filter to list records updated after this time.
+ group_ids: Filter to list records with specific group IDs.
+ limit: optional limit on the number of records to return.
+
+ Returns:
+ A list of keys for the matching records.
+ """
+
+ @abstractmethod
+ async def alist_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """Asynchronously list records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+ after: Filter to list records updated after this time.
+ group_ids: Filter to list records with specific group IDs.
+ limit: optional limit on the number of records to return.
+
+ Returns:
+ A list of keys for the matching records.
+ """
+
+ @abstractmethod
+ def delete_keys(self, keys: Sequence[str]) -> None:
+ """Delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+
+ @abstractmethod
+ async def adelete_keys(self, keys: Sequence[str]) -> None:
+ """Asynchronously delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+
+
+class _Record(TypedDict):
+ group_id: str | None
+ updated_at: float
+
+
+class InMemoryRecordManager(RecordManager):
+ """An in-memory record manager for testing purposes."""
+
+ def __init__(self, namespace: str) -> None:
+ """Initialize the in-memory record manager.
+
+ Args:
+ namespace: The namespace for the record manager.
+ """
+ super().__init__(namespace)
+ # Each key points to a dictionary
+ # of {'group_id': group_id, 'updated_at': timestamp}
+ self.records: dict[str, _Record] = {}
+ self.namespace = namespace
+
+ def create_schema(self) -> None:
+ """In-memory schema creation is simply ensuring the structure is initialized."""
+
+ async def acreate_schema(self) -> None:
+ """In-memory schema creation is simply ensuring the structure is initialized."""
+
+ @override
+ def get_time(self) -> float:
+ return time.time()
+
+ @override
+ async def aget_time(self) -> float:
+ return self.get_time()
+
+ def update(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores.
+ E.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group
+ ids.
+ ValueError: If time_at_least is in the future.
+ """
+ if group_ids and len(keys) != len(group_ids):
+ msg = "Length of keys must match length of group_ids"
+ raise ValueError(msg)
+ for index, key in enumerate(keys):
+ group_id = group_ids[index] if group_ids else None
+ if time_at_least and time_at_least > self.get_time():
+ msg = "time_at_least must be in the past"
+ raise ValueError(msg)
+ self.records[key] = {"group_id": group_id, "updated_at": self.get_time()}
+
+ async def aupdate(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Async upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores.
+ E.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+ """
+ self.update(keys, group_ids=group_ids, time_at_least=time_at_least)
+
+ def exists(self, keys: Sequence[str]) -> list[bool]:
+ """Check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+ return [key in self.records for key in keys]
+
+ async def aexists(self, keys: Sequence[str]) -> list[bool]:
+ """Async check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+ return self.exists(keys)
+
+ def list_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """List records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+
+ after: Filter to list records updated after this time.
+
+ group_ids: Filter to list records with specific group IDs.
+
+ limit: optional limit on the number of records to return.
+
+
+ Returns:
+ A list of keys for the matching records.
+ """
+ result = []
+ for key, data in self.records.items():
+ if before and data["updated_at"] >= before:
+ continue
+ if after and data["updated_at"] <= after:
+ continue
+ if group_ids and data["group_id"] not in group_ids:
+ continue
+ result.append(key)
+ if limit:
+ return result[:limit]
+ return result
+
+ async def alist_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """Async list records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+
+ after: Filter to list records updated after this time.
+
+ group_ids: Filter to list records with specific group IDs.
+
+ limit: optional limit on the number of records to return.
+
+
+ Returns:
+ A list of keys for the matching records.
+ """
+ return self.list_keys(
+ before=before, after=after, group_ids=group_ids, limit=limit
+ )
+
+ def delete_keys(self, keys: Sequence[str]) -> None:
+ """Delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+ for key in keys:
+ if key in self.records:
+ del self.records[key]
+
+ async def adelete_keys(self, keys: Sequence[str]) -> None:
+ """Async delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+ self.delete_keys(keys)
+
+
+class UpsertResponse(TypedDict):
+ """A generic response for upsert operations.
+
+ The upsert response will be used by abstractions that implement an upsert
+ operation for content that can be upserted by ID.
+
+ Upsert APIs that accept inputs with IDs and generate IDs internally
+ will return a response that includes the IDs that succeeded and the IDs
+ that failed.
+
+ If there are no failures, the failed list will be empty, and the order
+ of the IDs in the succeeded list will match the order of the input documents.
+
+ If there are failures, the response becomes ill defined, and a user of the API
+ cannot determine which generated ID corresponds to which input document.
+
+ It is recommended for users explicitly attach the IDs to the items being
+ indexed to avoid this issue.
+ """
+
+ succeeded: list[str]
+ """The IDs that were successfully indexed."""
+ failed: list[str]
+ """The IDs that failed to index."""
+
+
+class DeleteResponse(TypedDict, total=False):
+ """A generic response for delete operation.
+
+ The fields in this response are optional and whether the `VectorStore`
+ returns them or not is up to the implementation.
+ """
+
+ num_deleted: int
+ """The number of items that were successfully deleted.
+
+ If returned, this should only include *actual* deletions.
+
+ If the ID did not exist to begin with,
+ it should not be included in this count.
+ """
+
+ succeeded: Sequence[str]
+ """The IDs that were successfully deleted.
+
+ If returned, this should only include *actual* deletions.
+
+ If the ID did not exist to begin with,
+ it should not be included in this list.
+ """
+
+ failed: Sequence[str]
+ """The IDs that failed to be deleted.
+
+ !!! warning
+ Deleting an ID that does not exist is **NOT** considered a failure.
+ """
+
+ num_failed: int
+ """The number of items that failed to be deleted."""
+
+
+@beta(message="Added in 0.2.29. The abstraction is subject to change.")
+class DocumentIndex(BaseRetriever):
+ """A document retriever that supports indexing operations.
+
+ This indexing interface is designed to be a generic abstraction for storing and
+ querying documents that has an ID and metadata associated with it.
+
+ The interface is designed to be agnostic to the underlying implementation of the
+ indexing system.
+
+ The interface is designed to support the following operations:
+
+ 1. Storing document in the index.
+ 2. Fetching document by ID.
+ 3. Searching for document using a query.
+ """
+
+ @abc.abstractmethod
+ def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse:
+ """Upsert documents into the index.
+
+ The upsert functionality should utilize the ID field of the content object
+ if it is provided. If the ID is not provided, the upsert method is free
+ to generate an ID for the content.
+
+ When an ID is specified and the content already exists in the `VectorStore`,
+ the upsert method should update the content with the new data. If the content
+ does not exist, the upsert method should add the item to the `VectorStore`.
+
+ Args:
+ items: Sequence of documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the `VectorStore` and the list of IDs that
+ failed to be added or updated.
+ """
+
+ async def aupsert(
+ self, items: Sequence[Document], /, **kwargs: Any
+ ) -> UpsertResponse:
+ """Add or update documents in the `VectorStore`. Async version of `upsert`.
+
+ The upsert functionality should utilize the ID field of the item
+ if it is provided. If the ID is not provided, the upsert method is free
+ to generate an ID for the item.
+
+ When an ID is specified and the item already exists in the `VectorStore`,
+ the upsert method should update the item with the new data. If the item
+ does not exist, the upsert method should add the item to the `VectorStore`.
+
+ Args:
+ items: Sequence of documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the `VectorStore` and the list of IDs that
+ failed to be added or updated.
+ """
+ return await run_in_executor(
+ None,
+ self.upsert,
+ items,
+ **kwargs,
+ )
+
+ @abc.abstractmethod
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> DeleteResponse:
+ """Delete by IDs or other criteria.
+
+ Calling delete without any input parameters should raise a ValueError!
+
+ Args:
+ ids: List of IDs to delete.
+ **kwargs: Additional keyword arguments. This is up to the implementation.
+ For example, can include an option to delete the entire index,
+ or else issue a non-blocking delete etc.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully deleted and the list of IDs that failed to be deleted.
+ """
+
+ async def adelete(
+ self, ids: list[str] | None = None, **kwargs: Any
+ ) -> DeleteResponse:
+ """Delete by IDs or other criteria. Async variant.
+
+ Calling adelete without any input parameters should raise a ValueError!
+
+ Args:
+ ids: List of IDs to delete.
+ **kwargs: Additional keyword arguments. This is up to the implementation.
+ For example, can include an option to delete the entire index.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully deleted and the list of IDs that failed to be deleted.
+ """
+ return await run_in_executor(
+ None,
+ self.delete,
+ ids,
+ **kwargs,
+ )
+
+ @abc.abstractmethod
+ def get(
+ self,
+ ids: Sequence[str],
+ /,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Get documents by id.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to get.
+ **kwargs: Additional keyword arguments. These are up to the implementation.
+
+ Returns:
+ List of documents that were found.
+ """
+
+ async def aget(
+ self,
+ ids: Sequence[str],
+ /,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Get documents by id.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to get.
+ **kwargs: Additional keyword arguments. These are up to the implementation.
+
+ Returns:
+ List of documents that were found.
+ """
+ return await run_in_executor(
+ None,
+ self.get,
+ ids,
+ **kwargs,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/indexing/in_memory.py b/python/user_packages/Python313/site-packages/langchain_core/indexing/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae9cf84088dcbc5384de8149409b79d5556b3c0f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/indexing/in_memory.py
@@ -0,0 +1,104 @@
+"""In memory document index."""
+
+import operator
+import uuid
+from collections.abc import Sequence
+from typing import Any, cast
+
+from pydantic import Field
+from typing_extensions import override
+
+from langchain_core._api import beta
+from langchain_core.callbacks import CallbackManagerForRetrieverRun
+from langchain_core.documents import Document
+from langchain_core.indexing import UpsertResponse
+from langchain_core.indexing.base import DeleteResponse, DocumentIndex
+
+
+@beta(message="Introduced in version 0.2.29. Underlying abstraction subject to change.")
+class InMemoryDocumentIndex(DocumentIndex):
+ """In memory document index.
+
+ This is an in-memory document index that stores documents in a dictionary.
+
+ It provides a simple search API that returns documents by the number of
+ counts the given query appears in the document.
+ """
+
+ store: dict[str, Document] = Field(default_factory=dict)
+ top_k: int = 4
+
+ @override
+ def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse:
+ """Upsert documents into the index.
+
+ Args:
+ items: Sequence of documents to add to the index.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the index and the list of IDs that
+ failed to be added or updated.
+ """
+ ok_ids = []
+
+ for item in items:
+ if item.id is None:
+ id_ = str(uuid.uuid4())
+ item_ = item.model_copy()
+ item_.id = id_
+ else:
+ item_ = item
+ id_ = item.id
+
+ self.store[id_] = item_
+ ok_ids.append(cast("str", item_.id))
+
+ return UpsertResponse(succeeded=ok_ids, failed=[])
+
+ @override
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> DeleteResponse:
+ """Delete by IDs.
+
+ Args:
+ ids: List of IDs to delete.
+
+ Raises:
+ ValueError: If IDs is None.
+
+ Returns:
+ A response object that contains the list of IDs that were successfully
+ deleted and the list of IDs that failed to be deleted.
+ """
+ if ids is None:
+ msg = "IDs must be provided for deletion"
+ raise ValueError(msg)
+
+ ok_ids = []
+
+ for id_ in ids:
+ if id_ in self.store:
+ del self.store[id_]
+ ok_ids.append(id_)
+
+ return DeleteResponse(
+ succeeded=ok_ids, num_deleted=len(ok_ids), num_failed=0, failed=[]
+ )
+
+ @override
+ def get(self, ids: Sequence[str], /, **kwargs: Any) -> list[Document]:
+ return [self.store[id_] for id_ in ids if id_ in self.store]
+
+ @override
+ def _get_relevant_documents(
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun
+ ) -> list[Document]:
+ counts_by_doc = []
+
+ for document in self.store.values():
+ count = document.page_content.count(query)
+ counts_by_doc.append((document, count))
+
+ counts_by_doc.sort(key=operator.itemgetter(1), reverse=True)
+ return [doc.model_copy() for doc, count in counts_by_doc[: self.top_k]]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..722597d410581a7f9fb12e9ca63e9fcc232b62bc
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/__init__.py
@@ -0,0 +1,116 @@
+"""Core language model abstractions.
+
+LangChain has two main classes to work with language models: chat models and
+"old-fashioned" LLMs (string-in, string-out).
+
+**Chat models**
+
+Language models that use a sequence of messages as inputs and return chat messages
+as outputs (as opposed to using plain text).
+
+Chat models support the assignment of distinct roles to conversation messages, helping
+to distinguish messages from the AI, users, and instructions such as system messages.
+
+The key abstraction for chat models is
+[`BaseChatModel`][langchain_core.language_models.BaseChatModel]. Implementations should
+inherit from this class.
+
+See existing [chat model integrations](https://docs.langchain.com/oss/python/integrations/chat).
+
+**LLMs (legacy)**
+
+Language models that takes a string as input and returns a string.
+
+These are traditionally older models (newer models generally are chat models).
+
+Although the underlying models are string in, string out, the LangChain wrappers also
+allow these models to take messages as input. This gives them the same interface as
+chat models. When messages are passed in as input, they will be formatted into a string
+under the hood before being passed to the underlying model.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+from langchain_core.language_models._utils import is_openai_data_block
+
+if TYPE_CHECKING:
+ from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+ LanguageModelLike,
+ LanguageModelOutput,
+ get_tokenizer,
+ )
+ from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ SimpleChatModel,
+ )
+ from langchain_core.language_models.fake import FakeListLLM, FakeStreamingListLLM
+ from langchain_core.language_models.fake_chat_models import (
+ FakeListChatModel,
+ FakeMessagesListChatModel,
+ GenericFakeChatModel,
+ ParrotFakeChatModel,
+ )
+ from langchain_core.language_models.llms import LLM, BaseLLM
+ from langchain_core.language_models.model_profile import (
+ ModelProfile,
+ ModelProfileRegistry,
+ )
+
+__all__ = (
+ "LLM",
+ "BaseChatModel",
+ "BaseLLM",
+ "BaseLanguageModel",
+ "FakeListChatModel",
+ "FakeListLLM",
+ "FakeMessagesListChatModel",
+ "FakeStreamingListLLM",
+ "GenericFakeChatModel",
+ "LangSmithParams",
+ "LanguageModelInput",
+ "LanguageModelLike",
+ "LanguageModelOutput",
+ "ModelProfile",
+ "ModelProfileRegistry",
+ "ParrotFakeChatModel",
+ "SimpleChatModel",
+ "get_tokenizer",
+ "is_openai_data_block",
+)
+
+_dynamic_imports = {
+ "BaseLanguageModel": "base",
+ "LangSmithParams": "base",
+ "LanguageModelInput": "base",
+ "LanguageModelLike": "base",
+ "LanguageModelOutput": "base",
+ "get_tokenizer": "base",
+ "BaseChatModel": "chat_models",
+ "SimpleChatModel": "chat_models",
+ "FakeListLLM": "fake",
+ "FakeStreamingListLLM": "fake",
+ "FakeListChatModel": "fake_chat_models",
+ "FakeMessagesListChatModel": "fake_chat_models",
+ "GenericFakeChatModel": "fake_chat_models",
+ "ParrotFakeChatModel": "fake_chat_models",
+ "LLM": "llms",
+ "ModelProfile": "model_profile",
+ "ModelProfileRegistry": "model_profile",
+ "BaseLLM": "llms",
+ "is_openai_data_block": "_utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a39193d231b9245d2468c682e6f1d7c5f8571942
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c9f54f62c3657b83809ff29e4e9524d41615fe1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4982f836c16f9be5e20279cb010b60b62c7ac1d8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83ee6dca11b79297b0198c757ee79699ecb1bf2c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c03692d42114e941dde3d9edd11cf99ac9bcf20f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_models.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_models.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f05b5f747114d535330844e99ce8bf5beaf88a0d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/chat_models.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..edee39b5680ea79732b366115d9465a5c710b387
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f22ba1dccc5e891747e85bc1cac502e130ca4b52
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/llms.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/llms.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8583ea85e70e6e99f0d15b55dc6aae19f711acce
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/llms.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2accea897d03a33b50848eacc6dd490bbf4d57fe
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/_compat_bridge.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/_compat_bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c2cdf0ba0d96e756c2540087d7fd6230a978018
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/_compat_bridge.py
@@ -0,0 +1,778 @@
+"""Compat bridge: convert `AIMessageChunk` streams to protocol events.
+
+The bridge trusts `AIMessageChunk.content_blocks` as the single
+protocol view of any chunk. That property runs the three-tier lookup
+(`output_version == "v1"` short-circuit, registered translator, or
+best-effort parsing) and returns a `list[ContentBlock]` for every
+well-formed message — whether the provider is a registered partner, an
+unregistered community model, or not tagged at all.
+
+Per-chunk `content_blocks` output is a **delta slice**, not accumulated
+state: providers in this ecosystem emit SSE-style chunks that each carry
+their own increment. The bridge therefore forwards each slice straight
+through as a `content-block-delta` event, and accumulates per-index
+state only so the final `content-block-finish` event can report a
+finalized block (e.g. `tool_call_chunk` args parsed to a dict).
+
+Lifecycle::
+
+ message-start
+ -> content-block-start (first time each index is observed)
+ -> content-block-delta* (per chunk, carrying the slice)
+ -> content-block-finish (finalized block)
+ -> message-finish
+
+Public API:
+
+- `chunks_to_events` / `achunks_to_events` — for live streams where
+ chunks arrive over time.
+- `message_to_events` / `amessage_to_events` — for replaying a finalized
+ `AIMessage` (cache hit, checkpoint restore, graph-node return value)
+ as a synthetic event lifecycle.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any, cast
+
+from langchain_protocol.protocol import (
+ ContentBlock,
+ ContentBlockDeltaData,
+ ContentBlockFinishData,
+ ContentBlockStartData,
+ FinalizedContentBlock,
+ InvalidToolCall,
+ MessageFinishData,
+ MessageMetadata,
+ MessagesData,
+ MessageStartData,
+ ReasoningContentBlock,
+ ServerToolCall,
+ ServerToolCallChunk,
+ TextContentBlock,
+ ToolCall,
+ ToolCallChunk,
+ UsageInfo,
+)
+
+from langchain_core.messages import AIMessageChunk, BaseMessage
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_protocol.protocol import (
+ BlockDelta,
+ BlockDeltaFields,
+ ContentBlockDelta,
+ DataDelta,
+ ReasoningDelta,
+ TextDelta,
+ )
+
+ from langchain_core.outputs import ChatGenerationChunk
+
+
+CompatBlock = dict[str, Any]
+"""Internal working type for a content block.
+
+The bridge works with plain dicts internally because two separate but
+structurally similar `ContentBlock` Unions exist — one in
+`langchain_core.messages.content` (returned by `msg.content_blocks`),
+one in `langchain_protocol.protocol` (the wire/event shape). They are
+not mypy-compatible despite being near-isomorphic. Passing through
+`dict[str, Any]` launders between them. See `_to_protocol_block` for
+the single seam where the laundering cast lives.
+"""
+
+
+# ---------------------------------------------------------------------------
+# Type laundering between core and protocol `ContentBlock` unions
+# ---------------------------------------------------------------------------
+
+
+def _to_protocol_block(block: CompatBlock) -> ContentBlock:
+ """Narrow an internal working dict to a protocol `ContentBlock`.
+
+ Single seam between the two `ContentBlock` type systems:
+ `langchain_core.messages.content` (what `msg.content_blocks`
+ returns) and `langchain_protocol.protocol` (what event payloads
+ require). The two Unions overlap structurally but are nominally
+ distinct to mypy, so we launder through `dict[str, Any]`. When the
+ Unions are unified, this helper and its finalized counterpart can be
+ deleted.
+ """
+ return cast("ContentBlock", block)
+
+
+def _to_finalized_block(block: CompatBlock) -> FinalizedContentBlock:
+ """Counterpart of `_to_protocol_block` for finalized blocks."""
+ return cast("FinalizedContentBlock", block)
+
+
+def _to_block_delta_fields(block: CompatBlock) -> BlockDeltaFields:
+ """Narrow an internal working dict to protocol block-delta fields."""
+ return cast("BlockDeltaFields", block)
+
+
+def _to_content_delta(block: CompatBlock) -> ContentBlockDelta:
+ """Convert a content-block slice/snapshot to an explicit protocol delta."""
+ btype = block.get("type")
+ if btype == "text":
+ return cast("TextDelta", {"type": "text-delta", "text": block.get("text", "")})
+ if btype == "reasoning":
+ return cast(
+ "ReasoningDelta",
+ {
+ "type": "reasoning-delta",
+ "reasoning": block.get("reasoning", ""),
+ },
+ )
+ if "data" in block:
+ delta = cast("DataDelta", {"type": "data-delta", "data": block.get("data", "")})
+ if block.get("encoding") == "base64":
+ delta["encoding"] = "base64"
+ return delta
+ return cast(
+ "BlockDelta",
+ {
+ "type": "block-delta",
+ "fields": _to_block_delta_fields(block),
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# Block iteration
+# ---------------------------------------------------------------------------
+
+
+def _iter_protocol_blocks(msg: BaseMessage) -> list[tuple[Any, CompatBlock]]:
+ """Read per-chunk protocol blocks from `msg.content_blocks`.
+
+ Returns `(key, block)` pairs. The key is the block's stable identifier
+ across the stream: the block's `index` field when present (can be an
+ int or a string — some providers use string identifiers like
+ `"lc_rs_305f30"`), or the positional index within the message as a
+ fallback. Callers are responsible for allocating wire-level `uint`
+ indices; this helper only surfaces the source-side identity.
+
+ For finalized `AIMessage`, also surfaces `invalid_tool_calls`
+ — which `AIMessage.content_blocks` currently omits from its return
+ value even though they are a defined protocol block type.
+
+ The positional fallback is a known fragility: when a provider emits
+ blocks without an `index` field (e.g. Anthropic's `_stream` with
+ `coerce_content_to_string=True`, where text chunks lose their
+ source-side index), every such chunk gets positional key 0 and
+ successive chunks merge into one block. This works correctly for
+ single-type streams (pure-text responses merge cleanly) because all
+ chunks share the same key and the open-block logic collapses them.
+ It would miscategorise a stream that mixed indexed structured
+ blocks with non-indexed coerced-text blocks, since an indexed
+ block with `index == 0` would collide with the anonymous text
+ block's positional-0 key. In the anthropic integration this
+ cannot currently occur: coerce-to-string mode is only selected
+ when no tools, thinking, or documents are present, and any of
+ those flips the stream to structured mode where every block
+ carries an integer index. A native `_stream_chat_model_events`
+ hook per provider (or a bridge-level "continue the open block when
+ the source has no identity" rule) would close the gap if another
+ integration ever emits mixed content.
+ """
+ try:
+ raw = msg.content_blocks
+ except Exception:
+ return []
+
+ result: list[tuple[Any, CompatBlock]] = []
+ for i, block in enumerate(raw):
+ if not isinstance(block, dict):
+ continue
+ key = block.get("index", i)
+ result.append((key, dict(block)))
+
+ if not isinstance(msg, AIMessageChunk):
+ # Finalized AIMessage: pull invalid_tool_calls from the dedicated
+ # field — AIMessage.content_blocks does not currently include them.
+ for itc in getattr(msg, "invalid_tool_calls", None) or []:
+ itc_block: CompatBlock = {"type": "invalid_tool_call"}
+ for key_name in ("id", "name", "args", "error"):
+ if itc.get(key_name) is not None:
+ itc_block[key_name] = itc[key_name]
+ result.append((len(result), itc_block))
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Per-block helpers
+# ---------------------------------------------------------------------------
+
+
+# Fields that can carry large payloads (inline base64 media, parsed args,
+# arbitrary dicts). Stripped from `content-block-start` for self-contained
+# block types so the payload rides on `content-block-finish` alone instead
+# of being serialized twice on the wire.
+_HEAVY_FIELDS = frozenset({"args", "data", "output", "transcript", "value"})
+
+
+def _start_skeleton(block: CompatBlock) -> ContentBlock:
+ """Empty-content placeholder for the `content-block-start` event.
+
+ Deltaable block types (text, reasoning, the `_chunk` tool variants)
+ get an empty payload so the lifecycle's "start" signal is distinct
+ from the first incremental delta. Self-contained types (image,
+ audio, video, file, non_standard, finalized tool calls) drop their
+ heavy payload fields; those are carried by `content-block-finish`.
+ Correlation fields (id, name, toolCallId) and small metadata
+ (mime_type, url, status, …) are preserved on the start event.
+ """
+ btype = block.get("type", "text")
+ if btype == "text":
+ return TextContentBlock(type="text", text="")
+ if btype == "reasoning":
+ return ReasoningContentBlock(type="reasoning", reasoning="")
+ if btype == "tool_call_chunk":
+ return ToolCallChunk(
+ type="tool_call_chunk",
+ id=block.get("id"),
+ name=block.get("name"),
+ args="",
+ )
+ if btype == "server_tool_call_chunk":
+ s_skel = ServerToolCallChunk(
+ type="server_tool_call_chunk",
+ args="",
+ )
+ if block.get("id") is not None:
+ s_skel["id"] = block["id"]
+ if block.get("name") is not None:
+ s_skel["name"] = block["name"]
+ return s_skel
+
+ stripped: CompatBlock = {k: v for k, v in block.items() if k not in _HEAVY_FIELDS}
+ # Restore required-but-heavy fields with minimal placeholders so the
+ # start event still validates against the CDDL shape of the block type.
+ if btype in ("tool_call", "server_tool_call"):
+ stripped["args"] = {}
+ elif btype == "non_standard":
+ stripped["value"] = {}
+ return _to_protocol_block(stripped)
+
+
+def _should_emit_delta(block: CompatBlock) -> bool:
+ """Whether a per-chunk block carries content worth a delta event.
+
+ Deltaable types emit only when they have fresh content. Self-contained
+ / already-finalized types skip the delta entirely — the `finish`
+ event carries them.
+ """
+ btype = block.get("type")
+ if btype == "text":
+ return bool(block.get("text"))
+ if btype == "reasoning":
+ return bool(block.get("reasoning"))
+ if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ return bool(
+ block.get("args") or block.get("id") or block.get("name"),
+ )
+ if "data" in block:
+ return bool(block.get("data"))
+ return False
+
+
+def _accumulate(state: CompatBlock | None, delta: CompatBlock) -> CompatBlock:
+ """Merge a per-chunk delta slice into accumulated per-index state.
+
+ Used only for the finalization pass — live delta events are emitted
+ directly from the per-chunk block, without round-tripping through
+ accumulated state.
+ """
+ if state is None:
+ return dict(delta)
+ btype = state.get("type")
+ dtype = delta.get("type")
+ if btype == "text" and dtype == "text":
+ state["text"] = state.get("text", "") + delta.get("text", "")
+ # Providers may send non-text fields (like `id`, or annotations)
+ # on later deltas. Merging (not replacing) keeps earlier keys
+ # intact while picking up these late-arriving fields.
+ for key, value in delta.items():
+ if key in ("type", "text") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ elif btype == "reasoning" and dtype == "reasoning":
+ state["reasoning"] = state.get("reasoning", "") + delta.get("reasoning", "")
+ # Providers may ship non-text fields on later deltas. Claude's
+ # `signature_delta` arrives after the reasoning text, surfaced
+ # as `extras.signature`; merging (not replacing) keeps earlier
+ # keys intact.
+ for key, value in delta.items():
+ if key in ("type", "reasoning") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ elif btype in ("tool_call_chunk", "server_tool_call_chunk") and dtype == btype:
+ state["args"] = (state.get("args", "") or "") + (delta.get("args") or "")
+ if delta.get("id") is not None:
+ state["id"] = delta["id"]
+ if delta.get("name") is not None:
+ state["name"] = delta["name"]
+ elif btype == dtype and "data" in delta:
+ state["data"] = (state.get("data", "") or "") + (delta.get("data") or "")
+ for key, value in delta.items():
+ if key in ("type", "data") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ else:
+ # Self-contained or already-finalized types: replace wholesale.
+ state.clear()
+ state.update(delta)
+ return state
+
+
+def finalize_tool_call_chunk(
+ *,
+ raw_args: str | None,
+ id_: str | None,
+ name: str | None,
+ extras: dict[str, Any],
+ finalized_type: str,
+) -> FinalizedContentBlock:
+ """Parse accumulated tool-chunk args into a finalized block.
+
+ Shared between the compat bridge's `_finalize_block` and the
+ `ChatModelStream` end-of-stream sweep. Parses `raw_args` as JSON:
+ on success builds the requested finalized type (`tool_call` or
+ `server_tool_call`) with provider-specific fields (`extras`)
+ preserved; on failure falls back to `invalid_tool_call` carrying
+ the raw string so downstream consumers can still introspect the
+ malformed payload.
+
+ Args:
+ raw_args: Accumulated partial-JSON string; `None` or empty
+ treated as `{}`.
+ id_: Tool-call id collected across chunks.
+ name: Tool name collected across chunks.
+ extras: Provider-specific fields to carry onto the finalized
+ block. Callers are responsible for having already dropped
+ keys they don't want propagated (notably `type`, `id`,
+ `name`, `args`, and `index` on client-side `tool_call`).
+ finalized_type: `"tool_call"` or `"server_tool_call"`.
+
+ Returns:
+ A `ToolCall`, `ServerToolCall`, or `InvalidToolCall` — the
+ latter when `raw_args` is non-empty but not valid JSON.
+ """
+ raw = raw_args or "{}"
+ try:
+ parsed = json.loads(raw) if raw else {}
+ except (json.JSONDecodeError, TypeError):
+ invalid = InvalidToolCall(
+ type="invalid_tool_call",
+ id=id_,
+ name=name,
+ args=raw,
+ error="Failed to parse tool call arguments as JSON",
+ )
+ invalid.update(extras) # type: ignore[typeddict-item]
+ return invalid
+ if finalized_type == "tool_call":
+ finalized_tc = ToolCall(
+ type="tool_call",
+ id=id_ or "",
+ name=name or "",
+ args=parsed,
+ )
+ finalized_tc.update(extras) # type: ignore[typeddict-item]
+ return finalized_tc
+ finalized_stc = ServerToolCall(
+ type="server_tool_call",
+ id=id_ or "",
+ name=name or "",
+ args=parsed,
+ )
+ finalized_stc.update(extras) # type: ignore[typeddict-item]
+ return finalized_stc
+
+
+def _finalize_block(block: CompatBlock) -> FinalizedContentBlock:
+ """Promote chunk variants to their finalized form.
+
+ `tool_call_chunk` becomes `tool_call` — or `invalid_tool_call`
+ if the accumulated `args` don't parse as JSON.
+ `server_tool_call_chunk` becomes `server_tool_call` under the same
+ rule. Everything else passes through: text/reasoning blocks carry
+ their accumulated snapshot, and self-contained types are already in
+ their terminal shape.
+ """
+ btype = block.get("type")
+ if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ # Carry provider-specific fields from the accumulated chunk onto
+ # the finalized block. Drop the chunk-only keys we rewrite
+ # explicitly. `index` is stripped on client-side
+ # `tool_call` / `invalid_tool_call` finalizations to match v1
+ # (`AIMessage.init_tool_calls` rebuilds tool_call blocks without
+ # `index`), preventing `merge_lists` from re-merging further
+ # chunks into an already-parsed args dict. `server_tool_call`
+ # retains `index` because v1's `init_server_tool_calls`
+ # finalizes in-place and preserves it.
+ client_tool_call = btype == "tool_call_chunk"
+ extras_drop = {"type", "id", "name", "args"}
+ if client_tool_call:
+ extras_drop = extras_drop | {"index"}
+ extras = {
+ k: v for k, v in block.items() if k not in extras_drop and v is not None
+ }
+ return finalize_tool_call_chunk(
+ raw_args=block.get("args"),
+ id_=block.get("id"),
+ name=block.get("name"),
+ extras=extras,
+ finalized_type="tool_call" if client_tool_call else "server_tool_call",
+ )
+ return _to_finalized_block(block)
+
+
+# ---------------------------------------------------------------------------
+# Metadata, usage, finish-reason
+# ---------------------------------------------------------------------------
+
+
+def _extract_start_metadata(response_metadata: dict[str, Any]) -> MessageMetadata:
+ """Pull provider/model hints for the `message-start` event."""
+ metadata: MessageMetadata = {}
+ if "model_provider" in response_metadata:
+ metadata["provider"] = response_metadata["model_provider"]
+ if "model_name" in response_metadata:
+ metadata["model"] = response_metadata["model_name"]
+ return metadata
+
+
+def _accumulate_usage(
+ current: dict[str, Any] | None, delta: Any
+) -> dict[str, Any] | None:
+ """Sum usage counts and merge detail dicts across chunks."""
+ if not isinstance(delta, dict):
+ return current
+ if current is None:
+ return dict(delta)
+ for key in ("input_tokens", "output_tokens", "total_tokens", "cached_tokens"):
+ if key in delta:
+ current[key] = current.get(key, 0) + delta[key]
+ for detail_key in ("input_token_details", "output_token_details"):
+ if detail_key in delta and isinstance(delta[detail_key], dict):
+ if detail_key not in current:
+ current[detail_key] = {}
+ current[detail_key].update(delta[detail_key])
+ return current
+
+
+def _to_protocol_usage(usage: dict[str, Any] | None) -> UsageInfo | None:
+ """Convert accumulated usage to the protocol's `UsageInfo` shape."""
+ if usage is None:
+ return None
+ result: dict[str, Any] = {}
+ for key in ("input_tokens", "output_tokens", "total_tokens", "cached_tokens"):
+ if key in usage:
+ result[key] = usage[key]
+ return cast("UsageInfo", result) if result else None
+
+
+# ---------------------------------------------------------------------------
+# Event builders
+# ---------------------------------------------------------------------------
+
+
+def _build_message_start(
+ msg: BaseMessage,
+ message_id: str | None,
+) -> MessageStartData:
+ start_data = MessageStartData(event="message-start", role="ai", id="")
+ resolved_id = message_id if message_id is not None else getattr(msg, "id", None)
+ if resolved_id:
+ start_data["id"] = resolved_id
+ start_metadata = _extract_start_metadata(msg.response_metadata or {})
+ if start_metadata:
+ start_data["metadata"] = start_metadata
+ return start_data
+
+
+def _build_message_finish(
+ *,
+ usage: dict[str, Any] | None,
+ response_metadata: dict[str, Any] | None,
+) -> MessageFinishData:
+ # Protocol 0.0.9 removed the top-level `reason` field from
+ # `MessageFinishData`; the provider's raw `finish_reason` /
+ # `stop_reason` now rides inside `metadata` alongside other
+ # response metadata. Pass it through unchanged.
+ finish_data: dict[str, Any] = {"event": "message-finish"}
+ usage_info = _to_protocol_usage(usage)
+ if usage_info is not None:
+ finish_data["usage"] = usage_info
+ if response_metadata:
+ finish_data["metadata"] = dict(response_metadata)
+ return cast("MessageFinishData", finish_data)
+
+
+def _finalize_and_build_finish(
+ wire_idx: int,
+ block: CompatBlock,
+) -> MessagesData:
+ """Finalize a block and wrap it in a `content-block-finish` event."""
+ return ContentBlockFinishData(
+ event="content-block-finish",
+ index=wire_idx,
+ content=_finalize_block(block),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Main generators
+# ---------------------------------------------------------------------------
+
+
+def chunks_to_events(
+ chunks: Iterator[ChatGenerationChunk],
+ *,
+ message_id: str | None = None,
+) -> Iterator[MessagesData]:
+ """Convert a stream of `ChatGenerationChunk` to protocol events.
+
+ Blocks are tracked independently by source-side identifier. Providers
+ such as Anthropic can interleave parallel tool-call chunks by index, so
+ each first-seen block gets a `content-block-start`, deltas keep their
+ stable wire index, and all open blocks are finalized at message end.
+ Source-side identifiers (from the block's `index` field, which may be
+ int or string) are translated to sequential `uint` wire indices.
+
+ Args:
+ chunks: Iterator of `ChatGenerationChunk` from `_stream()`.
+ message_id: Optional stable message ID.
+
+ Yields:
+ `MessagesData` lifecycle events.
+ """
+ started = False
+ blocks: dict[Any, tuple[int, CompatBlock]] = {}
+ next_wire_idx = 0
+ usage: dict[str, Any] | None = None
+ response_metadata: dict[str, Any] = {}
+
+ for chunk in chunks:
+ msg = chunk.message
+ if not isinstance(msg, AIMessageChunk):
+ continue
+
+ # The v1 `stream()` wrapper merges `generation_info` into
+ # `response_metadata` before yielding (`chat_models.py` via
+ # `_gen_info_and_msg_metadata`). We bypass that wrapper by reading
+ # `_stream` directly, so reproduce the merge here with the same
+ # priority: `generation_info` first, then `message.response_metadata`
+ # overlays. This is how provider fields like `model_name`,
+ # `system_fingerprint`, and `finish_reason` reach the bridge when
+ # a provider emits them via `generation_info` instead of the
+ # message's `response_metadata`.
+ merged_rm: dict[str, Any] = {
+ **(chunk.generation_info or {}),
+ **(msg.response_metadata or {}),
+ }
+ if merged_rm:
+ response_metadata.update(merged_rm)
+
+ if not started:
+ started = True
+ yield _build_message_start(msg, message_id)
+
+ for key, block in _iter_protocol_blocks(msg):
+ if key not in blocks:
+ wire_idx = next_wire_idx
+ next_wire_idx += 1
+ blocks[key] = (wire_idx, dict(block))
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ else:
+ wire_idx, existing = blocks[key]
+ blocks[key] = (wire_idx, _accumulate(existing, block))
+ if _should_emit_delta(block):
+ wire_idx, current = blocks[key]
+ is_block_delta = block.get("type") in (
+ "tool_call_chunk",
+ "server_tool_call_chunk",
+ )
+ delta_source = current if is_block_delta else block
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(delta_source or block),
+ )
+
+ if msg.usage_metadata:
+ usage = _accumulate_usage(usage, msg.usage_metadata)
+
+ if not started:
+ return
+
+ for wire_idx, block in blocks.values():
+ yield _finalize_and_build_finish(wire_idx, block)
+
+ yield _build_message_finish(
+ usage=usage,
+ response_metadata=response_metadata,
+ )
+
+
+async def achunks_to_events(
+ chunks: AsyncIterator[ChatGenerationChunk],
+ *,
+ message_id: str | None = None,
+) -> AsyncIterator[MessagesData]:
+ """Async variant of `chunks_to_events`."""
+ started = False
+ blocks: dict[Any, tuple[int, CompatBlock]] = {}
+ next_wire_idx = 0
+ usage: dict[str, Any] | None = None
+ response_metadata: dict[str, Any] = {}
+
+ async for chunk in chunks:
+ msg = chunk.message
+ if not isinstance(msg, AIMessageChunk):
+ continue
+
+ # See sync twin for rationale: merge `generation_info` into the
+ # accumulated `response_metadata` with the same priority as the
+ # v1 `stream()` wrapper.
+ merged_rm: dict[str, Any] = {
+ **(chunk.generation_info or {}),
+ **(msg.response_metadata or {}),
+ }
+ if merged_rm:
+ response_metadata.update(merged_rm)
+
+ if not started:
+ started = True
+ yield _build_message_start(msg, message_id)
+
+ for key, block in _iter_protocol_blocks(msg):
+ if key not in blocks:
+ wire_idx = next_wire_idx
+ next_wire_idx += 1
+ blocks[key] = (wire_idx, dict(block))
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ else:
+ wire_idx, existing = blocks[key]
+ blocks[key] = (wire_idx, _accumulate(existing, block))
+ if _should_emit_delta(block):
+ wire_idx, current = blocks[key]
+ is_block_delta = block.get("type") in (
+ "tool_call_chunk",
+ "server_tool_call_chunk",
+ )
+ delta_source = current if is_block_delta else block
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(delta_source or block),
+ )
+
+ if msg.usage_metadata:
+ usage = _accumulate_usage(usage, msg.usage_metadata)
+
+ if not started:
+ return
+
+ for wire_idx, block in blocks.values():
+ yield _finalize_and_build_finish(wire_idx, block)
+
+ yield _build_message_finish(
+ usage=usage,
+ response_metadata=response_metadata,
+ )
+
+
+def message_to_events(
+ msg: BaseMessage,
+ *,
+ message_id: str | None = None,
+) -> Iterator[MessagesData]:
+ """Replay a finalized message as a synthetic event lifecycle.
+
+ For a message returned whole (from a graph node, checkpoint, or
+ cache), produce the same `message-start` / per-block /
+ `message-finish` event stream a live call would produce. Consumers
+ downstream see a uniform event shape regardless of source.
+
+ Text and reasoning blocks emit a single `content-block-delta` with
+ the full accumulated content. Already-finalized blocks (tool_call,
+ server_tool_call, image, etc.) skip the delta and rely on the
+ `content-block-finish` event alone.
+
+ Args:
+ msg: The finalized message — typically an `AIMessage`.
+ message_id: Optional stable message ID; falls back to `msg.id`.
+
+ Yields:
+ `MessagesData` lifecycle events.
+ """
+ response_metadata = msg.response_metadata or {}
+ yield _build_message_start(msg, message_id)
+
+ for wire_idx, (_key, block) in enumerate(_iter_protocol_blocks(msg)):
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ if _should_emit_delta(block):
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(block),
+ )
+ yield ContentBlockFinishData(
+ event="content-block-finish",
+ index=wire_idx,
+ content=_finalize_block(block),
+ )
+
+ yield _build_message_finish(
+ usage=getattr(msg, "usage_metadata", None),
+ response_metadata=response_metadata,
+ )
+
+
+async def amessage_to_events(
+ msg: BaseMessage,
+ *,
+ message_id: str | None = None,
+) -> AsyncIterator[MessagesData]:
+ """Async variant of `message_to_events`."""
+ for event in message_to_events(msg, message_id=message_id):
+ yield event
+
+
+__all__ = [
+ "CompatBlock",
+ "achunks_to_events",
+ "amessage_to_events",
+ "chunks_to_events",
+ "finalize_tool_call_chunk",
+ "message_to_events",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/_utils.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..289b675307415364adb94d19a7559bcb51738e5b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/_utils.py
@@ -0,0 +1,343 @@
+import re
+from collections.abc import Sequence
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypedDict,
+ TypeVar,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.messages import BaseMessage
+from langchain_core.messages.content import (
+ ContentBlock,
+)
+
+
+def _filter_invocation_params_for_tracing(params: dict[str, Any]) -> dict[str, Any]:
+ """Filter out large/inappropriate fields from invocation params for tracing.
+
+ Removes fields like tools, functions, messages, response_format that can be large.
+
+ Args:
+ params: The invocation parameters to filter.
+
+ Returns:
+ The filtered parameters with large fields removed.
+ """
+ excluded_keys = {"tools", "functions", "messages", "response_format"}
+ return {k: v for k, v in params.items() if k not in excluded_keys}
+
+
+def is_openai_data_block(
+ block: dict, filter_: Literal["image", "audio", "file"] | None = None
+) -> bool:
+ """Check whether a block contains multimodal data in OpenAI Chat Completions format.
+
+ Supports both data and ID-style blocks (e.g. `'file_data'` and `'file_id'`)
+
+ If additional keys are present, they are ignored / will not affect outcome as long
+ as the required keys are present and valid.
+
+ Args:
+ block: The content block to check.
+ filter_: If provided, only return True for blocks matching this specific type.
+ - "image": Only match image_url blocks
+ - "audio": Only match input_audio blocks
+ - "file": Only match file blocks
+ If `None`, match any valid OpenAI data block type. Note that this means that
+ if the block has a valid OpenAI data type but the filter_ is set to a
+ different type, this function will return False.
+
+ Returns:
+ `True` if the block is a valid OpenAI data block and matches the filter_
+ (if provided).
+
+ """
+ if block.get("type") == "image_url":
+ if filter_ is not None and filter_ != "image":
+ return False
+ if (
+ (set(block.keys()) <= {"type", "image_url", "detail"})
+ and (image_url := block.get("image_url"))
+ and isinstance(image_url, dict)
+ ):
+ url = image_url.get("url")
+ if isinstance(url, str):
+ # Required per OpenAI spec
+ return True
+ # Ignore `'detail'` since it's optional and specific to OpenAI
+
+ elif block.get("type") == "input_audio":
+ if filter_ is not None and filter_ != "audio":
+ return False
+ if (audio := block.get("input_audio")) and isinstance(audio, dict):
+ audio_data = audio.get("data")
+ audio_format = audio.get("format")
+ # Both required per OpenAI spec
+ if isinstance(audio_data, str) and isinstance(audio_format, str):
+ return True
+
+ elif block.get("type") == "file":
+ if filter_ is not None and filter_ != "file":
+ return False
+ if (file := block.get("file")) and isinstance(file, dict):
+ file_data = file.get("file_data")
+ file_id = file.get("file_id")
+ # Files can be either base64-encoded or pre-uploaded with an ID
+ if isinstance(file_data, str) or isinstance(file_id, str):
+ return True
+
+ else:
+ return False
+
+ # Has no `'type'` key
+ return False
+
+
+class ParsedDataUri(TypedDict):
+ source_type: Literal["base64"]
+ data: str
+ mime_type: str
+
+
+def _parse_data_uri(uri: str) -> ParsedDataUri | None:
+ """Parse a data URI into its components.
+
+ If parsing fails, return `None`. If either MIME type or data is missing, return
+ `None`.
+
+ Example:
+ ```python
+ data_uri = "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
+ parsed = _parse_data_uri(data_uri)
+
+ assert parsed == {
+ "source_type": "base64",
+ "mime_type": "image/jpeg",
+ "data": "/9j/4AAQSkZJRg...",
+ }
+ ```
+ """
+ regex = r"^data:(?P[^;]+);base64,(?P.+)$"
+ match = re.match(regex, uri)
+ if match is None:
+ return None
+
+ mime_type = match.group("mime_type")
+ data = match.group("data")
+ if not mime_type or not data:
+ return None
+
+ return {
+ "source_type": "base64",
+ "data": data,
+ "mime_type": mime_type,
+ }
+
+
+def _normalize_messages(
+ messages: Sequence["BaseMessage"],
+) -> list["BaseMessage"]:
+ """Normalize message formats to LangChain v1 standard content blocks.
+
+ Chat models already implement support for:
+ - Images in OpenAI Chat Completions format
+ These will be passed through unchanged
+ - LangChain v1 standard content blocks
+
+ This function extends support to:
+ - `[Audio](https://platform.openai.com/docs/api-reference/chat/create) and
+ `[file](https://platform.openai.com/docs/api-reference/files) data in OpenAI
+ Chat Completions format
+ - Images are technically supported but we expect chat models to handle them
+ directly; this may change in the future
+ - LangChain v0 standard content blocks for backward compatibility
+
+ !!! warning "Behavior changed in `langchain-core` 1.0.0"
+
+ In previous versions, this function returned messages in LangChain v0 format.
+ Now, it returns messages in LangChain v1 format, which upgraded chat models now
+ expect to receive when passing back in message history. For backward
+ compatibility, this function will convert v0 message content to v1 format.
+
+ ??? note "v0 Content Block Schemas"
+
+ `URLContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['image', 'audio', 'file'],
+ source_type: Literal['url'],
+ url: str,
+ }
+ ```
+
+ `Base64ContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['image', 'audio', 'file'],
+ source_type: Literal['base64'],
+ data: str,
+ }
+ ```
+
+ `IDContentBlock`:
+
+ (In practice, this was never used)
+
+ ```python
+ {
+ type: Literal["image", "audio", "file"],
+ source_type: Literal["id"],
+ id: str,
+ }
+ ```
+
+ `PlainTextContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['file'],
+ source_type: Literal['text'],
+ url: str,
+ }
+ ```
+
+ If a v1 message is passed in, it will be returned as-is, meaning it is safe to
+ always pass in v1 messages to this function for assurance.
+
+ For posterity, here are the OpenAI Chat Completions schemas we expect:
+
+ Chat Completions image. Can be URL-based or base64-encoded. Supports MIME types
+ png, jpeg/jpg, webp, static gif:
+ {
+ "type": Literal['image_url'],
+ "image_url": {
+ "url": Union["data:$MIME_TYPE;base64,$BASE64_ENCODED_IMAGE", "$IMAGE_URL"],
+ "detail": Literal['low', 'high', 'auto'] = 'auto', # Supported by OpenAI
+ }
+ }
+
+ Chat Completions audio:
+ {
+ "type": Literal['input_audio'],
+ "input_audio": {
+ "format": Literal['wav', 'mp3'],
+ "data": str = "$BASE64_ENCODED_AUDIO",
+ },
+ }
+
+ Chat Completions files: either base64 or pre-uploaded file ID
+ {
+ "type": Literal['file'],
+ "file": Union[
+ {
+ "filename": str | None = "$FILENAME",
+ "file_data": str = "$BASE64_ENCODED_FILE",
+ },
+ {
+ "file_id": str = "$FILE_ID", # For pre-uploaded files to OpenAI
+ },
+ ],
+ }
+
+ """
+ from langchain_core.messages.block_translators.langchain_v0 import ( # noqa: PLC0415
+ _convert_legacy_v0_content_block_to_v1,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _convert_openai_format_to_data_block,
+ )
+
+ formatted_messages = []
+ for message in messages:
+ # We preserve input messages - the caller may reuse them elsewhere and expects
+ # them to remain unchanged. We only create a copy if we need to translate.
+ formatted_message = message
+
+ if isinstance(message.content, list):
+ for idx, block in enumerate(message.content):
+ # OpenAI Chat Completions multimodal data blocks to v1 standard
+ if (
+ isinstance(block, dict)
+ and block.get("type") in {"input_audio", "file"}
+ # Discriminate between OpenAI/LC format since they share `'type'`
+ and is_openai_data_block(block)
+ ):
+ formatted_message = _ensure_message_copy(message, formatted_message)
+
+ converted_block = _convert_openai_format_to_data_block(block)
+ _update_content_block(formatted_message, idx, converted_block)
+
+ # Convert multimodal LangChain v0 to v1 standard content blocks
+ elif (
+ isinstance(block, dict)
+ and block.get("type")
+ in {
+ "image",
+ "audio",
+ "file",
+ }
+ and block.get("source_type") # v1 doesn't have `source_type`
+ in {
+ "url",
+ "base64",
+ "id",
+ "text",
+ }
+ ):
+ formatted_message = _ensure_message_copy(message, formatted_message)
+
+ converted_block = _convert_legacy_v0_content_block_to_v1(block)
+ _update_content_block(formatted_message, idx, converted_block)
+ continue
+
+ # else, pass through blocks that look like they have v1 format unchanged
+
+ formatted_messages.append(formatted_message)
+
+ return formatted_messages
+
+
+T = TypeVar("T", bound="BaseMessage")
+
+
+def _ensure_message_copy(message: T, formatted_message: T) -> T:
+ """Create a copy of the message if it hasn't been copied yet."""
+ if formatted_message is message:
+ formatted_message = message.model_copy()
+ # Shallow-copy content list to allow modifications
+ formatted_message.content = list(formatted_message.content)
+ return formatted_message
+
+
+def _update_content_block(
+ formatted_message: "BaseMessage", idx: int, new_block: ContentBlock | dict
+) -> None:
+ """Update a content block at the given index, handling type issues."""
+ # Type ignore needed because:
+ # - `BaseMessage.content` is typed as `Union[str, list[Union[str, dict]]]`
+ # - When content is str, indexing fails (index error)
+ # - When content is list, the items are `Union[str, dict]` but we're assigning
+ # `Union[ContentBlock, dict]` where ContentBlock is richer than dict
+ # - This is safe because we only call this when we've verified content is a list and
+ # we're doing content block conversions
+ formatted_message.content[idx] = new_block # type: ignore[index, assignment]
+
+
+def _update_message_content_to_blocks(message: T, output_version: str) -> T:
+ return message.model_copy(
+ update={
+ "content": message.content_blocks,
+ "response_metadata": {
+ **message.response_metadata,
+ "output_version": output_version,
+ },
+ }
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/base.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..570076290e09ffbb1cae52811f6cc0231b951217
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/base.py
@@ -0,0 +1,391 @@
+"""Base language models class."""
+
+from __future__ import annotations
+
+import warnings
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Mapping, Sequence
+from functools import cache
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypeAlias,
+ TypeVar,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+from typing_extensions import TypedDict, override
+
+from langchain_core.caches import BaseCache # noqa: TC001
+from langchain_core.callbacks import Callbacks # noqa: TC001
+from langchain_core.globals import get_verbose
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ MessageLikeRepresentation,
+ get_buffer_string,
+)
+from langchain_core.prompt_values import (
+ ChatPromptValueConcrete,
+ PromptValue,
+ StringPromptValue,
+)
+from langchain_core.runnables import Runnable, RunnableSerializable
+
+if TYPE_CHECKING:
+ from langchain_core.outputs import LLMResult
+
+try:
+ from transformers import GPT2TokenizerFast # type: ignore[import-not-found]
+
+ _HAS_TRANSFORMERS = True
+except ImportError:
+ _HAS_TRANSFORMERS = False
+
+
+class LangSmithParams(TypedDict, total=False):
+ """LangSmith parameters for tracing."""
+
+ ls_provider: str
+ """Provider of the model."""
+
+ ls_model_name: str
+ """Name of the model."""
+
+ ls_model_type: Literal["chat", "llm"]
+ """Type of the model.
+
+ Should be `'chat'` or `'llm'`.
+ """
+
+ ls_temperature: float | None
+ """Temperature for generation."""
+
+ ls_max_tokens: int | None
+ """Max tokens for generation."""
+
+ ls_stop: list[str] | None
+ """Stop words for generation."""
+ ls_integration: str
+ """Integration that created the trace."""
+
+
+@cache # Cache the tokenizer
+def get_tokenizer() -> Any:
+ """Get a GPT-2 tokenizer instance.
+
+ This function is cached to avoid re-loading the tokenizer every time it is called.
+
+ Raises:
+ ImportError: If the transformers package is not installed.
+
+ Returns:
+ The GPT-2 tokenizer instance.
+
+ """
+ if not _HAS_TRANSFORMERS:
+ msg = (
+ "Could not import transformers python package. "
+ "This is needed in order to calculate get_token_ids. "
+ "Please install it with `pip install transformers`."
+ )
+ raise ImportError(msg)
+ # create a GPT-2 tokenizer instance
+ return GPT2TokenizerFast.from_pretrained("gpt2")
+
+
+_GPT2_TOKENIZER_WARNED = False
+
+
+def _get_token_ids_default_method(text: str) -> list[int]:
+ """Encode the text into token IDs using the fallback GPT-2 tokenizer."""
+ global _GPT2_TOKENIZER_WARNED # noqa: PLW0603
+ if not _GPT2_TOKENIZER_WARNED:
+ warnings.warn(
+ "Using fallback GPT-2 tokenizer for token counting. "
+ "Token counts may be inaccurate for non-GPT-2 models. "
+ "For accurate counts, use a model-specific method if available.",
+ stacklevel=3,
+ )
+ _GPT2_TOKENIZER_WARNED = True
+
+ tokenizer = get_tokenizer()
+
+ # Pass verbose=False to suppress the "Token indices sequence length is longer than
+ # the specified maximum sequence length" warning from HuggingFace. This warning is
+ # about GPT-2's 1024 token context limit, but we're only using the tokenizer for
+ # counting, not for model input.
+ return cast("list[int]", tokenizer.encode(text, verbose=False))
+
+
+LanguageModelInput = PromptValue | str | Sequence[MessageLikeRepresentation]
+"""Input to a language model."""
+
+LanguageModelOutput = BaseMessage | str
+"""Output from a language model."""
+
+LanguageModelLike = Runnable[LanguageModelInput, LanguageModelOutput]
+"""Input/output interface for a language model."""
+
+LanguageModelOutputVar = TypeVar("LanguageModelOutputVar", AIMessage, str)
+"""Type variable for the output of a language model."""
+
+
+def _get_verbosity() -> bool:
+ return get_verbose()
+
+
+class BaseLanguageModel(
+ RunnableSerializable[LanguageModelInput, LanguageModelOutputVar], ABC
+):
+ """Abstract base class for interfacing with language models.
+
+ All language model wrappers inherited from `BaseLanguageModel`.
+
+ """
+
+ cache: BaseCache | bool | None = Field(default=None, exclude=True)
+ """Whether to cache the response.
+
+ * If `True`, will use the global cache.
+ * If `False`, will not use a cache
+ * If `None`, will use the global cache if it's set, otherwise no cache.
+ * If instance of `BaseCache`, will use the provided cache.
+
+ Caching is not currently supported for streaming methods of models.
+ """
+
+ verbose: bool = Field(default_factory=_get_verbosity, exclude=True, repr=False)
+ """Whether to print out response text."""
+
+ callbacks: Callbacks = Field(default=None, exclude=True)
+ """Callbacks to add to the run trace."""
+
+ tags: list[str] | None = Field(default=None, exclude=True)
+ """Tags to add to the run trace."""
+
+ metadata: dict[str, Any] | None = Field(default=None, exclude=True)
+ """Metadata to add to the run trace."""
+
+ custom_get_token_ids: Callable[[str], list[int]] | None = Field(
+ default=None, exclude=True
+ )
+ """Optional encoder to use for counting tokens."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @field_validator("verbose", mode="before")
+ def set_verbose(cls, verbose: bool | None) -> bool: # noqa: FBT001
+ """If verbose is `None`, set it.
+
+ This allows users to pass in `None` as verbose to access the global setting.
+
+ Args:
+ verbose: The verbosity setting to use.
+
+ Returns:
+ The verbosity setting to use.
+
+ """
+ if verbose is None:
+ return _get_verbosity()
+ return verbose
+
+ @property
+ @override
+ def InputType(self) -> TypeAlias:
+ """Get the input type for this `Runnable`."""
+ # This is a version of LanguageModelInput which replaces the abstract
+ # base class BaseMessage with a union of its subclasses, which makes
+ # for a much better schema.
+ return str | StringPromptValue | ChatPromptValueConcrete | list[AnyMessage]
+
+ @abstractmethod
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to the model and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of `PromptValue` objects.
+
+ A `PromptValue` is an object that can be converted to match the format
+ of any language model (string for pure text generation models and
+ `BaseMessage` objects for chat models).
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
+
+ """
+
+ @abstractmethod
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of `PromptValue` objects.
+
+ A `PromptValue` is an object that can be converted to match the format
+ of any language model (string for pure text generation models and
+ `BaseMessage` objects for chat models).
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
+
+ """
+
+ def with_structured_output(
+ self, schema: dict | type, **kwargs: Any
+ ) -> Runnable[LanguageModelInput, dict | BaseModel]:
+ """Not implemented on this class."""
+ # Implement this on child class if there is a way of steering the model to
+ # generate responses that match a given schema.
+ raise NotImplementedError
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None, # noqa: ARG002
+ **kwargs: Any, # noqa: ARG002
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ return LangSmithParams()
+
+ def _get_ls_params_with_defaults(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Wrap _get_ls_params to include any additional default parameters."""
+ return self._get_ls_params(stop=stop, **kwargs)
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ return self.lc_attributes
+
+ def get_token_ids(self, text: str) -> list[int]:
+ """Return the ordered IDs of the tokens in a text.
+
+ Args:
+ text: The string input to tokenize.
+
+ Returns:
+ A list of IDs corresponding to the tokens in the text, in order they occur
+ in the text.
+ """
+ if self.custom_get_token_ids is not None:
+ return self.custom_get_token_ids(text)
+ return _get_token_ids_default_method(text)
+
+ def get_num_tokens(self, text: str) -> int:
+ """Get the number of tokens present in the text.
+
+ Useful for checking if an input fits in a model's context window.
+
+ This should be overridden by model-specific implementations to provide accurate
+ token counts via model-specific tokenizers.
+
+ Args:
+ text: The string input to tokenize.
+
+ Returns:
+ The integer number of tokens in the text.
+
+ """
+ return len(self.get_token_ids(text))
+
+ def get_num_tokens_from_messages(
+ self,
+ messages: list[BaseMessage],
+ tools: Sequence | None = None,
+ ) -> int:
+ """Get the number of tokens in the messages.
+
+ Useful for checking if an input fits in a model's context window.
+
+ This should be overridden by model-specific implementations to provide accurate
+ token counts via model-specific tokenizers.
+
+ !!! note
+
+ * The base implementation of `get_num_tokens_from_messages` ignores tool
+ schemas.
+ * The base implementation of `get_num_tokens_from_messages` adds additional
+ prefixes to messages in represent user roles, which will add to the
+ overall token count. Model-specific implementations may choose to
+ handle this differently.
+
+ Args:
+ messages: The message inputs to tokenize.
+ tools: If provided, sequence of dict, `BaseModel`, function, or
+ `BaseTool` objects to be converted to tool schemas.
+
+ Returns:
+ The sum of the number of tokens across the messages.
+
+ """
+ if tools is not None:
+ warnings.warn(
+ "Counting tokens in tool schemas is not yet supported. Ignoring tools.",
+ stacklevel=2,
+ )
+ return sum(self.get_num_tokens(get_buffer_string([m])) for m in messages)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_model_stream.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_model_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b25a66fd2a4f943b4ae95a014ae3bcc8a236e96
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_model_stream.py
@@ -0,0 +1,1428 @@
+"""Per-message streaming objects for content-block protocol events.
+
+`ChatModelStream` is the synchronous variant returned by
+`BaseChatModel.stream_events(version="v3")`. `AsyncChatModelStream` is the
+asynchronous variant returned by `BaseChatModel.astream_events(version="v3")`.
+
+Both expose typed projection properties (`.text`, `.reasoning`,
+`.tool_calls`, `.usage`, `.output`) that accumulate protocol
+events as they arrive. Projections can be iterated for deltas or
+drained for the final accumulated value.
+
+Raw protocol events are also available via direct iteration on the
+stream object (replay-buffer semantics — multiple independent
+consumers supported).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from typing import TYPE_CHECKING, Any, cast
+
+from langchain_core.language_models._compat_bridge import finalize_tool_call_chunk
+from langchain_core.messages import AIMessage
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable, Generator, Iterator, Mapping
+
+ from langchain_protocol.protocol import (
+ ContentBlockDeltaData,
+ ContentBlockFinishData,
+ FinalizedContentBlock,
+ InvalidToolCall,
+ MessageFinishData,
+ MessageMetadata,
+ MessagesData,
+ MessageStartData,
+ ReasoningContentBlock,
+ ServerToolCallChunk,
+ TextContentBlock,
+ ToolCall,
+ ToolCallChunk,
+ UsageInfo,
+ )
+ from typing_extensions import Self
+
+
+# ---------------------------------------------------------------------------
+# Tool-call chunk helpers (shared by tool_call_chunk and server_tool_call_chunk)
+# ---------------------------------------------------------------------------
+
+
+def _merge_chunk_into_store(
+ store: dict[int, dict[str, Any]],
+ idx: int,
+ block: dict[str, Any],
+) -> None:
+ """Merge a tool-call-chunk delta: sticky id/name, concat args."""
+ existing = store.get(idx, {})
+ if block.get("id") and "id" not in existing:
+ existing["id"] = block["id"]
+ if block.get("name") and "name" not in existing:
+ existing["name"] = block["name"]
+ existing["args"] = existing.get("args", "") + (block.get("args") or "")
+ store[idx] = existing
+
+
+def _merge_block_delta_into_store(
+ store: dict[int, dict[str, Any]],
+ idx: int,
+ fields: dict[str, Any],
+) -> None:
+ """Shallow-merge a block-delta snapshot into an indexed chunk store."""
+ existing = store.get(idx, {})
+ for key, value in fields.items():
+ if value is not None:
+ existing[key] = value
+ store[idx] = existing
+
+
+def _event_content_block(data: Mapping[str, Any]) -> dict[str, Any] | None:
+ """Return start/finish content, tolerating the pre-delta field name."""
+ block = data.get("content") or data.get("content_block")
+ return block if isinstance(block, dict) else None
+
+
+def _legacy_block_to_delta(block: Mapping[str, Any]) -> dict[str, Any]:
+ """Convert the old content-block delta shape to an explicit delta."""
+ btype = block.get("type")
+ if btype == "text":
+ return {"type": "text-delta", "text": block.get("text", "")}
+ if btype == "reasoning":
+ return {
+ "type": "reasoning-delta",
+ "reasoning": block.get("reasoning", ""),
+ }
+ if "data" in block:
+ delta = {"type": "data-delta", "data": block.get("data", "")}
+ if block.get("encoding") == "base64":
+ delta["encoding"] = "base64"
+ return delta
+ return {"type": "legacy-block-delta", "fields": block}
+
+
+def _event_delta(data: Mapping[str, Any]) -> dict[str, Any] | None:
+ """Return an explicit delta, converting legacy content-block deltas."""
+ delta = data.get("delta")
+ if isinstance(delta, dict):
+ return delta
+ block = data.get("content_block")
+ if isinstance(block, dict):
+ return _legacy_block_to_delta(block)
+ return None
+
+
+def _sweep_chunk_store(
+ store: dict[int, dict[str, Any]],
+ *,
+ finalized_type: str,
+ finalized_blocks: dict[int, FinalizedContentBlock],
+ tool_calls_acc: list[ToolCall] | None,
+ invalid_acc: list[InvalidToolCall],
+) -> None:
+ """Parse each unswept chunk's `args`; record as `finalized_type` or invalid.
+
+ `tool_calls_acc` is only populated when `finalized_type == "tool_call"`
+ (server-side calls don't surface through `.tool_calls`).
+
+ Deliberately does not backfill `index` onto finalized tool-call blocks:
+ matches v1 (`AIMessage.init_tool_calls` drops `index` when substituting
+ `tool_call_chunk` → `tool_call`) and prevents `merge_lists` from
+ re-merging further chunks into an already-parsed args dict.
+ """
+ for idx in sorted(store):
+ chunk = store[idx]
+ # Carry over any non-finalize-rewritten fields the chunk collected
+ # (e.g., `extras`). `_merge_chunk_into_store` only populates
+ # `id` / `name` / `args`, so this is empty in practice today;
+ # future provider-specific fields would flow through here.
+ extras = {
+ k: v
+ for k, v in chunk.items()
+ if k not in ("type", "id", "name", "args") and v is not None
+ }
+ final_block = finalize_tool_call_chunk(
+ raw_args=chunk.get("args"),
+ id_=chunk.get("id"),
+ name=chunk.get("name"),
+ extras=extras,
+ finalized_type=finalized_type,
+ )
+ if final_block["type"] == "invalid_tool_call":
+ invalid_acc.append(final_block)
+ elif tool_calls_acc is not None and finalized_type == "tool_call":
+ tool_calls_acc.append(cast("ToolCall", final_block))
+ finalized_blocks[idx] = final_block
+ store.clear()
+
+
+# ---------------------------------------------------------------------------
+# Projection base — shared producer API
+# ---------------------------------------------------------------------------
+
+
+class _ProjectionBase:
+ """Shared state and producer API for sync and async projections.
+
+ The `push` / `complete` / `fail` methods are the producer-side
+ API — called by the stream as events arrive. Subclasses add the
+ consumer protocol (sync iteration or async iteration + await).
+
+ `done` and `error` are safe read-only views of the terminal state
+ for iterators and other siblings that need to observe lifecycle
+ without reaching into the underlying fields.
+ """
+
+ __slots__ = ("_deltas", "_done", "_error", "_final_set", "_final_value")
+
+ def __init__(self) -> None:
+ """Initialize empty projection state."""
+ self._deltas: list[Any] = []
+ self._final_value: Any = None
+ self._final_set: bool = False
+ self._done: bool = False
+ self._error: BaseException | None = None
+
+ @property
+ def done(self) -> bool:
+ """Whether the projection has finished (successfully or via error)."""
+ return self._done
+
+ @property
+ def error(self) -> BaseException | None:
+ """The terminal error, if any."""
+ return self._error
+
+ def push(self, delta: Any) -> None:
+ """Append a delta value. Producer-side API."""
+ self._deltas.append(delta)
+
+ def complete(self, final_value: Any) -> None:
+ """Set the final accumulated value and mark as done. Producer-side API."""
+ self._final_value = final_value
+ self._final_set = True
+ self._done = True
+
+ def fail(self, error: BaseException) -> None:
+ """Mark as errored. Producer-side API."""
+ self._error = error
+ self._done = True
+
+
+# ---------------------------------------------------------------------------
+# Sync projections
+# ---------------------------------------------------------------------------
+
+
+class SyncProjection(_ProjectionBase):
+ """Sync iterable of deltas with pull-based backpressure.
+
+ Follows the same `_request_more` convention as langgraph's
+ `EventLog`: when the cursor catches up to the buffer and the
+ projection is not done, it calls `_request_more()` to pull more
+ events from the producer.
+
+ Each call to `__iter__` creates a new cursor at position 0.
+ Multiple iterators replay all deltas from the start.
+ """
+
+ __slots__ = ("_ensure_started", "_request_more")
+
+ def __init__(self) -> None:
+ """Initialize with no pull callback."""
+ super().__init__()
+ self._ensure_started: Callable[[], None] | None = None
+ self._request_more: Callable[[], bool] | None = None
+
+ def set_start(self, cb: Callable[[], None] | None) -> None:
+ """Install a lazy-start callback invoked on first consumption."""
+ self._ensure_started = cb
+
+ def set_request_more(self, cb: Callable[[], bool] | None) -> None:
+ """Install the pull callback the iterator uses to drain the source."""
+ self._request_more = cb
+
+ def __iter__(self) -> Iterator[Any]:
+ """Yield deltas, pulling via `_request_more` when caught up."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ cursor = 0
+ while True:
+ if cursor < len(self._deltas):
+ yield self._deltas[cursor]
+ cursor += 1
+ elif self._error is not None:
+ raise self._error
+ elif self._done:
+ return
+ elif self._request_more is not None:
+ while cursor >= len(self._deltas) and not self._done:
+ if not self._request_more():
+ break
+ if cursor >= len(self._deltas):
+ if self._error is not None:
+ raise self._error
+ return
+ else:
+ return
+
+ def get(self) -> Any:
+ """Drain via `_request_more` and return the final value."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ if not self._done and self._request_more is not None:
+ while not self._done:
+ if not self._request_more():
+ break
+ if self._error is not None:
+ raise self._error
+ return self._final_value
+
+
+class SyncTextProjection(SyncProjection):
+ """String-specialized sync projection.
+
+ Adds `__str__`, `__bool__`, `__repr__` for ergonomic use with
+ `.text` and `.reasoning` projections.
+ """
+
+ __slots__ = ()
+
+ def __str__(self) -> str:
+ """Drain and return the full accumulated string."""
+ val = self.get()
+ return val if val is not None else ""
+
+ def __bool__(self) -> bool:
+ """Return whether any deltas have been pushed."""
+ return len(self._deltas) > 0
+
+ def __repr__(self) -> str:
+ """Return repr of the accumulated text so far."""
+ if self._final_set:
+ return repr(self._final_value)
+ return repr("".join(self._deltas))
+
+
+# ---------------------------------------------------------------------------
+# Async projection
+# ---------------------------------------------------------------------------
+
+
+class AsyncProjection(_ProjectionBase):
+ """Async iterable of deltas that is also awaitable for the final value.
+
+ Uses an `asyncio.Event` to notify consumers of state changes. Each
+ waiter — the awaitable (`__await__`) and each async iterator cursor
+ — shares the event and re-checks its own condition on wake. The event
+ is cleared before a waiter awaits, so stale "something happened"
+ signals don't cause spin loops.
+
+ This is single-loop only — producers and consumers must share an
+ event loop. If cross-thread wake is ever required, revert to a
+ list-of-futures pattern with `call_soon_threadsafe`.
+ """
+
+ __slots__ = ("_arequest_more", "_ensure_started", "_event")
+
+ def __init__(self) -> None:
+ """Initialize with an un-set event and no pump callback."""
+ super().__init__()
+ self._event = asyncio.Event()
+ self._arequest_more: Callable[[], Awaitable[bool]] | None = None
+ self._ensure_started: Callable[[], Awaitable[None]] | None = None
+
+ def set_start(self, cb: Callable[[], Awaitable[None]] | None) -> None:
+ """Install a lazy-start callback invoked on first consumption."""
+ self._ensure_started = cb
+
+ def set_arequest_more(self, cb: Callable[[], Awaitable[bool]] | None) -> None:
+ """Wire the async pull callback iterators use to drive the source.
+
+ Mirrors `SyncProjection.set_request_more`. Under caller-driven
+ streaming, consumers call this callback when their buffer is
+ empty so that the owning graph advances one step.
+
+ Args:
+ cb: Async no-arg callable returning `True` when a new event
+ was produced, `False` when the source is exhausted. Pass
+ `None` to unwire.
+ """
+ self._arequest_more = cb
+
+ def push(self, delta: Any) -> None:
+ """Append a delta and notify waiters."""
+ super().push(delta)
+ self._event.set()
+
+ def complete(self, final_value: Any) -> None:
+ """Set the final value, mark done, and notify waiters."""
+ super().complete(final_value)
+ self._event.set()
+
+ def fail(self, error: BaseException) -> None:
+ """Mark errored and notify waiters."""
+ super().fail(error)
+ self._event.set()
+
+ # -- Async iterable (yields deltas) ------------------------------------
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Return an async iterator over deltas."""
+ return _AsyncProjectionIterator(self)
+
+ # -- Awaitable (returns final value) -----------------------------------
+
+ def __await__(self) -> Generator[Any, None, Any]:
+ """Await the final accumulated value."""
+ return self._await_impl().__await__()
+
+ async def _await_impl(self) -> Any:
+ """Wait until the final value is set and return it.
+
+ When a caller-driven pump is wired via `set_arequest_more`, drive
+ it instead of blocking on `self._event`; otherwise fall back to
+ the event (used by tests that dispatch manually).
+ """
+ if self._ensure_started is not None:
+ await self._ensure_started()
+ while not self._final_set:
+ if self._error is not None:
+ raise self._error
+ if self._arequest_more is not None:
+ if not await self._arequest_more() and not self._final_set:
+ # Pump exhausted without completing this projection —
+ # nothing more will arrive. Return current state and
+ # let callers observe the missing final via the
+ # returned None / unset error.
+ break
+ else:
+ self._event.clear()
+ await self._event.wait()
+ if self._error is not None:
+ raise self._error
+ return self._final_value
+
+
+class _AsyncProjectionIterator:
+ """Async iterator over an `AsyncProjection`'s deltas."""
+
+ __slots__ = ("_offset", "_proj")
+
+ def __init__(self, proj: AsyncProjection) -> None:
+ """Initialize cursor at position 0."""
+ self._proj = proj
+ self._offset = 0
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Return self for the async iteration protocol."""
+ return self
+
+ async def __anext__(self) -> Any:
+ """Return the next delta, awaiting if necessary.
+
+ When the projection has an `_arequest_more` pump wired, drain it
+ in an inner loop (mirrors `SyncProjection.__iter__`) until this
+ cursor advances or the pump reports exhaustion. Without a pump,
+ fall back to waiting on the shared event.
+ """
+ proj = self._proj
+ if proj._ensure_started is not None: # noqa: SLF001
+ await proj._ensure_started() # noqa: SLF001
+ while True:
+ # Direct access to the projection's internal list/event is
+ # intentional — the iterator is the projection's sidekick and
+ # depends on reading the shared buffer by cursor.
+ if self._offset < len(proj._deltas): # noqa: SLF001
+ item = proj._deltas[self._offset] # noqa: SLF001
+ self._offset += 1
+ return item
+ if proj.error is not None:
+ raise proj.error
+ if proj.done:
+ raise StopAsyncIteration
+ if proj._arequest_more is not None: # noqa: SLF001
+ # Caller-driven: drive the producer. Pump may land new
+ # deltas for a sibling projection — loop until our cursor
+ # advances, the projection terminates, or the pump is
+ # exhausted.
+ while (
+ self._offset >= len(proj._deltas) # noqa: SLF001
+ and not proj.done
+ ):
+ if not await proj._arequest_more(): # noqa: SLF001
+ break
+ if (
+ self._offset >= len(proj._deltas) # noqa: SLF001
+ and not proj.done
+ ):
+ if proj.error is not None:
+ raise proj.error
+ raise StopAsyncIteration
+ else:
+ proj._event.clear() # noqa: SLF001
+ await proj._event.wait() # noqa: SLF001
+
+
+# ---------------------------------------------------------------------------
+# Sync stream
+# ---------------------------------------------------------------------------
+
+
+class _ChatModelStreamBase:
+ """Shared state and event dispatch for chat-model streams.
+
+ Holds accumulated protocol state (text, reasoning, tool calls,
+ usage, metadata) and the event-dispatch machinery that drives the
+ typed projections. `ChatModelStream` (sync) and
+ `AsyncChatModelStream` (async) inherit from this base and add the
+ projection types and consumer APIs for their flavor.
+ """
+
+ # Projection instances — concrete subclasses create them as sync or
+ # async variants in their own __init__ after calling super().
+ _text_proj: _ProjectionBase
+ _reasoning_proj: _ProjectionBase
+ _tool_calls_proj: _ProjectionBase
+
+ def __init__(
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ self._namespace = namespace or []
+ self._node = node
+ self._message_id = message_id
+
+ # Accumulated state
+ self._text_acc: str = ""
+ self._reasoning_acc: str = ""
+ # Per-block text / reasoning storage keyed by wire index. Used to
+ # populate the finalized block payload without cross-contaminating
+ # other blocks of the same type in the same message. Without
+ # per-block storage the message-wide accumulator would bleed
+ # earlier block text into later finalized blocks.
+ self._text_per_block: dict[int, str] = {}
+ self._reasoning_per_block: dict[int, str] = {}
+ self._tool_call_chunks: dict[int, dict[str, Any]] = {}
+ self._tool_calls_acc: list[ToolCall] = []
+ self._invalid_tool_calls_acc: list[InvalidToolCall] = []
+ self._server_tool_call_chunks: dict[int, dict[str, Any]] = {}
+ # Ordered snapshot of every finalized block, keyed by event index.
+ # Single source of truth for .output.content. Typed accumulators
+ # (text/reasoning/tool_calls/invalid_tool_calls) continue to serve
+ # the public projections.
+ self._blocks: dict[int, FinalizedContentBlock] = {}
+ self._usage_value: UsageInfo | None = None
+ self._start_metadata: MessageMetadata | None = None
+ self._finish_metadata: dict[str, Any] | None = None
+ self._done: bool = False
+ self._error: BaseException | None = None
+ self._output_message: AIMessage | None = None
+
+ # Raw event replay buffer
+ self._events: list[MessagesData] = []
+
+ # -- Common properties ------------------------------------------------
+
+ @property
+ def namespace(self) -> list[str]:
+ """Graph namespace path for this message."""
+ return self._namespace
+
+ @property
+ def node(self) -> str | None:
+ """Graph node that produced this message."""
+ return self._node
+
+ @property
+ def message_id(self) -> str | None:
+ """Stable message identifier."""
+ return self._message_id
+
+ def set_message_id(self, message_id: str) -> None:
+ """Assign the stable message identifier once the run starts.
+
+ Called by the stream driver (`stream_events(version="v3")` /
+ `astream_events(version="v3")`) after `on_chat_model_start` produces a run
+ id. Not intended for end-user code.
+ """
+ self._message_id = message_id
+
+ @property
+ def done(self) -> bool:
+ """Whether the stream has finished."""
+ return self._done
+
+ @property
+ def has_events(self) -> bool:
+ """Whether any protocol events have been recorded."""
+ return bool(self._events)
+
+ @property
+ def output_message(self) -> AIMessage | None:
+ """The assembled message if the stream has finished, else `None`.
+
+ Unlike `ChatModelStream.output` (which blocks until the stream
+ finishes), this never pumps, blocks, or raises. Intended for the
+ stream driver (`stream_events(version="v3")` and its async
+ equivalent) to check whether the stream produced a message before
+ firing `on_llm_end` callbacks.
+ """
+ return self._output_message
+
+ # -- Event ingestion (public) ------------------------------------------
+
+ def dispatch(self, event: Mapping[str, Any]) -> None:
+ """Route a protocol event to the appropriate internal handler.
+
+ Public entry point for feeding events into the stream. Called by
+ the stream driver (the `stream_events(version="v3")` pump and its
+ async equivalent) and by any observer or test that needs to
+ inject protocol events.
+ """
+ self._record_event(event)
+ event_type = event.get("event")
+ if event_type == "message-start":
+ self._push_message_start(cast("MessageStartData", event))
+ elif event_type == "content-block-delta":
+ self._push_content_block_delta(cast("ContentBlockDeltaData", event))
+ elif event_type == "content-block-finish":
+ self._push_content_block_finish(cast("ContentBlockFinishData", event))
+ elif event_type == "message-finish":
+ self._finish(cast("MessageFinishData", event))
+ elif event_type == "error":
+ self.fail(RuntimeError(event.get("message", "Unknown error")))
+ # content-block-start is informational — no accumulation needed
+
+ # -- Internal push API (called by dispatch) ----------------------------
+
+ def _record_event(self, event: Mapping[str, Any]) -> None:
+ """Append a raw event to the replay buffer."""
+ self._events.append(cast("MessagesData", event))
+
+ def _push_message_start(self, data: MessageStartData) -> None:
+ """Process a `message-start` event."""
+ self._start_metadata = data.get("metadata")
+ message_id = data.get("id")
+ if message_id:
+ self._message_id = message_id
+
+ def _push_content_block_delta(self, data: ContentBlockDeltaData) -> None:
+ """Process a `content-block-delta` event."""
+ delta = _event_delta(data)
+ if delta is None:
+ return
+ event_idx = data.get("index")
+ dtype = delta.get("type", "")
+
+ if dtype == "text-delta":
+ delta_text = delta.get("text", "")
+ if delta_text:
+ self._text_acc += delta_text
+ if event_idx is not None:
+ self._text_per_block[event_idx] = (
+ self._text_per_block.get(event_idx, "") + delta_text
+ )
+ self._text_proj.push(delta_text)
+ elif dtype == "reasoning-delta":
+ delta_r = delta.get("reasoning", "")
+ if delta_r:
+ self._reasoning_acc += delta_r
+ if event_idx is not None:
+ self._reasoning_per_block[event_idx] = (
+ self._reasoning_per_block.get(event_idx, "") + delta_r
+ )
+ self._reasoning_proj.push(delta_r)
+ elif dtype == "block-delta":
+ fields = delta.get("fields")
+ if not isinstance(fields, dict):
+ return
+ btype = fields.get("type", "")
+ if btype == "tool_call_chunk":
+ tcc = cast("ToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_block_delta_into_store(self._tool_call_chunks, idx, dict(tcc))
+ chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(chunk_block)
+ elif btype == "server_tool_call_chunk":
+ stcc = cast("ServerToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = len(self._server_tool_call_chunks)
+ _merge_block_delta_into_store(
+ self._server_tool_call_chunks,
+ idx,
+ dict(stcc),
+ )
+ elif dtype == "legacy-block-delta":
+ fields = delta.get("fields")
+ if not isinstance(fields, dict):
+ return
+ btype = fields.get("type", "")
+ if btype == "tool_call_chunk":
+ tcc = cast("ToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))
+ legacy_chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ legacy_chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(legacy_chunk_block)
+ elif btype == "server_tool_call_chunk":
+ stcc = cast("ServerToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = len(self._server_tool_call_chunks)
+ _merge_chunk_into_store(
+ self._server_tool_call_chunks,
+ idx,
+ dict(stcc),
+ )
+ elif dtype == "data-delta":
+ # Binary/modal payload deltas are reflected in the final
+ # content-block finish event; there is no dedicated projection.
+ return
+ else:
+ # Transitional legacy path for old `content_block` deltas that
+ # should not be reachable after `_event_delta` conversion, kept
+ # here for custom in-tree test fixtures or third-party emitters.
+ block = data.get("content_block")
+ if not isinstance(block, dict):
+ return
+ btype = block.get("type", "")
+ if btype != "tool_call_chunk":
+ return
+ tcc = cast("ToolCallChunk", block)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))
+ fallback_chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ fallback_chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(fallback_chunk_block)
+
+ def _resolve_block_text(self, idx: int | None, full_text: str) -> str:
+ """Return authoritative text for a single text block at `idx`.
+
+ Prefers per-block delta accumulation; reconciles with the finish
+ event's `full_text` when the provider emits authoritative text
+ that differs from what the deltas built up.
+
+ Does not mutate `self._text_acc` (the delta-sum accumulator) —
+ the message-wide projection value is derived from per-block
+ storage at `_finish` time, so reconciliation remains correct
+ regardless of finish ordering across blocks.
+ """
+ if idx is None:
+ # No wire index — legacy behavior: use the message-wide
+ # accumulator. Preserved for pre-index semantics; not
+ # exercised by the compat bridge or any in-tree provider.
+ if full_text and full_text != self._text_acc:
+ self._text_acc = full_text
+ return self._text_acc
+ existing = self._text_per_block.get(idx, "")
+ if full_text and full_text != existing:
+ if not existing:
+ # No deltas arrived for this block — surface the full
+ # text as a single delta so the stream projection
+ # reflects it.
+ self._text_acc += full_text
+ self._text_proj.push(full_text)
+ elif full_text.startswith(existing):
+ # Authoritative text extends the partial deltas — emit
+ # the tail so delta consumers see the completion.
+ tail = full_text[len(existing) :]
+ self._text_acc += tail
+ self._text_proj.push(tail)
+ # else: authoritative text replaces the partial deltas
+ # entirely. No corrective delta is emitted (semantics
+ # would be ambiguous mid-stream). `_text_acc` is not
+ # spliced — the final value is computed from per-block
+ # storage at `_finish`, so this remains correct even when
+ # other blocks have added to `_text_acc` in between.
+ self._text_per_block[idx] = full_text
+ return self._text_per_block.get(idx, "")
+
+ def _resolve_block_reasoning(self, idx: int | None, full_r: str) -> str:
+ """Return authoritative reasoning text for a single block at `idx`.
+
+ Mirrors `_resolve_block_text` for the reasoning projection.
+ """
+ if idx is None:
+ if full_r and full_r != self._reasoning_acc:
+ self._reasoning_acc = full_r
+ return self._reasoning_acc
+ existing = self._reasoning_per_block.get(idx, "")
+ if full_r and full_r != existing:
+ if not existing:
+ self._reasoning_acc += full_r
+ self._reasoning_proj.push(full_r)
+ elif full_r.startswith(existing):
+ tail = full_r[len(existing) :]
+ self._reasoning_acc += tail
+ self._reasoning_proj.push(tail)
+ self._reasoning_per_block[idx] = full_r
+ return self._reasoning_per_block.get(idx, "")
+
+ def _push_content_block_finish(self, data: ContentBlockFinishData) -> None:
+ """Process a `content-block-finish` event."""
+ block = _event_content_block(data)
+ if block is None:
+ return
+ btype = block.get("type", "")
+ idx = data.get("index")
+ finalized: FinalizedContentBlock | None = None
+
+ if btype == "text":
+ text_block = cast("TextContentBlock", block)
+ full_text = text_block.get("text", "")
+ block_text = self._resolve_block_text(idx, full_text)
+ finalized = cast(
+ "FinalizedContentBlock",
+ {
+ **text_block,
+ "type": "text",
+ "text": block_text,
+ },
+ )
+ elif btype == "reasoning":
+ reasoning_block = cast("ReasoningContentBlock", block)
+ full_r = reasoning_block.get("reasoning", "")
+ block_reasoning = self._resolve_block_reasoning(idx, full_r)
+ # Keep provider-specific fields alongside the accumulated
+ # reasoning text. Anthropic's `signature` arrives under
+ # `extras` and is required on follow-up turns. Only overwrite
+ # `reasoning` when we have accumulated content; OpenAI can
+ # emit a reasoning block with no text deltas, and writing an
+ # empty string there makes downstream serializers synthesize
+ # an empty summary entry.
+ finalized_dict: dict[str, Any] = {**reasoning_block, "type": "reasoning"}
+ if block_reasoning:
+ finalized_dict["reasoning"] = block_reasoning
+ finalized = cast("FinalizedContentBlock", finalized_dict)
+ elif btype == "tool_call":
+ tcb = cast("ToolCall", block)
+ # Preserve provider-specific fields (extras, etc.) on the
+ # content block. `_assemble_message` separately projects the
+ # minimal {id, name, args, type} shape onto
+ # `AIMessage.tool_calls`. Strip `index` to match v1
+ # (`AIMessage.init_tool_calls` rebuilds the block without
+ # `index`); see `_finalize_block` in `_compat_bridge.py`.
+ tc = cast(
+ "ToolCall",
+ {
+ **{k: v for k, v in tcb.items() if k != "index"},
+ "type": "tool_call",
+ "id": tcb.get("id", ""),
+ "name": tcb.get("name", ""),
+ "args": tcb.get("args", {}),
+ },
+ )
+ self._tool_calls_acc.append(tc)
+ if idx is not None and idx in self._tool_call_chunks:
+ del self._tool_call_chunks[idx]
+ finalized = tc
+ elif btype == "invalid_tool_call":
+ itc = cast("InvalidToolCall", block)
+ # Strip `index` on the stored block to stay symmetric with
+ # the `tool_call` path.
+ itc = cast(
+ "InvalidToolCall",
+ {k: v for k, v in itc.items() if k != "index"},
+ )
+ self._invalid_tool_calls_acc.append(itc)
+ # Critical: drop the stale chunk so _finish's sweep doesn't revive
+ # it as an empty-args ToolCall.
+ if idx is not None and idx in self._tool_call_chunks:
+ del self._tool_call_chunks[idx]
+ if idx is not None and idx in self._server_tool_call_chunks:
+ del self._server_tool_call_chunks[idx]
+ finalized = itc
+ elif btype in (
+ "server_tool_call",
+ "server_tool_result",
+ "image",
+ "audio",
+ "video",
+ "file",
+ "non_standard",
+ ):
+ if btype == "server_tool_call" and idx is not None:
+ self._server_tool_call_chunks.pop(idx, None)
+ finalized = cast("FinalizedContentBlock", block)
+
+ if finalized is not None and idx is not None:
+ # Backfill the wire index onto the finalized block when the
+ # source didn't supply one. `langchain_core.utils._merge`'s
+ # block-merger (used by `AIMessageChunk.__add__` /
+ # `add_ai_message_chunks`) keys on `block["index"]` to group
+ # deltas into the same output block — without it, a v2-
+ # assembled `AIMessage` that later re-enters the chunk
+ # aggregation path won't merge cleanly. Client-side
+ # `tool_call` / `invalid_tool_call` blocks are excluded: v1
+ # finalization drops `index` on them so further deltas
+ # cannot clobber already-parsed args, and v2 mirrors that.
+ if btype not in ("tool_call", "invalid_tool_call"):
+ finalized.setdefault("index", idx)
+ self._blocks[idx] = finalized
+
+ def _finish(self, data: MessageFinishData) -> None:
+ """Process a `message-finish` event."""
+ self._done = True
+ self._usage_value = data.get("usage")
+ self._finish_metadata = cast("dict[str, Any] | None", data.get("metadata"))
+
+ # Finalize any unswept chunks — both client- and server-side.
+ _sweep_chunk_store(
+ self._tool_call_chunks,
+ finalized_type="tool_call",
+ finalized_blocks=self._blocks,
+ tool_calls_acc=self._tool_calls_acc,
+ invalid_acc=self._invalid_tool_calls_acc,
+ )
+ _sweep_chunk_store(
+ self._server_tool_call_chunks,
+ finalized_type="server_tool_call",
+ finalized_blocks=self._blocks,
+ tool_calls_acc=None,
+ invalid_acc=self._invalid_tool_calls_acc,
+ )
+
+ # Prefer the per-block sum when any indexed text / reasoning
+ # arrived — it stays correct regardless of finish ordering and
+ # of whether finish events carried authoritative text that
+ # differed from the deltas. Fall back to the delta-sum
+ # accumulator only for the legacy no-index path.
+ if self._text_per_block:
+ text_final = "".join(
+ self._text_per_block[i] for i in sorted(self._text_per_block)
+ )
+ else:
+ text_final = self._text_acc
+ if self._reasoning_per_block:
+ reasoning_final = "".join(
+ self._reasoning_per_block[i] for i in sorted(self._reasoning_per_block)
+ )
+ else:
+ reasoning_final = self._reasoning_acc
+
+ self._text_proj.complete(text_final)
+ self._reasoning_proj.complete(reasoning_final)
+ self._tool_calls_proj.complete(self._tool_calls_acc)
+ self._output_message = self._assemble_message()
+
+ def fail(self, error: BaseException) -> None:
+ """Mark the stream as errored and propagate to all projections.
+
+ Public API — called by the stream driver (`stream_events(version="v3")` /
+ `astream_events(version="v3")`) when the underlying producer raises, by
+ `dispatch` when an `error` protocol event arrives, and by
+ cancellation paths.
+ """
+ self._done = True
+ self._error = error
+ self._text_proj.fail(error)
+ self._reasoning_proj.fail(error)
+ self._tool_calls_proj.fail(error)
+
+ def _assemble_message(self) -> AIMessage:
+ """Build an `AIMessage` from accumulated state.
+
+ Content is built from `self._blocks`, an index-ordered snapshot of
+ finalized protocol blocks. The bare-string fast path is used when
+ the message has exactly one `text` block (the common chat case);
+ otherwise content is a list of protocol-shape block dicts.
+ """
+ content: Any
+ if not self._blocks:
+ # No protocol blocks ever arrived. Fall back to the accumulated
+ # text (possibly empty) as bare-string content.
+ content = self._text_acc
+ else:
+ # `ChatModelStream` is the v1 content-block surface: content
+ # is always a list of protocol blocks when any block arrived.
+ # Do not collapse a single text block down to a bare string —
+ # that would drop block-level fields (`id`, `index`,
+ # annotations, extras) that downstream serializers need to
+ # round-trip the message on a follow-up turn.
+ ordered_blocks = [self._blocks[idx] for idx in sorted(self._blocks)]
+ content = [dict(b) for b in ordered_blocks]
+
+ response_metadata: dict[str, Any] = {}
+ if self._start_metadata:
+ if "provider" in self._start_metadata:
+ response_metadata["model_provider"] = self._start_metadata["provider"]
+ if "model" in self._start_metadata:
+ response_metadata["model_name"] = self._start_metadata["model"]
+ if self._finish_metadata:
+ response_metadata.update(self._finish_metadata)
+ # Pin `output_version` last: `stream_events(version="v3")` always
+ # assembles content as v1 protocol blocks, regardless of the
+ # provider's configured output format.
+ # A provider-supplied `output_version` in finish metadata (e.g.
+ # `"responses/v1"` from `ChatOpenAI(use_responses_api=True, ...)`) would
+ # otherwise cause `AIMessage.content_blocks` to re-run the wrong
+ # translator on already-v1 content.
+ response_metadata["output_version"] = "v1"
+
+ tool_calls = [
+ {
+ "id": tc.get("id", ""),
+ "name": tc.get("name", ""),
+ "args": tc.get("args", {}),
+ "type": "tool_call",
+ }
+ for tc in self._tool_calls_acc
+ ]
+
+ invalid_tool_calls = [
+ {
+ "type": "invalid_tool_call",
+ "id": itc.get("id") or None,
+ "name": itc.get("name") or None,
+ "args": itc.get("args") or None,
+ "error": itc.get("error"),
+ }
+ for itc in self._invalid_tool_calls_acc
+ ]
+
+ return AIMessage(
+ content=content,
+ id=self._message_id,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ usage_metadata=self._usage_value,
+ response_metadata=response_metadata,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Sync stream
+# ---------------------------------------------------------------------------
+
+
+class ChatModelStream(_ChatModelStreamBase):
+ """Synchronous per-message streaming object for a single LLM response.
+
+ Returned by `BaseChatModel.stream_events(version="v3")`. Content-block protocol
+ events are fed into this object and accumulated into typed projections.
+
+ Projections (always return the same cached object):
+
+ - `.text` — iterable of `str` deltas; `str()` for full text
+ - `.reasoning` — same as `.text` for reasoning content
+ - `.tool_calls` — iterable of `ToolCallChunk` deltas;
+ `.get()` returns `list[ToolCall]`
+ - `.output` — blocking property, returns assembled `AIMessage`
+
+ Usage info is available on `.output.usage_metadata` once the stream
+ has finished.
+
+ !!! note "Output shape is always v1 content blocks"
+
+ `.output.content` is always a list of v1 protocol blocks
+ (text, reasoning, tool_call, image, …), regardless of the
+ underlying model's `output_version` setting. That attribute
+ only controls the legacy `stream()` / `astream()` / `invoke()`
+ paths; `ChatModelStream` is built on the content-block
+ protocol and emits v1 shapes by construction.
+
+ Raw event iteration::
+
+ for event in stream:
+ print(event) # MessagesData dicts
+ """
+
+ _text_proj: SyncTextProjection
+ _reasoning_proj: SyncTextProjection
+ _tool_calls_proj: SyncProjection
+
+ def __init__( # noqa: D107
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ super().__init__(namespace=namespace, node=node, message_id=message_id)
+ # Projections — created eagerly
+ self._text_proj = SyncTextProjection()
+ self._reasoning_proj = SyncTextProjection()
+ self._tool_calls_proj = SyncProjection()
+ # Pull callback (set by bind_pump or set_request_more)
+ self._ensure_started: Callable[[], None] | None = None
+ self._request_more: Callable[[], bool] | None = None
+
+ # -- Pump/pull wiring --------------------------------------------------
+
+ def bind_pump(self, pump_one: Callable[[], bool]) -> None:
+ """Bind a pump for standalone streaming.
+
+ Delegates to `set_request_more`. Used by
+ `BaseChatModel.stream_events(version="v3")`.
+ """
+ self.set_request_more(pump_one)
+
+ def set_start(self, cb: Callable[[], None] | None) -> None:
+ """Install a lazy-start callback on this stream and its projections."""
+ self._ensure_started = cb
+ self._text_proj.set_start(cb)
+ self._reasoning_proj.set_start(cb)
+ self._tool_calls_proj.set_start(cb)
+
+ def set_request_more(self, cb: Callable[[], bool]) -> None:
+ """Set the pull callback on this stream and all its projections.
+
+ Used by langgraph's `GraphRunStream._wire_request_more` to
+ connect the shared graph pump.
+ """
+ self._request_more = cb
+ self._text_proj.set_request_more(cb)
+ self._reasoning_proj.set_request_more(cb)
+ self._tool_calls_proj.set_request_more(cb)
+
+ # -- Public projections ------------------------------------------------
+
+ @property
+ def text(self) -> SyncTextProjection:
+ """Text content — iterable of `str` deltas, `str()` for full."""
+ return self._text_proj
+
+ @property
+ def reasoning(self) -> SyncTextProjection:
+ """Reasoning content — same interface as :attr:`text`."""
+ return self._reasoning_proj
+
+ @property
+ def tool_calls(self) -> SyncProjection:
+ """Tool calls — iterable of `ToolCallChunk` deltas.
+
+ `.get()` returns finalized `list[ToolCall]`.
+ """
+ return self._tool_calls_proj
+
+ @property
+ def output(self) -> AIMessage:
+ """Assembled `AIMessage` — blocks until the stream finishes."""
+ self._drain()
+ if self._error is not None:
+ raise self._error
+ if self._output_message is None:
+ msg = "Stream finished without producing a message"
+ raise RuntimeError(msg)
+ return self._output_message
+
+ # -- Raw event iteration (replay buffer) -------------------------------
+
+ def __iter__(self) -> Iterator[MessagesData]:
+ """Iterate raw protocol events with replay-buffer semantics."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ cursor = 0
+ while True:
+ if cursor < len(self._events):
+ yield self._events[cursor]
+ cursor += 1
+ elif self._error is not None:
+ raise self._error
+ elif self._done:
+ return
+ elif self._request_more is not None:
+ while cursor >= len(self._events) and not self._done:
+ if not self._request_more():
+ break
+ if cursor >= len(self._events):
+ if self._error is not None:
+ raise self._error
+ return
+ else:
+ return
+
+ # -- Internal helpers --------------------------------------------------
+
+ def _drain(self) -> None:
+ """Pull all remaining events until done."""
+ if self._done:
+ return
+ if self._ensure_started is not None:
+ self._ensure_started()
+ if self._request_more is not None:
+ while not self._done:
+ if not self._request_more():
+ break
+
+
+# ---------------------------------------------------------------------------
+# Async stream
+# ---------------------------------------------------------------------------
+
+
+class AsyncChatModelStream(_ChatModelStreamBase):
+ """Asynchronous per-message streaming object for a single LLM response.
+
+ Returned by `BaseChatModel.astream_events(version="v3")`. Content-block events
+ are fed into this object by a background producer task.
+
+ Projections:
+
+ - `.text` — async iterable of text deltas; awaitable for full text
+ - `.reasoning` — async iterable of reasoning deltas; awaitable
+ - `.tool_calls` — async iterable of `ToolCallChunk` deltas;
+ awaitable for `list[ToolCall]`
+ - `.output` — awaitable for assembled `AIMessage`
+
+ Usage info is available on `.output.usage_metadata` once the stream
+ has finished.
+
+ !!! note "Output shape is always v1 content blocks"
+
+ The assembled message's content is always a list of v1
+ protocol blocks, regardless of the model's `output_version`
+ setting — see `ChatModelStream` for the full rationale.
+
+ The stream itself is awaitable (`msg = await stream`) and
+ async-iterable (`async for event in stream`).
+ """
+
+ _text_proj: AsyncProjection
+ _reasoning_proj: AsyncProjection
+ _tool_calls_proj: AsyncProjection
+
+ def __init__( # noqa: D107
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ super().__init__(namespace=namespace, node=node, message_id=message_id)
+ self._text_proj = AsyncProjection()
+ self._reasoning_proj = AsyncProjection()
+ self._tool_calls_proj = AsyncProjection()
+ self._output_proj = AsyncProjection()
+ self._events_proj = AsyncProjection()
+ self._ensure_started: Callable[[], Awaitable[None]] | None = None
+ self._producer_task: asyncio.Task[None] | None = None
+ # Teardown callback invoked by `aclose()` only when the producer
+ # task was cancelled before its body ran (so the normal
+ # `_produce` CancelledError handler — which fires
+ # `on_llm_error` — never executed). Set by `astream_events(version="v3")`.
+ self._on_aclose_fail: Callable[[BaseException], Awaitable[None]] | None = None
+
+ # -- Pump/pull wiring (async) ------------------------------------------
+
+ def set_arequest_more(self, cb: Callable[[], Awaitable[bool]] | None) -> None:
+ """Fan the async pump callback out to every projection.
+
+ Used by langgraph's `AsyncGraphRunStream._wire_arequest_more` so
+ cursors on `stream.text`, `stream.reasoning`, etc. can drive the
+ shared graph pump when their buffer is empty.
+
+ Args:
+ cb: Async no-arg callable returning `True` when a new event
+ was produced, `False` when the source is exhausted. Pass
+ `None` to unwire.
+ """
+ for proj in (
+ self._text_proj,
+ self._reasoning_proj,
+ self._tool_calls_proj,
+ self._output_proj,
+ self._events_proj,
+ ):
+ proj.set_arequest_more(cb)
+
+ def set_start(self, cb: Callable[[], Awaitable[None]] | None) -> None:
+ """Install a lazy-start callback on this stream and its projections."""
+ self._ensure_started = cb
+ for proj in (
+ self._text_proj,
+ self._reasoning_proj,
+ self._tool_calls_proj,
+ self._output_proj,
+ self._events_proj,
+ ):
+ proj.set_start(cb)
+
+ # -- Public projections ------------------------------------------------
+
+ @property
+ def text(self) -> AsyncProjection:
+ """Text content — async iterable of deltas, awaitable for full."""
+ return self._text_proj
+
+ @property
+ def reasoning(self) -> AsyncProjection:
+ """Reasoning content — same interface as :attr:`text`."""
+ return self._reasoning_proj
+
+ @property
+ def tool_calls(self) -> AsyncProjection:
+ """Tool calls — async iterable, awaitable for finalized list."""
+ return self._tool_calls_proj
+
+ @property
+ def output(self) -> AsyncProjection:
+ """Assembled `AIMessage` — awaitable."""
+ return self._output_proj
+
+ def __await__(self) -> Generator[Any, None, AIMessage]:
+ """Await the assembled `AIMessage` and full producer lifecycle.
+
+ The producer task is awaited after the output projection resolves so
+ that post-stream work (notably `on_llm_end` callbacks) has run by
+ the time the caller's `await` returns.
+ """
+ return self._await_full().__await__()
+
+ async def _await_full(self) -> AIMessage:
+ if self._ensure_started is not None:
+ await self._ensure_started()
+ message: AIMessage = await self._output_proj
+ if self._producer_task is not None:
+ await self._producer_task
+ return message
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Iterate raw protocol events asynchronously."""
+ return _AsyncProjectionIterator(self._events_proj)
+
+ # -- Cleanup -----------------------------------------------------------
+
+ async def aclose(self) -> None:
+ """Cancel the background producer task and release resources.
+
+ If a consumer cancels mid-stream or decides to stop iterating
+ early, the producer task keeps pumping the provider HTTP call to
+ completion because `asyncio.Task` has no implicit link to its
+ awaiter. Call this method to cancel the producer explicitly; the
+ stream transitions to an errored state with `CancelledError`.
+
+ If the stream has already produced a message successfully (for
+ example, after `await stream.output`), the producer may still be
+ running post-stream work such as `on_llm_end` callbacks. In that
+ case `aclose()` awaits the task rather than cancelling it —
+ turning a successful run into a cancelled one would drop the
+ end callback and corrupt tracing.
+
+ Idempotent: safe to call multiple times, including after the
+ stream has finished normally. Also invoked by the async context
+ manager protocol on `__aexit__`.
+ """
+ if self._ensure_started is not None and self._producer_task is None:
+ await self._ensure_started()
+
+ task = self._producer_task
+ if task is None:
+ return
+ if task.done() and self._done:
+ return
+
+ we_cancelled = not (self._output_message is not None and self._error is None)
+ if we_cancelled and not task.done():
+ task.cancel()
+
+ # Wait for the task via a linked `Future`, not by awaiting the
+ # task directly. Awaiting the task would raise `CancelledError`
+ # in two indistinguishable cases: (1) the task we just cancelled
+ # completed, (2) our caller cancelled us. `asyncio.Task.cancelling()`
+ # disambiguates on 3.11+ but doesn't exist on 3.10.
+ #
+ # The `done_future` resolves with `None` whenever the task
+ # finishes (any reason). It is not a `Task` itself, so its
+ # `await` only raises when our caller is cancelled — giving us
+ # a portable, unambiguous signal to propagate.
+ if not task.done():
+ loop = asyncio.get_running_loop()
+ done_future: asyncio.Future[None] = loop.create_future()
+
+ def _link(_: asyncio.Task[None]) -> None:
+ if not done_future.done():
+ done_future.set_result(None)
+
+ task.add_done_callback(_link)
+ try:
+ await done_future
+ finally:
+ task.remove_done_callback(_link)
+
+ # If the task was cancelled before `_produce` ran (e.g.
+ # `astream_events(version="v3")` immediately followed by `aclose()`), the stream
+ # never reached `_produce`'s CancelledError handler — its
+ # projections are still pending and no end-of-lifecycle callback
+ # has fired. Resolve both here so callers of `await stream.output`
+ # don't hang and tracing sees a matching end event.
+ if we_cancelled and not self._done:
+ cancel_exc = asyncio.CancelledError()
+ self.fail(cancel_exc)
+ teardown = self._on_aclose_fail
+ if teardown is not None:
+ with contextlib.suppress(Exception):
+ await teardown(cancel_exc)
+
+ async def __aenter__(self) -> Self:
+ """Enter the async context — returns self."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: object,
+ ) -> None:
+ """Exit the async context — cancels the producer via `aclose()`."""
+ del exc_type, exc, tb
+ await self.aclose()
+
+ # -- Internal API (extend base to drive async projections) -------------
+
+ def _record_event(self, event: Mapping[str, Any]) -> None:
+ """Record event and push to async event replay projection."""
+ super()._record_event(event)
+ self._events_proj.push(cast("MessagesData", event))
+
+ def _finish(self, data: MessageFinishData) -> None:
+ """Finish base projections and async-only projections."""
+ super()._finish(data)
+ self._output_proj.complete(self._output_message)
+ self._events_proj.complete(self._events)
+
+ def fail(self, error: BaseException) -> None:
+ """Fail base projections and async-only projections."""
+ super().fail(error)
+ self._output_proj.fail(error)
+ self._events_proj.fail(error)
+
+
+__all__ = [
+ "AsyncChatModelStream",
+ "AsyncProjection",
+ "ChatModelStream",
+ "SyncProjection",
+ "SyncTextProjection",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_models.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea4194e69cda42505e2832b1f5f6ab6a7f6171a7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/chat_models.py
@@ -0,0 +1,2675 @@
+"""Chat models for conversational AI."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import inspect
+import json
+from abc import ABC, abstractmethod
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from functools import cached_property
+from operator import itemgetter
+from typing import TYPE_CHECKING, Any, Literal, cast, overload
+
+from langchain_protocol.protocol import MessageFinishData
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core._api import beta
+from langchain_core.caches import BaseCache
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForLLMRun,
+ CallbackManager,
+ CallbackManagerForLLMRun,
+ Callbacks,
+)
+from langchain_core.globals import get_llm_cache
+from langchain_core.language_models._compat_bridge import (
+ achunks_to_events,
+ amessage_to_events,
+ chunks_to_events,
+ message_to_events,
+)
+from langchain_core.language_models._utils import (
+ _filter_invocation_params_for_tracing,
+ _normalize_messages,
+ _update_message_content_to_blocks,
+)
+from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+)
+from langchain_core.language_models.chat_model_stream import (
+ AsyncChatModelStream,
+ ChatModelStream,
+)
+from langchain_core.language_models.model_profile import (
+ ModelProfile,
+ _warn_unknown_profile_keys,
+)
+from langchain_core.load import dumpd, dumps
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ AnyMessage,
+ BaseMessage,
+ convert_to_messages,
+ is_data_content_block,
+ message_chunk_to_message,
+)
+from langchain_core.messages import content as types
+from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_image_block,
+)
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ Generation,
+ LLMResult,
+ RunInfo,
+)
+from langchain_core.outputs.chat_generation import merge_chat_generation_chunks
+from langchain_core.prompt_values import ChatPromptValue, PromptValue, StringPromptValue
+from langchain_core.rate_limiters import BaseRateLimiter
+from langchain_core.runnables import RunnableBinding, RunnableMap, RunnablePassthrough
+from langchain_core.runnables.config import ensure_config, run_in_executor
+from langchain_core.tracers._streaming import (
+ _StreamingCallbackHandler,
+ _V2StreamingCallbackHandler,
+)
+from langchain_core.utils.function_calling import (
+ convert_to_json_schema,
+ convert_to_openai_tool,
+)
+from langchain_core.utils.pydantic import TypeBaseModel, is_basemodel_subclass
+from langchain_core.utils.utils import LC_ID_PREFIX, from_env
+
+if TYPE_CHECKING:
+ import builtins
+ import uuid
+ from collections.abc import Awaitable
+
+ from langchain_protocol.protocol import MessagesData
+
+ from langchain_core.output_parsers.base import OutputParserLike
+ from langchain_core.runnables import Runnable, RunnableConfig
+ from langchain_core.runnables.schema import StreamEvent
+ from langchain_core.tools import BaseTool
+
+
+def _generate_response_from_error(error: BaseException) -> list[ChatGeneration]:
+ if hasattr(error, "response"):
+ response = error.response
+ metadata: dict = {}
+ if hasattr(response, "json"):
+ try:
+ metadata["body"] = response.json()
+ except Exception:
+ try:
+ metadata["body"] = getattr(response, "text", None)
+ except Exception:
+ metadata["body"] = None
+ if hasattr(response, "headers"):
+ try:
+ metadata["headers"] = dict(response.headers)
+ except Exception:
+ metadata["headers"] = None
+ if hasattr(response, "status_code"):
+ metadata["status_code"] = response.status_code
+ if hasattr(error, "request_id"):
+ metadata["request_id"] = error.request_id
+ generations = [
+ ChatGeneration(message=AIMessage(content="", response_metadata=metadata))
+ ]
+ else:
+ generations = []
+
+ return generations
+
+
+def _format_for_tracing(messages: list[BaseMessage]) -> list[BaseMessage]:
+ """Format messages for tracing in `on_chat_model_start`.
+
+ - Update image content blocks to OpenAI Chat Completions format (backward
+ compatibility).
+ - Add `type` key to content blocks that have a single key.
+
+ Args:
+ messages: List of messages to format.
+
+ Returns:
+ List of messages formatted for tracing.
+
+ """
+ messages_to_trace = []
+ for message in messages:
+ message_to_trace = message
+ if isinstance(message.content, list):
+ for idx, block in enumerate(message.content):
+ if isinstance(block, dict):
+ # Update image content blocks to OpenAI # Chat Completions format.
+ if (
+ block.get("type") == "image"
+ and is_data_content_block(block)
+ and not ("file_id" in block or block.get("source_type") == "id")
+ ):
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+
+ message_to_trace.content[idx] = ( # type: ignore[index] # mypy confused by .model_copy
+ convert_to_openai_image_block(block)
+ )
+ elif (
+ block.get("type") == "file"
+ and is_data_content_block(block) # v0 (image/audio/file) or v1
+ and "base64" in block
+ # Backward compat: convert v1 base64 blocks to v0
+ ):
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+
+ message_to_trace.content[idx] = { # type: ignore[index]
+ **{k: v for k, v in block.items() if k != "base64"},
+ "data": block["base64"],
+ "source_type": "base64",
+ }
+ elif len(block) == 1 and "type" not in block:
+ # Tracing assumes all content blocks have a "type" key. Here
+ # we add this key if it is missing, and there's an obvious
+ # choice for the type (e.g., a single key in the block).
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+ key = next(iter(block))
+ message_to_trace.content[idx] = { # type: ignore[index]
+ "type": key,
+ key: block[key],
+ }
+ messages_to_trace.append(message_to_trace)
+
+ return messages_to_trace
+
+
+def generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult:
+ """Generate from a stream.
+
+ Args:
+ stream: Iterator of `ChatGenerationChunk`.
+
+ Raises:
+ ValueError: If no generations are found in the stream.
+
+ Returns:
+ Chat result.
+
+ """
+ generation = next(stream, None)
+ if generation:
+ generation += list(stream)
+ if generation is None:
+ msg = "No generations found in stream."
+ raise ValueError(msg)
+ return ChatResult(
+ generations=[
+ ChatGeneration(
+ message=message_chunk_to_message(generation.message),
+ generation_info=generation.generation_info,
+ )
+ ]
+ )
+
+
+async def agenerate_from_stream(
+ stream: AsyncIterator[ChatGenerationChunk],
+) -> ChatResult:
+ """Async generate from a stream.
+
+ Args:
+ stream: AsyncIterator of `ChatGenerationChunk`.
+
+ Returns:
+ Chat result.
+
+ """
+ chunks = [chunk async for chunk in stream]
+ return await run_in_executor(None, generate_from_stream, iter(chunks))
+
+
+def _format_ls_structured_output(ls_structured_output_format: dict | None) -> dict:
+ if ls_structured_output_format:
+ try:
+ ls_structured_output_format_dict = {
+ "ls_structured_output_format": {
+ "kwargs": ls_structured_output_format.get("kwargs", {}),
+ "schema": convert_to_json_schema(
+ ls_structured_output_format["schema"]
+ ),
+ }
+ }
+ except ValueError:
+ ls_structured_output_format_dict = {}
+ else:
+ ls_structured_output_format_dict = {}
+
+ return ls_structured_output_format_dict
+
+
+class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
+ r"""Base class for chat models.
+
+ Key imperative methods:
+ Methods that actually call the underlying model.
+
+ This table provides a brief overview of the main imperative methods. Please see the base `Runnable` reference for full documentation.
+
+ | Method | Input | Output | Description |
+ | ---------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------- |
+ | `invoke` | `str` \| `list[dict | tuple | BaseMessage]` \| `PromptValue` | `BaseMessage` | A single chat model call. |
+ | `ainvoke` | `'''` | `BaseMessage` | Defaults to running `invoke` in an async executor. |
+ | `stream` | `'''` | `Iterator[BaseMessageChunk]` | Defaults to yielding output of `invoke`. |
+ | `astream` | `'''` | `AsyncIterator[BaseMessageChunk]` | Defaults to yielding output of `ainvoke`. |
+ | `astream_events` | `'''` | `AsyncIterator[StreamEvent]` | Event types: `on_chat_model_start`, `on_chat_model_stream`, `on_chat_model_end`. |
+ | `batch` | `list[''']` | `list[BaseMessage]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch` | `list[''']` | `list[BaseMessage]` | Defaults to running `ainvoke` in concurrent threads. |
+ | `batch_as_completed` | `list[''']` | `Iterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch_as_completed` | `list[''']` | `AsyncIterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `ainvoke` in concurrent threads. |
+
+ Key declarative methods:
+ Methods for creating another `Runnable` using the chat model.
+
+ This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
+
+ | Method | Description |
+ | ---------------------------- | ------------------------------------------------------------------------------------------ |
+ | `bind_tools` | Create chat model that can call tools. |
+ | `with_structured_output` | Create wrapper that structures model output using schema. |
+ | `with_retry` | Create wrapper that retries model calls on failure. |
+ | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
+ | `configurable_fields` | Specify init args of the model that can be configured at runtime via the `RunnableConfig`. |
+ | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the `RunnableConfig`. |
+
+ Creating custom chat model:
+ Custom chat model implementations should inherit from this class.
+ Please reference the table below for information about which
+ methods and properties are required or optional for implementations.
+
+ | Method/Property | Description | Required |
+ | -------------------------------- | ------------------------------------------------------------------ | ----------------- |
+ | `_generate` | Use to generate a chat result from a prompt | Required |
+ | `_llm_type` (property) | Used to uniquely identify the type of the model. Used for logging. | Required |
+ | `_identifying_params` (property) | Represent model parameterization for tracing purposes. | Optional |
+ | `_stream` | Use to implement streaming | Optional |
+ | `_agenerate` | Use to implement a native async method | Optional |
+ | `_astream` | Use to implement async version of `_stream` | Optional |
+
+ """ # noqa: E501
+
+ rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True)
+ "An optional rate limiter to use for limiting the number of requests."
+
+ disable_streaming: bool | Literal["tool_calling"] = False
+ """Whether to disable streaming for this model.
+
+ If streaming is bypassed, then `stream`/`astream`/`astream_events` will
+ defer to `invoke`/`ainvoke`.
+
+ - If `True`, will always bypass streaming case.
+ - If `'tool_calling'`, will bypass streaming case only when the model is called
+ with a `tools` keyword argument. In other words, LangChain will automatically
+ switch to non-streaming behavior (`invoke`) only when the tools argument is
+ provided. This offers the best of both worlds.
+ - If `False` (Default), will always use streaming case if available.
+
+ The main reason for this flag is that code might be written using `stream` and
+ a user may want to swap out a given model for another model whose implementation
+ does not properly support streaming.
+ """
+
+ output_version: str | None = Field(
+ default_factory=from_env("LC_OUTPUT_VERSION", default=None)
+ )
+ """Version of `AIMessage` output format to store in message content.
+
+ `AIMessage.content_blocks` will lazily parse the contents of `content` into a
+ standard format. This flag can be used to additionally store the standard format
+ in message content, e.g., for serialization purposes.
+
+ Supported values:
+
+ - `'v0'`: provider-specific format in content (can lazily-parse with
+ `content_blocks`)
+ - `'v1'`: standardized format in content (consistent with `content_blocks`)
+
+ Partner packages (e.g.,
+ [`langchain-openai`](https://pypi.org/project/langchain-openai)) can also use this
+ field to roll out new content formats in a backward-compatible way.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+
+ """
+
+ profile: ModelProfile | None = Field(default=None, exclude=True)
+ """Profile detailing model capabilities.
+
+ !!! warning "Beta feature"
+
+ This is a beta feature. The format of model profiles is subject to change.
+
+ If not specified, automatically loaded from the provider package on initialization
+ if data is available.
+
+ Example profile data includes context window sizes, supported modalities, or support
+ for tool calling, structured output, and other features.
+
+ !!! version-added "Added in `langchain-core` 1.1.0"
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def _resolve_model_profile(self) -> ModelProfile | None:
+ """Return the default model profile, or `None` if unavailable.
+
+ Override this in subclasses instead of `_set_model_profile`. The base
+ validator calls it automatically and handles assignment. This avoids
+ coupling partner code to Pydantic validator mechanics.
+
+ Each partner needs its own override because things can vary per-partner,
+ such as the attribute that identifies the model (e.g., `model`,
+ `model_name`, `model_id`, `deployment_name`) and the partner-local
+ `_get_default_model_profile` function that reads from each partner's own
+ profile data.
+ """
+ # TODO: consider adding a `_model_identifier` property on BaseChatModel
+ # to standardize how partners identify their model, which could allow a
+ # default implementation here that calls a shared
+ # profile-loading mechanism.
+ return None
+
+ @model_validator(mode="after")
+ def _set_model_profile(self) -> Self:
+ """Populate `profile` from `_resolve_model_profile` if not provided.
+
+ Partners should override `_resolve_model_profile` rather than this
+ validator. Overriding this with a new `@model_validator` replaces the
+ base validator (Pydantic v2 behavior), bypassing the standard resolution
+ path. A plain method override does not prevent the base validator from
+ running.
+ """
+ if self.profile is None:
+ # Suppress errors from partner overrides (e.g., missing profile
+ # files, broken imports) so model construction never fails over an
+ # optional field.
+ with contextlib.suppress(Exception):
+ self.profile = self._resolve_model_profile()
+ return self
+
+ # NOTE: _check_profile_keys must be defined AFTER _set_model_profile.
+ # Pydantic v2 runs mode="after" validators in definition order.
+ @model_validator(mode="after")
+ def _check_profile_keys(self) -> Self:
+ """Warn on unrecognized profile keys."""
+ # isinstance guard: ModelProfile is a TypedDict (always a dict), but
+ # protects against unexpected types from partner overrides.
+ if self.profile and isinstance(self.profile, dict):
+ _warn_unknown_profile_keys(self.profile)
+ return self
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumps uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ # --- Runnable methods ---
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """Get the output type for this `Runnable`."""
+ return AnyMessage
+
+ def _convert_input(self, model_input: LanguageModelInput) -> PromptValue:
+ if isinstance(model_input, PromptValue):
+ return model_input
+ if isinstance(model_input, str):
+ return StringPromptValue(text=model_input)
+ if isinstance(model_input, Sequence):
+ return ChatPromptValue(messages=convert_to_messages(model_input))
+ msg = (
+ f"Invalid input type {type(model_input)}. "
+ "Must be a PromptValue, str, or list of BaseMessages."
+ )
+ raise ValueError(msg)
+
+ @override
+ def invoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AIMessage:
+ config = ensure_config(config)
+ return cast(
+ "AIMessage",
+ cast(
+ "ChatGeneration",
+ self.generate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ ).generations[0][0],
+ ).message,
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AIMessage:
+ config = ensure_config(config)
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ return cast(
+ "AIMessage", cast("ChatGeneration", llm_result.generations[0][0]).message
+ )
+
+ def _streaming_disabled(self, **kwargs: Any) -> bool:
+ """Return whether streaming is hard-disabled for this call.
+
+ Shared opt-outs honored by both `_should_stream` and
+ `_should_use_protocol_streaming` — these override any affirmative trigger
+ (attached handler, `stream=True`, etc.):
+
+ - `self.disable_streaming is True`
+ - `self.disable_streaming == "tool_calling"` with `tools` passed
+ - `stream=` in call kwargs
+ - `self.streaming is False` on the instance
+ """
+ if self.disable_streaming is True:
+ return True
+ # We assume tools are passed in via "tools" kwarg in all models.
+ if self.disable_streaming == "tool_calling" and kwargs.get("tools"):
+ return True
+ if "stream" in kwargs and not kwargs["stream"]:
+ return True
+ return (
+ "streaming" in self.model_fields_set
+ and getattr(self, "streaming", None) is False
+ )
+
+ def _should_stream(
+ self,
+ *,
+ async_api: bool,
+ run_manager: CallbackManagerForLLMRun
+ | AsyncCallbackManagerForLLMRun
+ | None = None,
+ **kwargs: Any,
+ ) -> bool:
+ """Determine if a given model call should hit the streaming API."""
+ sync_not_implemented = type(self)._stream == BaseChatModel._stream # noqa: SLF001
+ async_not_implemented = type(self)._astream == BaseChatModel._astream # noqa: SLF001
+
+ # Check if streaming is implemented.
+ if (not async_api) and sync_not_implemented:
+ return False
+ # Note, since async falls back to sync we check both here.
+ if async_api and async_not_implemented and sync_not_implemented:
+ return False
+
+ if self._streaming_disabled(**kwargs):
+ return False
+
+ # Affirmative: explicit `stream=` kwarg.
+ if kwargs.get("stream"):
+ return True
+
+ # Affirmative: instance-level `streaming=True` attribute.
+ if (
+ "streaming" in self.model_fields_set
+ and getattr(self, "streaming", None) is True
+ ):
+ return True
+
+ # Affirmative: a v1 streaming callback handler is attached.
+ handlers = run_manager.handlers if run_manager else []
+ return any(isinstance(h, _StreamingCallbackHandler) for h in handlers)
+
+ def _should_use_protocol_streaming(
+ self,
+ *,
+ async_api: bool,
+ run_manager: CallbackManagerForLLMRun
+ | AsyncCallbackManagerForLLMRun
+ | None = None,
+ **kwargs: Any,
+ ) -> bool:
+ """Determine whether an invoke should route through the v2 event path.
+
+ Runs alongside `_should_stream` inside `_generate_with_cache` /
+ `_agenerate_with_cache` — after the run manager is open — and
+ wins over the v1 streaming branch when a handler has declared
+ itself a `_V2StreamingCallbackHandler`. Parallel to
+ `_should_stream` rather than a delegation — v1 and v2 have
+ disjoint affirmative triggers.
+
+ Args:
+ async_api: Whether the caller is on the async path.
+ run_manager: The active LLM run manager.
+ **kwargs: Call kwargs; inspected for `disable_streaming`
+ semantics and an explicit `stream=False` override.
+
+ Returns:
+ `True` if any attached handler inherits
+ `_V2StreamingCallbackHandler` and the model can drive the v2
+ event generator (natively or via the `_stream` compat
+ bridge).
+ """
+ # Opt-in: only route through v2 when a v2 handler is attached.
+ handlers = run_manager.handlers if run_manager else []
+ if not any(isinstance(h, _V2StreamingCallbackHandler) for h in handlers):
+ return False
+
+ # Need a source of v2 events on the requested flavor. A native
+ # `_(a)stream_chat_model_events` hook bypasses the bridge;
+ # otherwise the bridge wraps `_stream` / `_astream`. Async can
+ # fall back to sync.
+ #
+ # `cls._stream is not BaseChatModel._stream` is an identity
+ # check for "subclass overrode `_stream`" — same pattern as
+ # `_should_stream`.
+ cls = type(self)
+ has_native_sync = getattr(cls, "_stream_chat_model_events", None) is not None
+ has_native_async = getattr(cls, "_astream_chat_model_events", None) is not None
+ overrides_sync = cls._stream is not BaseChatModel._stream
+ overrides_async = cls._astream is not BaseChatModel._astream
+ has_sync_source = has_native_sync or overrides_sync
+ has_async_source = has_native_async or overrides_async
+ has_source = (
+ (has_sync_source or has_async_source) if async_api else has_sync_source
+ )
+ if not has_source:
+ return False
+
+ return not self._streaming_disabled(**kwargs)
+
+ def _iter_v2_events(
+ self,
+ messages: list[BaseMessage],
+ *,
+ run_manager: CallbackManagerForLLMRun,
+ stream: ChatModelStream,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[MessagesData]:
+ """Drive the v2 event generator with per-event dispatch.
+
+ Shared between the `stream_events(version="v3")` pump and the
+ invoke-time v2 branch in `_generate_with_cache`. Picks the native
+ `_stream_chat_model_events` hook when the subclass provides one,
+ else bridges `_stream` chunks via `chunks_to_events`. Each event
+ is dispatched into `stream` and fired as `on_stream_event` on
+ the run manager. Run-lifecycle callbacks
+ (`on_chat_model_start` / `on_llm_end` / `on_llm_error`) and
+ rate-limiter acquisition are the caller's responsibility.
+
+ Args:
+ messages: Normalized input messages.
+ run_manager: Active LLM run manager; receives
+ `on_stream_event` per event.
+ stream: Accumulator owned by the caller; receives each
+ event via `stream.dispatch`.
+ stop: Optional stop sequences.
+ **kwargs: Forwarded to the event producer.
+
+ Yields:
+ Each protocol event produced by the model.
+ """
+ native = cast(
+ "Callable[..., Iterator[MessagesData]] | None",
+ getattr(self, "_stream_chat_model_events", None),
+ )
+ if native is not None:
+ event_iter: Iterator[MessagesData] = native(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ event_iter = chunks_to_events(
+ self._stream(messages, stop=stop, run_manager=run_manager, **kwargs),
+ message_id=stream.message_id,
+ )
+ for event in event_iter:
+ stream.dispatch(event)
+ run_manager.on_stream_event(event)
+ yield event
+
+ async def _aiter_v2_events(
+ self,
+ messages: list[BaseMessage],
+ *,
+ run_manager: AsyncCallbackManagerForLLMRun,
+ stream: AsyncChatModelStream,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[MessagesData]:
+ """Async counterpart to `_iter_v2_events`.
+
+ See `_iter_v2_events` for the shared contract.
+ """
+ native = cast(
+ "Callable[..., AsyncIterator[MessagesData]] | None",
+ getattr(self, "_astream_chat_model_events", None),
+ )
+ if native is not None:
+ event_iter: AsyncIterator[MessagesData] = native(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ event_iter = achunks_to_events(
+ self._astream(messages, stop=stop, run_manager=run_manager, **kwargs),
+ message_id=stream.message_id,
+ )
+ async for event in event_iter:
+ stream.dispatch(event)
+ await run_manager.on_stream_event(event)
+ yield event
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[AIMessageChunk]:
+ if not self._should_stream(async_api=False, **{**kwargs, "stream": True}):
+ # Model doesn't implement streaming, so use default implementation
+ yield cast(
+ "AIMessageChunk",
+ self.invoke(input, config=config, stop=stop, **kwargs),
+ )
+ else:
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+
+ chunks: list[ChatGenerationChunk] = []
+
+ if self.rate_limiter:
+ self.rate_limiter.acquire(blocking=True)
+
+ try:
+ input_messages = _normalize_messages(messages)
+ run_id = "-".join((LC_ID_PREFIX, str(run_manager.run_id)))
+ yielded = False
+ index = -1
+ index_type = ""
+ for chunk in self._stream(input_messages, stop=stop, **kwargs):
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yield cast("AIMessageChunk", chunk.message)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet
+ # yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ msg_chunk = AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ run_manager.on_llm_new_token(
+ "", chunk=ChatGenerationChunk(message=msg_chunk)
+ )
+ yield msg_chunk
+ except BaseException as e:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ chat_generation_chunk = merge_chat_generation_chunks(chunks)
+ if chat_generation_chunk:
+ generations = [
+ [chat_generation_chunk],
+ generations_with_error_metadata,
+ ]
+ else:
+ generations = [generations_with_error_metadata]
+ run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=generations),
+ )
+ raise
+
+ generation = merge_chat_generation_chunks(chunks)
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[AIMessageChunk]:
+ if not self._should_stream(async_api=True, **{**kwargs, "stream": True}):
+ # No async or sync stream is implemented, so fall back to ainvoke
+ yield cast(
+ "AIMessageChunk",
+ await self.ainvoke(input, config=config, stop=stop, **kwargs),
+ )
+ return
+
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = await callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ chunks: list[ChatGenerationChunk] = []
+
+ try:
+ input_messages = _normalize_messages(messages)
+ run_id = "-".join((LC_ID_PREFIX, str(run_manager.run_id)))
+ yielded = False
+ index = -1
+ index_type = ""
+ async for chunk in self._astream(
+ input_messages,
+ stop=stop,
+ **kwargs,
+ ):
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ await run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yield cast("AIMessageChunk", chunk.message)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ msg_chunk = AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ await run_manager.on_llm_new_token(
+ "", chunk=ChatGenerationChunk(message=msg_chunk)
+ )
+ yield msg_chunk
+ except BaseException as e:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ chat_generation_chunk = merge_chat_generation_chunks(chunks)
+ if chat_generation_chunk:
+ generations = [[chat_generation_chunk], generations_with_error_metadata]
+ else:
+ generations = [generations_with_error_metadata]
+ await run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=generations),
+ )
+ raise
+
+ generation = merge_chat_generation_chunks(chunks)
+ if not generation:
+ err = ValueError("No generation chunks were returned")
+ await run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ await run_manager.on_llm_end(
+ LLMResult(generations=[[generation]]),
+ )
+
+ # --- stream_events v3 ---
+
+ @beta()
+ def _chat_model_stream_v3(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream:
+ """Internal v3 sync streaming implementation.
+
+ Public entry point: `stream_events(version='v3')`.
+ """
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ input_messages = _normalize_messages(messages)
+
+ # Strip tracing-only kwargs before forwarding to `_stream` — matches
+ # `stream()` / `astream()`. Provider clients reject unknown kwargs,
+ # so `.with_structured_output().stream_events(version="v3", ...)`
+ # and any other binding that carries `ls_structured_output_format`
+ # / `structured_output_format` would raise without this pop.
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ stream = ChatModelStream()
+ run_manager: CallbackManagerForLLMRun | None = None
+ event_iter_ref: Iterator[MessagesData] | None = None
+ rate_limiter_acquired = self.rate_limiter is None
+ run_name = config.get("run_name")
+ run_id = config.pop("run_id", None)
+
+ def ensure_started() -> None:
+ nonlocal event_iter_ref, run_manager
+ if event_iter_ref is not None:
+ return
+
+ (run_manager,) = callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=1,
+ )
+ stream.set_message_id("-".join((LC_ID_PREFIX, str(run_manager.run_id))))
+ event_iter_ref = iter(
+ self._iter_v2_events(
+ input_messages,
+ run_manager=run_manager,
+ stream=stream,
+ stop=stop,
+ **kwargs,
+ )
+ )
+
+ def pump_one() -> bool:
+ nonlocal rate_limiter_acquired
+ ensure_started()
+ if not rate_limiter_acquired:
+ assert self.rate_limiter is not None # noqa: S101
+ self.rate_limiter.acquire(blocking=True)
+ rate_limiter_acquired = True
+ assert event_iter_ref is not None # noqa: S101
+ assert run_manager is not None # noqa: S101
+ try:
+ next(event_iter_ref)
+ except StopIteration:
+ if not stream.done:
+ if stream.has_events:
+ # Native event producers may omit the terminal
+ # `message-finish`. Close the lifecycle here so
+ # `on_llm_end` still observes the assembled
+ # message. A truly empty stream remains an error
+ # for parity with `stream()`.
+ stream.dispatch(MessageFinishData(event="message-finish"))
+ else:
+ err = ValueError("No generation chunks were returned")
+ stream.fail(err)
+ run_manager.on_llm_error(
+ err,
+ response=LLMResult(generations=[]),
+ )
+ return False
+ if stream.done and stream.output_message is not None:
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ return False
+ except BaseException as exc:
+ stream.fail(exc)
+ run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+ return False
+ if stream.done and stream.output_message is not None:
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ return True
+
+ stream.set_start(ensure_started)
+ stream.bind_pump(pump_one)
+ return stream
+
+ @beta()
+ async def _achat_model_stream_v3(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncChatModelStream:
+ """Internal v3 async streaming implementation.
+
+ Public entry point: `astream_events(version='v3')`.
+ """
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ input_messages = _normalize_messages(messages)
+
+ # Strip tracing-only kwargs before forwarding — see the sync v3
+ # implementation for the full rationale.
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ stream = AsyncChatModelStream()
+ run_manager: AsyncCallbackManagerForLLMRun | None = None
+ run_name = config.get("run_name")
+ run_id = config.pop("run_id", None)
+ start_lock = asyncio.Lock()
+
+ async def _produce() -> None:
+ assert run_manager is not None # noqa: S101
+ try:
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ async for _event in self._aiter_v2_events(
+ input_messages,
+ run_manager=run_manager,
+ stream=stream,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if not stream.done:
+ if stream.has_events:
+ # Native event producers may omit the terminal
+ # `message-finish`. Close the lifecycle here so
+ # `on_llm_end` sees the finalized message. A
+ # truly empty stream remains an error for parity
+ # with `astream()`.
+ stream.dispatch(MessageFinishData(event="message-finish"))
+ else:
+ err = ValueError("No generation chunks were returned")
+ stream.fail(err)
+ await run_manager.on_llm_error(
+ err,
+ response=LLMResult(generations=[]),
+ )
+ return
+ if stream.done and stream.output_message is not None:
+ await run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ except asyncio.CancelledError as exc:
+ stream.fail(exc)
+ # Close the callback lifecycle so tracing observes a
+ # matching end event for the earlier `on_chat_model_start`.
+ # `on_llm_error` is `@shielded`, so the callback runs to
+ # completion in the background even though the `await`
+ # here re-raises our cancellation.
+ with contextlib.suppress(Exception):
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+ raise
+ except BaseException as exc:
+ stream.fail(exc)
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+
+ async def ensure_started() -> None:
+ nonlocal run_manager
+ if stream._producer_task is not None: # noqa: SLF001
+ return
+
+ async with start_lock:
+ if stream._producer_task is not None: # noqa: SLF001
+ return
+
+ (run_manager,) = await callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=1,
+ )
+ stream.set_message_id("-".join((LC_ID_PREFIX, str(run_manager.run_id))))
+ stream._producer_task = asyncio.get_running_loop().create_task( # noqa: SLF001
+ _produce()
+ )
+
+ async def _on_aclose_fail(exc: BaseException) -> None:
+ assert run_manager is not None # noqa: S101
+ # Invoked by `stream.aclose()` only when the producer was
+ # cancelled before `_produce` ran — so `on_llm_error` from
+ # the CancelledError handler never fired. Shielded by the
+ # callback manager; runs to completion even if our caller
+ # is being cancelled.
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+
+ stream.set_start(ensure_started)
+ stream._on_aclose_fail = _on_aclose_fail # noqa: SLF001
+ return stream
+
+ @overload # type: ignore[override]
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream: ...
+
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | ChatModelStream:
+ """Stream events from this chat model.
+
+ For `version="v1"` / `"v2"`, yields `StreamEvent` dicts (see
+ `Runnable.stream_events`). For `version="v3"`, returns a
+ `ChatModelStream` exposing typed projections (`.text`,
+ `.reasoning`, `.tool_calls`, `.output`).
+
+ !!! warning "Beta"
+
+ `version="v3"` is in beta. The protocol shape, return type,
+ and surface area may change in future releases. Calling it
+ emits a `LangChainBetaWarning` at runtime.
+
+ !!! note "v3 always produces v1-shaped content"
+
+ `ChatModelStream.output.content` is always a list of v1
+ content blocks (text / reasoning / tool_call / image / …),
+ regardless of the model's `output_version` attribute. The
+ setting only affects the legacy `stream()` / `astream()` /
+ `invoke()` paths. If you're mixing
+ `stream_events(version="v3")` with those paths in the same
+ pipeline and need a consistent output shape across them,
+ set `output_version="v1"` on the model.
+
+ Args:
+ input: The model input.
+ config: Optional runnable config.
+ version: Streaming-event schema version. `"v3"` selects the
+ content-block-centric streaming protocol.
+ stop: Optional stop sequences. Only used for `version="v3"`;
+ ignored otherwise.
+ **kwargs: Additional keyword arguments. For `version="v3"`,
+ forwarded to the model.
+
+ Returns:
+ For `version="v3"`, a `ChatModelStream` with typed
+ projections. Otherwise an `Iterator[StreamEvent]`.
+ """
+ if version == "v3":
+ return self._chat_model_stream_v3(input, config, stop=stop, **kwargs)
+ return super().stream_events(
+ input, config, version=version, stop=stop, **kwargs
+ )
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[AsyncChatModelStream]: ...
+
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]:
+ """Async variant of `stream_events`. See `stream_events` for full docs."""
+ if version == "v3":
+ return self._achat_model_stream_v3(input, config, stop=stop, **kwargs)
+ # v1/v2: forward to Runnable.astream_events (async generator).
+ return super().astream_events(
+ input, config, version=version, stop=stop, **kwargs
+ )
+
+ # --- Custom methods ---
+
+ def _combine_llm_outputs(self, _llm_outputs: list[dict | None], /) -> dict:
+ return {}
+
+ def _convert_cached_generations(self, cache_val: list) -> list[ChatGeneration]:
+ """Convert cached Generation objects to ChatGeneration objects.
+
+ Handle case where cache contains Generation objects instead of
+ ChatGeneration objects. This can happen due to serialization/deserialization
+ issues or legacy cache data (see #22389).
+
+ Args:
+ cache_val: List of cached generation objects.
+
+ Returns:
+ List of ChatGeneration objects.
+
+ """
+ converted_generations = []
+ for gen in cache_val:
+ if isinstance(gen, Generation) and not isinstance(gen, ChatGeneration):
+ # Convert Generation to ChatGeneration by creating AIMessage
+ # from the text content
+ chat_gen = ChatGeneration(
+ message=AIMessage(content=gen.text),
+ generation_info=gen.generation_info,
+ )
+ converted_generations.append(chat_gen)
+ else:
+ # Already a ChatGeneration or other expected type
+ if hasattr(gen, "message") and isinstance(gen.message, AIMessage):
+ # We zero out cost on cache hits
+ gen.message = gen.message.model_copy(
+ update={
+ "usage_metadata": {
+ **(gen.message.usage_metadata or {}),
+ "total_cost": 0,
+ }
+ }
+ )
+ converted_generations.append(gen)
+ return converted_generations
+
+ def _replay_v2_events_for_cache_hit(
+ self,
+ generations: list[ChatGeneration],
+ *,
+ run_manager: CallbackManagerForLLMRun | None,
+ **kwargs: Any,
+ ) -> None:
+ """Replay cached messages as v2 events when a v2 handler is attached.
+
+ A warm cache must produce the same `on_stream_event` stream as a
+ cold call so LangGraph-style consumers do not observe behavior
+ that depends on cache state. Gated by
+ `_should_use_protocol_streaming` so a `disable_streaming` config
+ that suppresses v2 on cold calls also suppresses it here.
+ """
+ if run_manager is None or not self._should_use_protocol_streaming(
+ async_api=False, run_manager=run_manager, **kwargs
+ ):
+ return
+ message_id = f"{LC_ID_PREFIX}-{run_manager.run_id}"
+ for gen in generations:
+ msg = getattr(gen, "message", None)
+ if not isinstance(msg, AIMessage):
+ continue
+ for event in message_to_events(msg, message_id=message_id):
+ run_manager.on_stream_event(event)
+
+ async def _areplay_v2_events_for_cache_hit(
+ self,
+ generations: list[ChatGeneration],
+ *,
+ run_manager: AsyncCallbackManagerForLLMRun | None,
+ **kwargs: Any,
+ ) -> None:
+ """Async counterpart to `_replay_v2_events_for_cache_hit`."""
+ if run_manager is None or not self._should_use_protocol_streaming(
+ async_api=True, run_manager=run_manager, **kwargs
+ ):
+ return
+ message_id = f"{LC_ID_PREFIX}-{run_manager.run_id}"
+ for gen in generations:
+ msg = getattr(gen, "message", None)
+ if not isinstance(msg, AIMessage):
+ continue
+ async for event in amessage_to_events(msg, message_id=message_id):
+ await run_manager.on_stream_event(event)
+
+ def _get_invocation_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> dict:
+ params = self.dict()
+ params["stop"] = stop
+ return {**params, **kwargs}
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ # get default provider from class name
+ default_provider = self.__class__.__name__
+ if default_provider.startswith("Chat"):
+ default_provider = default_provider[4:].lower()
+ elif default_provider.endswith("Chat"):
+ default_provider = default_provider[:-4]
+ default_provider = default_provider.lower()
+
+ ls_params = LangSmithParams(ls_provider=default_provider, ls_model_type="chat")
+ if stop:
+ ls_params["ls_stop"] = stop
+
+ # model
+ if "model" in kwargs and isinstance(kwargs["model"], str):
+ ls_params["ls_model_name"] = kwargs["model"]
+ elif hasattr(self, "model") and isinstance(self.model, str):
+ ls_params["ls_model_name"] = self.model
+ elif hasattr(self, "model_name") and isinstance(self.model_name, str):
+ ls_params["ls_model_name"] = self.model_name
+
+ # temperature
+ if "temperature" in kwargs and isinstance(kwargs["temperature"], (int, float)):
+ ls_params["ls_temperature"] = kwargs["temperature"]
+ elif hasattr(self, "temperature") and isinstance(
+ self.temperature, (int, float)
+ ):
+ ls_params["ls_temperature"] = self.temperature
+
+ # max_tokens
+ if "max_tokens" in kwargs and isinstance(kwargs["max_tokens"], int):
+ ls_params["ls_max_tokens"] = kwargs["max_tokens"]
+ elif hasattr(self, "max_tokens") and isinstance(self.max_tokens, int):
+ ls_params["ls_max_tokens"] = self.max_tokens
+
+ return ls_params
+
+ def _get_ls_params_with_defaults(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Wrap _get_ls_params to always include ls_integration."""
+ ls_params = self._get_ls_params(stop=stop, **kwargs)
+ ls_params["ls_integration"] = "langchain_chat_model"
+ return ls_params
+
+ def _get_llm_string(self, stop: list[str] | None = None, **kwargs: Any) -> str:
+ if self.is_lc_serializable():
+ params = {**kwargs, "stop": stop}
+ param_string = str(sorted(params.items()))
+ # This code is not super efficient as it goes back and forth between
+ # json and dict.
+ serialized_repr = self._serialized
+ _cleanup_llm_representation(serialized_repr, 1)
+ llm_string = json.dumps(serialized_repr, sort_keys=True)
+ return llm_string + "---" + param_string
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ params = {**params, **kwargs}
+ return str(sorted(params.items()))
+
+ def generate(
+ self,
+ messages: list[list[BaseMessage]],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to the model and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ messages: List of list of messages.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+
+ """
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+
+ callback_manager = CallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose,
+ tags,
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ messages_to_trace = [
+ _format_for_tracing(message_list) for message_list in messages
+ ]
+ run_managers = callback_manager.on_chat_model_start(
+ self._serialized,
+ messages_to_trace,
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=len(messages),
+ )
+ results = []
+ input_messages = [
+ _normalize_messages(message_list) for message_list in messages
+ ]
+ for i, m in enumerate(input_messages):
+ try:
+ results.append(
+ self._generate_with_cache(
+ m,
+ stop=stop,
+ run_manager=run_managers[i] if run_managers else None,
+ **kwargs,
+ )
+ )
+ except BaseException as e:
+ if run_managers:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ run_managers[i].on_llm_error(
+ e,
+ response=LLMResult(
+ generations=[generations_with_error_metadata]
+ ),
+ )
+ raise
+ flattened_outputs = [
+ LLMResult(generations=[res.generations], llm_output=res.llm_output)
+ for res in results
+ ]
+ llm_output = self._combine_llm_outputs([res.llm_output for res in results])
+ generations = [res.generations for res in results]
+ output = LLMResult(generations=generations, llm_output=llm_output)
+ if run_managers:
+ run_infos = []
+ for manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ ):
+ manager.on_llm_end(flattened_output)
+ run_infos.append(RunInfo(run_id=manager.run_id))
+ output.run = run_infos
+ return output
+
+ async def agenerate(
+ self,
+ messages: list[list[BaseMessage]],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ messages: List of list of messages.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+
+ """
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+
+ callback_manager = AsyncCallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose,
+ tags,
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+
+ messages_to_trace = [
+ _format_for_tracing(message_list) for message_list in messages
+ ]
+ run_managers = await callback_manager.on_chat_model_start(
+ self._serialized,
+ messages_to_trace,
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(messages),
+ run_id=run_id,
+ )
+
+ input_messages = [
+ _normalize_messages(message_list) for message_list in messages
+ ]
+ results = await asyncio.gather(
+ *[
+ self._agenerate_with_cache(
+ m,
+ stop=stop,
+ run_manager=run_managers[i] if run_managers else None,
+ **kwargs,
+ )
+ for i, m in enumerate(input_messages)
+ ],
+ return_exceptions=True,
+ )
+ exceptions = []
+ for i, res in enumerate(results):
+ if isinstance(res, BaseException):
+ if run_managers:
+ generations_with_error_metadata = _generate_response_from_error(res)
+ await run_managers[i].on_llm_error(
+ res,
+ response=LLMResult(
+ generations=[generations_with_error_metadata]
+ ),
+ )
+ exceptions.append(res)
+ if exceptions:
+ if run_managers:
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[res.generations], # type: ignore[union-attr]
+ llm_output=res.llm_output, # type: ignore[union-attr]
+ )
+ )
+ for run_manager, res in zip(run_managers, results, strict=False)
+ if not isinstance(res, Exception)
+ ]
+ )
+ raise exceptions[0]
+ flattened_outputs = [
+ LLMResult(generations=[res.generations], llm_output=res.llm_output) # type: ignore[union-attr]
+ for res in results
+ ]
+ llm_output = self._combine_llm_outputs([res.llm_output for res in results]) # type: ignore[union-attr]
+ generations = [res.generations for res in results] # type: ignore[union-attr]
+ output = LLMResult(generations=generations, llm_output=llm_output)
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(flattened_output)
+ for run_manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ )
+ ]
+ )
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ @override
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_messages = [p.to_messages() for p in prompts]
+ return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)
+
+ @override
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_messages = [p.to_messages() for p in prompts]
+ return await self.agenerate(
+ prompt_messages, stop=stop, callbacks=callbacks, **kwargs
+ )
+
+ def _generate_with_cache(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_cache = self.cache if isinstance(self.cache, BaseCache) else get_llm_cache()
+ # We should check the cache unless it's explicitly set to False
+ # A None cache means we should use the default global cache
+ # if it's configured.
+ check_cache = self.cache or self.cache is None
+ if check_cache:
+ if llm_cache:
+ llm_string = self._get_llm_string(stop=stop, **kwargs)
+ normalized_messages = [
+ (
+ msg.model_copy(update={"id": None})
+ if getattr(msg, "id", None) is not None
+ else msg
+ )
+ for msg in messages
+ ]
+ prompt = dumps(normalized_messages)
+ cache_val = llm_cache.lookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ converted_generations = self._convert_cached_generations(cache_val)
+ self._replay_v2_events_for_cache_hit(
+ converted_generations,
+ run_manager=run_manager,
+ **kwargs,
+ )
+ return ChatResult(generations=converted_generations)
+ elif self.cache is None:
+ pass
+ else:
+ msg = "Asked to cache, but no cache found at `langchain.cache`."
+ raise ValueError(msg)
+
+ # Apply the rate limiter after checking the cache, since
+ # we usually don't want to rate limit cache lookups, but
+ # we do want to rate limit API requests.
+ if self.rate_limiter:
+ self.rate_limiter.acquire(blocking=True)
+
+ # v2 streaming: preferred over v1 when any attached handler opts in via
+ # `_V2StreamingCallbackHandler`. Drives the protocol event generator
+ # (native or `_stream` compat bridge) through the shared helper so
+ # `on_stream_event` fires per event, then returns a normal `ChatResult`
+ # so caching / `on_llm_end` stay on the existing generate path.
+ if self._should_use_protocol_streaming(
+ async_api=False,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ stream_accum = ChatModelStream(
+ message_id=(
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ )
+ assert run_manager is not None # noqa: S101
+ for _event in self._iter_v2_events(
+ messages,
+ run_manager=run_manager,
+ stream=stream_accum,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if stream_accum.output_message is None:
+ msg = "v2 stream finished without producing a message"
+ raise RuntimeError(msg)
+ result = ChatResult(
+ generations=[ChatGeneration(message=stream_accum.output_message)]
+ )
+ # If stream is not explicitly set, check if implicitly requested by
+ # astream_events() or astream_log(). Bail out if _stream not implemented
+ elif self._should_stream(
+ async_api=False,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ chunks: list[ChatGenerationChunk] = []
+ run_id: str | None = (
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ yielded = False
+ index = -1
+ index_type = ""
+ for chunk in self._stream(messages, stop=stop, **kwargs):
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ if run_manager:
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token("", chunk=chunk)
+ chunks.append(chunk)
+ result = generate_from_stream(iter(chunks))
+ elif inspect.signature(self._generate).parameters.get("run_manager"):
+ result = self._generate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ result = self._generate(messages, stop=stop, **kwargs)
+
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ for generation in result.generations:
+ generation.message = _update_message_content_to_blocks(
+ generation.message, "v1"
+ )
+
+ # Add response metadata to each generation
+ for idx, generation in enumerate(result.generations):
+ if run_manager and generation.message.id is None:
+ generation.message.id = f"{LC_ID_PREFIX}-{run_manager.run_id}-{idx}"
+ generation.message.response_metadata = _gen_info_and_msg_metadata(
+ generation
+ )
+ if len(result.generations) == 1 and result.llm_output is not None:
+ result.generations[0].message.response_metadata = {
+ **result.llm_output,
+ **result.generations[0].message.response_metadata,
+ }
+ if check_cache and llm_cache:
+ llm_cache.update(prompt, llm_string, result.generations)
+ return result
+
+ async def _agenerate_with_cache(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_cache = self.cache if isinstance(self.cache, BaseCache) else get_llm_cache()
+ # We should check the cache unless it's explicitly set to False
+ # A None cache means we should use the default global cache
+ # if it's configured.
+ check_cache = self.cache or self.cache is None
+ if check_cache:
+ if llm_cache:
+ llm_string = self._get_llm_string(stop=stop, **kwargs)
+ normalized_messages = [
+ (
+ msg.model_copy(update={"id": None})
+ if getattr(msg, "id", None) is not None
+ else msg
+ )
+ for msg in messages
+ ]
+ prompt = dumps(normalized_messages)
+ cache_val = await llm_cache.alookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ converted_generations = self._convert_cached_generations(cache_val)
+ await self._areplay_v2_events_for_cache_hit(
+ converted_generations,
+ run_manager=run_manager,
+ **kwargs,
+ )
+ return ChatResult(generations=converted_generations)
+ elif self.cache is None:
+ pass
+ else:
+ msg = "Asked to cache, but no cache found at `langchain.cache`."
+ raise ValueError(msg)
+
+ # Apply the rate limiter after checking the cache, since
+ # we usually don't want to rate limit cache lookups, but
+ # we do want to rate limit API requests.
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ # v2 streaming: see sync counterpart in `_generate_with_cache`.
+ if self._should_use_protocol_streaming(
+ async_api=True,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ stream_accum = AsyncChatModelStream(
+ message_id=(
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ )
+ assert run_manager is not None # noqa: S101
+ async for _event in self._aiter_v2_events(
+ messages,
+ run_manager=run_manager,
+ stream=stream_accum,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if stream_accum.output_message is None:
+ msg = "v2 stream finished without producing a message"
+ raise RuntimeError(msg)
+ result = ChatResult(
+ generations=[ChatGeneration(message=stream_accum.output_message)]
+ )
+ # If stream is not explicitly set, check if implicitly requested by
+ # astream_events() or astream_log(). Bail out if _astream not implemented
+ elif self._should_stream(
+ async_api=True,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ chunks: list[ChatGenerationChunk] = []
+ run_id: str | None = (
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ yielded = False
+ index = -1
+ index_type = ""
+ async for chunk in self._astream(messages, stop=stop, **kwargs):
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ if run_manager:
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ await run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token("", chunk=chunk)
+ chunks.append(chunk)
+ result = generate_from_stream(iter(chunks))
+ elif inspect.signature(self._agenerate).parameters.get("run_manager"):
+ result = await self._agenerate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ result = await self._agenerate(messages, stop=stop, **kwargs)
+
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ for generation in result.generations:
+ generation.message = _update_message_content_to_blocks(
+ generation.message, "v1"
+ )
+
+ # Add response metadata to each generation
+ for idx, generation in enumerate(result.generations):
+ if run_manager and generation.message.id is None:
+ generation.message.id = f"{LC_ID_PREFIX}-{run_manager.run_id}-{idx}"
+ generation.message.response_metadata = _gen_info_and_msg_metadata(
+ generation
+ )
+ if len(result.generations) == 1 and result.llm_output is not None:
+ result.generations[0].message.response_metadata = {
+ **result.llm_output,
+ **result.generations[0].message.response_metadata,
+ }
+ if check_cache and llm_cache:
+ await llm_cache.aupdate(prompt, llm_string, result.generations)
+ return result
+
+ @abstractmethod
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate the result.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Returns:
+ The chat result.
+ """
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate the result.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Returns:
+ The chat result.
+ """
+ return await run_in_executor(
+ None,
+ self._generate,
+ messages,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream the output of the model.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Yields:
+ The chat generation chunks.
+ """
+ raise NotImplementedError
+
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ """Stream the output of the model.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Yields:
+ The chat generation chunks.
+ """
+ iterator = await run_in_executor(
+ None,
+ self._stream,
+ messages,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+ done = object()
+ while True:
+ item = await run_in_executor(
+ None,
+ next,
+ iterator,
+ done,
+ )
+ if item is done:
+ break
+ yield item # type: ignore[misc]
+
+ async def _call_async(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> BaseMessage:
+ result = await self.agenerate(
+ [messages], stop=stop, callbacks=callbacks, **kwargs
+ )
+ generation = result.generations[0][0]
+ if isinstance(generation, ChatGeneration):
+ return generation.message
+ msg = "Unexpected generation type"
+ raise ValueError(msg)
+
+ @property
+ @abstractmethod
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+
+ @override
+ def dict(self, **kwargs: Any) -> dict:
+ """Return a dictionary of the LLM."""
+ starter_dict = dict(self._identifying_params)
+ starter_dict["_type"] = self._llm_type
+ return starter_dict
+
+ @override
+ def bind(self, **kwargs: Any) -> _ChatModelBinding:
+ """Bind kwargs to this chat model, returning a typed `_ChatModelBinding`.
+
+ Overrides `Runnable.bind` so the result preserves chat-model-specific
+ `stream_events` / `astream_events` overloads. Without this override,
+ `model.bind(...).stream_events(version="v3")` would type as
+ `Iterator[Any]` and `await model.bind(...).astream_events(version="v3")`
+ as `Any`, forcing callers to `cast`.
+ """
+ return _ChatModelBinding(bound=self, kwargs=kwargs, config={})
+
+ def bind_tools(
+ self,
+ tools: Sequence[builtins.dict[str, Any] | type | Callable | BaseTool],
+ *,
+ tool_choice: str | None = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tools to the model.
+
+ Args:
+ tools: Sequence of tools to bind to the model.
+ tool_choice: The tool to use. If "any" then any tool can be used.
+
+ Returns:
+ A Runnable that returns a message.
+
+ """
+ raise NotImplementedError
+
+ def with_structured_output(
+ self,
+ schema: builtins.dict[str, Any] | type,
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, builtins.dict[str, Any] | BaseModel]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema. Can be passed in as:
+
+ - An OpenAI function/tool schema,
+ - A JSON Schema,
+ - A `TypedDict` class,
+ - Or a Pydantic class.
+
+ If `schema` is a Pydantic class then the model output will be a
+ Pydantic instance of that class, and the model-generated fields will be
+ validated by the Pydantic class. Otherwise the model output will be a
+ dict and will not be validated.
+
+ See `langchain_core.utils.function_calling.convert_to_openai_tool` for
+ more on how to properly specify types and descriptions of schema fields
+ when specifying a Pydantic or `TypedDict` class.
+
+ include_raw:
+ If `False` then only the parsed structured output is returned.
+
+ If an error occurs during model output parsing it will be raised.
+
+ If `True` then both the raw model response (a `BaseMessage`) and the
+ parsed model response will be returned.
+
+ If an error occurs during output parsing it will be caught and returned
+ as well.
+
+ The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
+ `'parsing_error'`.
+
+ Raises:
+ ValueError: If there are any unsupported `kwargs`.
+ NotImplementedError: If the model does not implement
+ `with_structured_output()`.
+
+ Returns:
+ A `Runnable` that takes same inputs as a
+ `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
+ `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
+ of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
+ `False` then `Runnable` outputs a `dict`.
+
+ If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:
+
+ - `'raw'`: `BaseMessage`
+ - `'parsed'`: `None` if there was a parsing error, otherwise the type
+ depends on the `schema` as described above.
+ - `'parsing_error'`: `BaseException | None`
+
+ ???+ example "Pydantic schema (`include_raw=False`)"
+
+ ```python
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(AnswerWithJustification)
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
+ # )
+ ```
+
+ ??? example "Pydantic schema (`include_raw=True`)"
+
+ ```python
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(
+ AnswerWithJustification, include_raw=True
+ )
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
+ # 'parsing_error': None
+ # }
+ ```
+
+ ??? example "Dictionary schema (`include_raw=False`)"
+
+ ```python
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(dict_schema)
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
+ # }
+ ```
+
+ !!! warning "Behavior changed in `langchain-core` 0.2.26"
+
+ Added support for `TypedDict` class.
+
+ """ # noqa: E501
+ _ = kwargs.pop("method", None)
+ _ = kwargs.pop("strict", None)
+ if kwargs:
+ msg = f"Received unsupported arguments {kwargs}"
+ raise ValueError(msg)
+
+ if type(self).bind_tools is BaseChatModel.bind_tools:
+ msg = "with_structured_output is not implemented for this model."
+ raise NotImplementedError(msg)
+
+ llm = self.bind_tools(
+ [schema],
+ tool_choice="any",
+ ls_structured_output_format={
+ "kwargs": {"method": "function_calling"},
+ "schema": schema,
+ },
+ )
+ if isinstance(schema, type) and is_basemodel_subclass(schema):
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[cast("TypeBaseModel", schema)], first_tool_only=True
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ return llm | output_parser
+
+
+class _ChatModelBinding(RunnableBinding[LanguageModelInput, AIMessage]): # type: ignore[no-redef]
+ """`RunnableBinding` that preserves chat-model-typed v3 overloads.
+
+ Returned by `BaseChatModel.bind` so that callers of the bound runnable's
+ `stream_events(version="v3")` / `astream_events(version="v3")` get the
+ typed `ChatModelStream` / `AsyncChatModelStream` back without needing
+ `cast`. At runtime this is a plain `RunnableBinding`; the subclass
+ exists purely to give the type checker a more specific surface.
+
+ The chat-model narrowing is preserved across further `bind` /
+ `with_config` calls because `RunnableBinding.bind` constructs its
+ result via `self.__class__(...)`.
+ """
+
+ @classmethod
+ @override
+ def lc_id(cls) -> list[str]:
+ """Serialize as `RunnableBinding`.
+
+ At runtime this class is behaviorally identical to `RunnableBinding`;
+ keeping the serialized id stable means existing snapshots and the
+ load mapping continue to work without registering a new entry.
+ """
+ return [*cls.get_lc_namespace(), "RunnableBinding"]
+
+ @overload # type: ignore[override]
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream: ...
+
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | ChatModelStream:
+ return super().stream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[AsyncChatModelStream]: ...
+
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]:
+ return cast(
+ "AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]",
+ super().astream_events(input, config, **kwargs),
+ )
+
+
+class SimpleChatModel(BaseChatModel):
+ """Simplified implementation for a chat model to inherit from.
+
+ !!! note
+ This implementation is primarily here for backwards compatibility. For new
+ implementations, please use `BaseChatModel` directly.
+
+ """
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @abstractmethod
+ def _call(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Simpler interface."""
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ return await run_in_executor(
+ None,
+ self._generate,
+ messages,
+ stop=stop,
+ run_manager=run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+
+def _gen_info_and_msg_metadata(
+ generation: ChatGeneration | ChatGenerationChunk,
+) -> dict:
+ return {
+ **(generation.generation_info or {}),
+ **generation.message.response_metadata,
+ }
+
+
+_MAX_CLEANUP_DEPTH = 100
+
+
+def _cleanup_llm_representation(serialized: Any, depth: int) -> None:
+ """Remove non-serializable objects from a serialized object."""
+ if depth > _MAX_CLEANUP_DEPTH: # Don't cooperate for pathological cases
+ return
+
+ if not isinstance(serialized, dict):
+ return
+
+ if (
+ "type" in serialized
+ and serialized["type"] == "not_implemented"
+ and "repr" in serialized
+ ):
+ del serialized["repr"]
+
+ if "graph" in serialized:
+ del serialized["graph"]
+
+ if "kwargs" in serialized:
+ kwargs = serialized["kwargs"]
+
+ for value in kwargs.values():
+ _cleanup_llm_representation(value, depth + 1)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/fake.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..77b7cdd4ac66a6ed13f01df0b5d1bdb723babe75
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/fake.py
@@ -0,0 +1,137 @@
+"""Fake LLMs for testing purposes."""
+
+import asyncio
+import time
+from collections.abc import AsyncIterator, Iterator, Mapping
+from typing import Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.llms import LLM
+from langchain_core.runnables import RunnableConfig
+
+
+class FakeListLLM(LLM):
+ """Fake LLM for testing purposes."""
+
+ responses: list[str]
+ """List of responses to return in order."""
+ # This parameter should be removed from FakeListLLM since
+ # it's only used by sub-classes.
+ sleep: float | None = None
+ """Sleep time in seconds between responses.
+
+ Ignored by FakeListLLM, but used by sub-classes.
+ """
+ i: int = 0
+ """Internally incremented after every model invocation.
+
+ Useful primarily for testing purposes.
+ """
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "fake-list"
+
+ @override
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Return next response."""
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @override
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Return next response."""
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @property
+ @override
+ def _identifying_params(self) -> Mapping[str, Any]:
+ return {"responses": self.responses}
+
+
+class FakeListLLMError(Exception):
+ """Fake error for testing purposes."""
+
+
+class FakeStreamingListLLM(FakeListLLM):
+ """Fake streaming list LLM for testing purposes.
+
+ An LLM that will return responses from a list in order.
+
+ This model also supports optionally sleeping between successive
+ chunks in a streaming implementation.
+ """
+
+ error_on_chunk_number: int | None = None
+ """If set, will raise an exception on the specified chunk number."""
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[str]:
+ result = self.invoke(input, config)
+ for i_c, c in enumerate(result):
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListLLMError
+ yield c
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[str]:
+ result = await self.ainvoke(input, config)
+ for i_c, c in enumerate(result):
+ if self.sleep is not None:
+ await asyncio.sleep(self.sleep)
+
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListLLMError
+ yield c
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/fake_chat_models.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/fake_chat_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..12e5a73fdf5121e53f79bae5e4639abbae7f03ad
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/fake_chat_models.py
@@ -0,0 +1,396 @@
+"""Fake chat models for testing purposes."""
+
+import asyncio
+import re
+import time
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, Literal, cast
+
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
+from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import RunnableConfig
+
+
+class FakeMessagesListChatModel(BaseChatModel):
+ """Fake chat model for testing purposes."""
+
+ responses: list[BaseMessage]
+ """List of responses to **cycle** through in order."""
+ sleep: float | None = None
+ """Sleep time in seconds between responses."""
+ i: int = 0
+ """Internally incremented after every model invocation."""
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ generation = ChatGeneration(message=response)
+ return ChatResult(generations=[generation])
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ return "fake-messages-list-chat-model"
+
+
+class FakeListChatModelError(Exception):
+ """Fake error for testing purposes."""
+
+
+class FakeListChatModel(SimpleChatModel):
+ """Fake chat model for testing purposes."""
+
+ responses: list[str]
+ """List of responses to **cycle** through in order."""
+ sleep: float | None = None
+ i: int = 0
+ """Internally incremented after every model invocation."""
+ error_on_chunk_number: int | None = None
+ """If set, raise an error on the specified chunk number during streaming."""
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ return "fake-list-chat-model"
+
+ @override
+ def _call(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> str:
+ """Return the next response in the list.
+
+ Cycle back to the start if at the end.
+ """
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @override
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for i_c, c in enumerate(response):
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListChatModelError
+
+ chunk_position: Literal["last"] | None = (
+ "last" if i_c == len(response) - 1 else None
+ )
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content=c, chunk_position=chunk_position)
+ )
+
+ @override
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for i_c, c in enumerate(response):
+ if self.sleep is not None:
+ await asyncio.sleep(self.sleep)
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListChatModelError
+ chunk_position: Literal["last"] | None = (
+ "last" if i_c == len(response) - 1 else None
+ )
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content=c, chunk_position=chunk_position)
+ )
+
+ @property
+ @override
+ def _identifying_params(self) -> dict[str, Any]:
+ return {"responses": self.responses}
+
+ @override
+ # manually override batch to preserve batch ordering with no concurrency
+ def batch(
+ self,
+ inputs: list[Any],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[AIMessage]:
+ if isinstance(config, list):
+ return [
+ self.invoke(m, c, **kwargs)
+ for m, c in zip(inputs, config, strict=False)
+ ]
+ return [self.invoke(m, config, **kwargs) for m in inputs]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Any],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[AIMessage]:
+ if isinstance(config, list):
+ # do Not use an async iterator here because need explicit ordering
+ return [
+ await self.ainvoke(m, c, **kwargs)
+ for m, c in zip(inputs, config, strict=False)
+ ]
+ # do Not use an async iterator here because need explicit ordering
+ return [await self.ainvoke(m, config, **kwargs) for m in inputs]
+
+
+class FakeChatModel(SimpleChatModel):
+ """Fake Chat Model wrapper for testing purposes."""
+
+ @override
+ def _call(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ return "fake response"
+
+ @override
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = "fake response"
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "fake-chat-model"
+
+ @property
+ def _identifying_params(self) -> dict[str, Any]:
+ return {"key": "fake"}
+
+
+class GenericFakeChatModel(BaseChatModel):
+ """Generic fake chat model that can be used to test the chat model interface.
+
+ * Chat model should be usable in both sync and async tests
+ * Invokes `on_llm_new_token` to allow for testing of callback related code for new
+ tokens.
+ * Includes logic to break messages into message chunk to facilitate testing of
+ streaming.
+
+ """
+
+ messages: Iterator[AIMessage | str]
+ """Get an iterator over messages.
+
+ This can be expanded to accept other types like Callables / dicts / strings
+ to make the interface more generic if needed.
+
+ !!! note
+ if you want to pass a list, you can use `iter` to convert it to an iterator.
+
+ !!! warning
+ Streaming is not implemented yet. We should try to implement it in the future by
+ delegating to invoke and then breaking the resulting output into message chunks.
+
+ """
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message = next(self.messages)
+ message_ = AIMessage(content=message) if isinstance(message, str) else message
+ generation = ChatGeneration(message=message_)
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ chat_result = self._generate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ if not isinstance(chat_result, ChatResult):
+ msg = (
+ f"Expected generate to return a ChatResult, "
+ f"but got {type(chat_result)} instead."
+ )
+ raise ValueError(msg) # noqa: TRY004
+
+ message = chat_result.generations[0].message
+
+ if not isinstance(message, AIMessage):
+ msg = (
+ f"Expected invoke to return an AIMessage, "
+ f"but got {type(message)} instead."
+ )
+ raise ValueError(msg) # noqa: TRY004
+
+ content = message.content
+
+ if content:
+ # Use a regular expression to split on whitespace with a capture group
+ # so that we can preserve the whitespace in the output.
+ if not isinstance(content, str):
+ msg = "Expected content to be a string."
+ raise ValueError(msg)
+
+ content_chunks = cast("list[str]", re.split(r"(\s)", content))
+
+ for idx, token in enumerate(content_chunks):
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=token, id=message.id)
+ )
+ if (
+ idx == len(content_chunks) - 1
+ and isinstance(chunk.message, AIMessageChunk)
+ and not message.additional_kwargs
+ ):
+ chunk.message.chunk_position = "last"
+ if run_manager:
+ run_manager.on_llm_new_token(token, chunk=chunk)
+ yield chunk
+
+ if message.additional_kwargs:
+ for key, value in message.additional_kwargs.items():
+ # We should further break down the additional kwargs into chunks
+ # Special case for function call
+ if key == "function_call":
+ for fkey, fvalue in value.items():
+ if isinstance(fvalue, str):
+ # Break function call by `,`
+ fvalue_chunks = cast("list[str]", re.split(r"(,)", fvalue))
+ for fvalue_chunk in fvalue_chunks:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id,
+ content="",
+ additional_kwargs={
+ "function_call": {fkey: fvalue_chunk}
+ },
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+ else:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id,
+ content="",
+ additional_kwargs={"function_call": {fkey: fvalue}},
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+ else:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id, content="", additional_kwargs={key: value}
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+
+ @property
+ def _llm_type(self) -> str:
+ return "generic-fake-chat-model"
+
+
+class ParrotFakeChatModel(BaseChatModel):
+ """Generic fake chat model that can be used to test the chat model interface.
+
+ * Chat model should be usable in both sync and async tests
+
+ """
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if not messages:
+ msg = "messages list cannot be empty."
+ raise ValueError(msg)
+ return ChatResult(generations=[ChatGeneration(message=messages[-1])])
+
+ @property
+ def _llm_type(self) -> str:
+ return "parrot-fake-chat-model"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/llms.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/llms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ace9cb554a151f69b7b6fc411bf73ba09bff6eb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/llms.py
@@ -0,0 +1,1553 @@
+"""Base interface for traditional large language models (LLMs) to expose.
+
+These are traditionally older models (newer models generally are chat models).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import inspect
+import json
+import logging
+from abc import ABC, abstractmethod
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from pathlib import Path
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+import yaml
+from pydantic import ConfigDict
+from tenacity import (
+ RetryCallState,
+ before_sleep_log,
+ retry,
+ retry_base,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+from typing_extensions import override
+
+from langchain_core.caches import BaseCache
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForLLMRun,
+ BaseCallbackManager,
+ CallbackManager,
+ CallbackManagerForLLMRun,
+ Callbacks,
+)
+from langchain_core.globals import get_llm_cache
+from langchain_core.language_models._utils import _filter_invocation_params_for_tracing
+from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+)
+from langchain_core.load import dumpd
+from langchain_core.messages import (
+ convert_to_messages,
+)
+from langchain_core.outputs import Generation, GenerationChunk, LLMResult, RunInfo
+from langchain_core.prompt_values import ChatPromptValue, PromptValue, StringPromptValue
+from langchain_core.runnables import RunnableConfig, ensure_config, get_config_list
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ import uuid
+
+logger = logging.getLogger(__name__)
+
+_background_tasks: set[asyncio.Task] = set()
+
+
+@functools.lru_cache
+def _log_error_once(msg: str) -> None:
+ """Log an error once."""
+ logger.error(msg)
+
+
+def create_base_retry_decorator(
+ error_types: list[type[BaseException]],
+ max_retries: int = 1,
+ run_manager: AsyncCallbackManagerForLLMRun | CallbackManagerForLLMRun | None = None,
+) -> Callable[[Any], Any]:
+ """Create a retry decorator for a given LLM and provided a list of error types.
+
+ Args:
+ error_types: List of error types to retry on.
+ max_retries: Number of retries.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ A retry decorator.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ logging_ = before_sleep_log(logger, logging.WARNING)
+
+ def _before_sleep(retry_state: RetryCallState) -> None:
+ logging_(retry_state)
+ if run_manager:
+ if isinstance(run_manager, AsyncCallbackManagerForLLMRun):
+ coro = run_manager.on_retry(retry_state)
+ try:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ asyncio.run(coro)
+ else:
+ if loop.is_running():
+ task = loop.create_task(coro)
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
+ else:
+ asyncio.run(coro)
+ except Exception as e:
+ _log_error_once(f"Error in on_retry: {e}")
+ else:
+ run_manager.on_retry(retry_state)
+
+ min_seconds = 4
+ max_seconds = 10
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
+ retry_instance: retry_base = retry_if_exception_type(error_types[0])
+ for error in error_types[1:]:
+ retry_instance |= retry_if_exception_type(error)
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=retry_instance,
+ before_sleep=_before_sleep,
+ )
+
+
+def _resolve_cache(*, cache: BaseCache | bool | None) -> BaseCache | None:
+ """Resolve the cache."""
+ llm_cache: BaseCache | None
+ if isinstance(cache, BaseCache):
+ llm_cache = cache
+ elif cache is None:
+ llm_cache = get_llm_cache()
+ elif cache is True:
+ llm_cache = get_llm_cache()
+ if llm_cache is None:
+ msg = (
+ "No global cache was configured. Use `set_llm_cache`."
+ "to set a global cache if you want to use a global cache."
+ "Otherwise either pass a cache object or set cache to False/None"
+ )
+ raise ValueError(msg)
+ elif cache is False:
+ llm_cache = None
+ else:
+ msg = f"Unsupported cache value {cache}"
+ raise ValueError(msg)
+ return llm_cache
+
+
+def get_prompts(
+ params: dict[str, Any],
+ prompts: list[str],
+ cache: BaseCache | bool | None = None, # noqa: FBT001
+) -> tuple[dict[int, list], str, list[int], list[str]]:
+ """Get prompts that are already cached.
+
+ Args:
+ params: Dictionary of parameters.
+ prompts: List of prompts.
+ cache: Cache object.
+
+ Returns:
+ A tuple of existing prompts, llm_string, missing prompt indexes,
+ and missing prompts.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_string = str(sorted(params.items()))
+ missing_prompts = []
+ missing_prompt_idxs = []
+ existing_prompts = {}
+
+ llm_cache = _resolve_cache(cache=cache)
+ for i, prompt in enumerate(prompts):
+ if llm_cache:
+ cache_val = llm_cache.lookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ existing_prompts[i] = cache_val
+ else:
+ missing_prompts.append(prompt)
+ missing_prompt_idxs.append(i)
+ return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts
+
+
+async def aget_prompts(
+ params: dict[str, Any],
+ prompts: list[str],
+ cache: BaseCache | bool | None = None, # noqa: FBT001
+) -> tuple[dict[int, list], str, list[int], list[str]]:
+ """Get prompts that are already cached. Async version.
+
+ Args:
+ params: Dictionary of parameters.
+ prompts: List of prompts.
+ cache: Cache object.
+
+ Returns:
+ A tuple of existing prompts, llm_string, missing prompt indexes,
+ and missing prompts.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_string = str(sorted(params.items()))
+ missing_prompts = []
+ missing_prompt_idxs = []
+ existing_prompts = {}
+ llm_cache = _resolve_cache(cache=cache)
+ for i, prompt in enumerate(prompts):
+ if llm_cache:
+ cache_val = await llm_cache.alookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ existing_prompts[i] = cache_val
+ else:
+ missing_prompts.append(prompt)
+ missing_prompt_idxs.append(i)
+ return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts
+
+
+def update_cache(
+ cache: BaseCache | bool | None, # noqa: FBT001
+ existing_prompts: dict[int, list],
+ llm_string: str,
+ missing_prompt_idxs: list[int],
+ new_results: LLMResult,
+ prompts: list[str],
+) -> dict | None:
+ """Update the cache and get the LLM output.
+
+ Args:
+ cache: Cache object.
+ existing_prompts: Dictionary of existing prompts.
+ llm_string: LLM string.
+ missing_prompt_idxs: List of missing prompt indexes.
+ new_results: LLMResult object.
+ prompts: List of prompts.
+
+ Returns:
+ LLM output.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_cache = _resolve_cache(cache=cache)
+ for i, result in enumerate(new_results.generations):
+ existing_prompts[missing_prompt_idxs[i]] = result
+ prompt = prompts[missing_prompt_idxs[i]]
+ if llm_cache is not None:
+ llm_cache.update(prompt, llm_string, result)
+ return new_results.llm_output
+
+
+async def aupdate_cache(
+ cache: BaseCache | bool | None, # noqa: FBT001
+ existing_prompts: dict[int, list],
+ llm_string: str,
+ missing_prompt_idxs: list[int],
+ new_results: LLMResult,
+ prompts: list[str],
+) -> dict | None:
+ """Update the cache and get the LLM output. Async version.
+
+ Args:
+ cache: Cache object.
+ existing_prompts: Dictionary of existing prompts.
+ llm_string: LLM string.
+ missing_prompt_idxs: List of missing prompt indexes.
+ new_results: LLMResult object.
+ prompts: List of prompts.
+
+ Returns:
+ LLM output.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_cache = _resolve_cache(cache=cache)
+ for i, result in enumerate(new_results.generations):
+ existing_prompts[missing_prompt_idxs[i]] = result
+ prompt = prompts[missing_prompt_idxs[i]]
+ if llm_cache:
+ await llm_cache.aupdate(prompt, llm_string, result)
+ return new_results.llm_output
+
+
+class BaseLLM(BaseLanguageModel[str], ABC):
+ """Base LLM abstract interface.
+
+ It should take in a prompt and return a string.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @functools.cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumps uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ # --- Runnable methods ---
+
+ @property
+ @override
+ def OutputType(self) -> type[str]:
+ """Get the output type for this `Runnable`."""
+ return str
+
+ def _convert_input(self, model_input: LanguageModelInput) -> PromptValue:
+ if isinstance(model_input, PromptValue):
+ return model_input
+ if isinstance(model_input, str):
+ return StringPromptValue(text=model_input)
+ if isinstance(model_input, Sequence):
+ return ChatPromptValue(messages=convert_to_messages(model_input))
+ msg = (
+ f"Invalid input type {type(model_input)}. "
+ "Must be a PromptValue, str, or list of BaseMessages."
+ )
+ raise ValueError(msg)
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ # get default provider from class name
+ default_provider = self.__class__.__name__
+ default_provider = default_provider.removesuffix("LLM")
+ default_provider = default_provider.lower()
+
+ ls_params = LangSmithParams(ls_provider=default_provider, ls_model_type="llm")
+ if stop:
+ ls_params["ls_stop"] = stop
+
+ # model
+ if "model" in kwargs and isinstance(kwargs["model"], str):
+ ls_params["ls_model_name"] = kwargs["model"]
+ elif hasattr(self, "model") and isinstance(self.model, str):
+ ls_params["ls_model_name"] = self.model
+ elif hasattr(self, "model_name") and isinstance(self.model_name, str):
+ ls_params["ls_model_name"] = self.model_name
+
+ # temperature
+ if "temperature" in kwargs and isinstance(kwargs["temperature"], (int, float)):
+ ls_params["ls_temperature"] = kwargs["temperature"]
+ elif hasattr(self, "temperature") and isinstance(
+ self.temperature, (int, float)
+ ):
+ ls_params["ls_temperature"] = self.temperature
+
+ # max_tokens
+ if "max_tokens" in kwargs and isinstance(kwargs["max_tokens"], int):
+ ls_params["ls_max_tokens"] = kwargs["max_tokens"]
+ elif hasattr(self, "max_tokens") and isinstance(self.max_tokens, int):
+ ls_params["ls_max_tokens"] = self.max_tokens
+
+ return ls_params
+
+ @override
+ def invoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ config = ensure_config(config)
+ return (
+ self.generate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ .generations[0][0]
+ .text
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ config = ensure_config(config)
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ return llm_result.generations[0][0].text
+
+ @override
+ def batch(
+ self,
+ inputs: list[LanguageModelInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[str]:
+ if not inputs:
+ return []
+
+ config = get_config_list(config, len(inputs))
+ max_concurrency = config[0].get("max_concurrency")
+
+ if max_concurrency is None:
+ try:
+ llm_result = self.generate_prompt(
+ [self._convert_input(input_) for input_ in inputs],
+ callbacks=[c.get("callbacks") for c in config],
+ tags=[c.get("tags") for c in config],
+ metadata=[c.get("metadata") for c in config],
+ run_name=[c.get("run_name") for c in config],
+ **kwargs,
+ )
+ return [g[0].text for g in llm_result.generations]
+ except Exception as e:
+ if return_exceptions:
+ return cast("list[str]", [e for _ in inputs])
+ raise
+ else:
+ batches = [
+ inputs[i : i + max_concurrency]
+ for i in range(0, len(inputs), max_concurrency)
+ ]
+ config = [{**c, "max_concurrency": None} for c in config]
+ return [
+ output
+ for i, batch in enumerate(batches)
+ for output in self.batch(
+ batch,
+ config=config[i * max_concurrency : (i + 1) * max_concurrency],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+ ]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[LanguageModelInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[str]:
+ if not inputs:
+ return []
+ config = get_config_list(config, len(inputs))
+ max_concurrency = config[0].get("max_concurrency")
+
+ if max_concurrency is None:
+ try:
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input_) for input_ in inputs],
+ callbacks=[c.get("callbacks") for c in config],
+ tags=[c.get("tags") for c in config],
+ metadata=[c.get("metadata") for c in config],
+ run_name=[c.get("run_name") for c in config],
+ **kwargs,
+ )
+ return [g[0].text for g in llm_result.generations]
+ except Exception as e:
+ if return_exceptions:
+ return cast("list[str]", [e for _ in inputs])
+ raise
+ else:
+ batches = [
+ inputs[i : i + max_concurrency]
+ for i in range(0, len(inputs), max_concurrency)
+ ]
+ config = [{**c, "max_concurrency": None} for c in config]
+ return [
+ output
+ for i, batch in enumerate(batches)
+ for output in await self.abatch(
+ batch,
+ config=config[i * max_concurrency : (i + 1) * max_concurrency],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+ ]
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[str]:
+ if type(self)._stream == BaseLLM._stream: # noqa: SLF001
+ # model doesn't implement streaming, so use default implementation
+ yield self.invoke(input, config=config, stop=stop, **kwargs)
+ else:
+ prompt = self._convert_input(input).to_string()
+ config = ensure_config(config)
+ params = self.dict()
+ params["stop"] = stop
+ params = {**params, **kwargs}
+ options = {"stop": stop}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+ generation: GenerationChunk | None = None
+ try:
+ for chunk in self._stream(
+ prompt, stop=stop, run_manager=run_manager, **kwargs
+ ):
+ yield chunk.text
+ if generation is None:
+ generation = chunk
+ else:
+ generation += chunk
+ except BaseException as e:
+ run_manager.on_llm_error(
+ e,
+ response=LLMResult(
+ generations=[[generation]] if generation else []
+ ),
+ )
+ raise
+
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[str]:
+ if (
+ type(self)._astream is BaseLLM._astream # noqa: SLF001
+ and type(self)._stream is BaseLLM._stream # noqa: SLF001
+ ):
+ yield await self.ainvoke(input, config=config, stop=stop, **kwargs)
+ return
+
+ prompt = self._convert_input(input).to_string()
+ config = ensure_config(config)
+ params = self.dict()
+ params["stop"] = stop
+ params = {**params, **kwargs}
+ options = {"stop": stop}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = await callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+ generation: GenerationChunk | None = None
+ try:
+ async for chunk in self._astream(
+ prompt,
+ stop=stop,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ yield chunk.text
+ if generation is None:
+ generation = chunk
+ else:
+ generation += chunk
+ except BaseException as e:
+ await run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=[[generation]] if generation else []),
+ )
+ raise
+
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ await run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ await run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ # --- Custom methods ---
+
+ @abstractmethod
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Run the LLM on the given prompts.
+
+ Args:
+ prompts: The prompts to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ The LLM result.
+ """
+
+ async def _agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Run the LLM on the given prompts.
+
+ Args:
+ prompts: The prompts to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ The LLM result.
+ """
+ return await run_in_executor(
+ None,
+ self._generate,
+ prompts,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ """Stream the LLM on the given prompt.
+
+ This method should be overridden by subclasses that support streaming.
+
+ If not implemented, the default behavior of calls to stream will be to
+ fallback to the non-streaming version of the model and return
+ the output as a single chunk.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Yields:
+ Generation chunks.
+ """
+ raise NotImplementedError
+
+ async def _astream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[GenerationChunk]:
+ """An async version of the _stream method.
+
+ The default implementation uses the synchronous _stream method and wraps it in
+ an async iterator. Subclasses that need to provide a true async implementation
+ should override this method.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Yields:
+ Generation chunks.
+ """
+ iterator = await run_in_executor(
+ None,
+ self._stream,
+ prompt,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+ done = object()
+ while True:
+ item = await run_in_executor(
+ None,
+ next,
+ iterator,
+ done,
+ )
+ if item is done:
+ break
+ yield item # type: ignore[misc]
+
+ @override
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_strings = [p.to_string() for p in prompts]
+ return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)
+
+ @override
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_strings = [p.to_string() for p in prompts]
+ return await self.agenerate(
+ prompt_strings, stop=stop, callbacks=callbacks, **kwargs
+ )
+
+ def _generate_helper(
+ self,
+ prompts: list[str],
+ stop: list[str] | None,
+ run_managers: list[CallbackManagerForLLMRun],
+ *,
+ new_arg_supported: bool,
+ **kwargs: Any,
+ ) -> LLMResult:
+ try:
+ output = (
+ self._generate(
+ prompts,
+ stop=stop,
+ # TODO: support multiple run managers
+ run_manager=run_managers[0] if run_managers else None,
+ **kwargs,
+ )
+ if new_arg_supported
+ else self._generate(prompts, stop=stop)
+ )
+ except BaseException as e:
+ for run_manager in run_managers:
+ run_manager.on_llm_error(e, response=LLMResult(generations=[]))
+ raise
+ flattened_outputs = output.flatten()
+ for manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ ):
+ manager.on_llm_end(flattened_output)
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ def generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ *,
+ tags: list[str] | list[list[str]] | None = None,
+ metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
+ run_name: str | list[str] | None = None,
+ run_id: uuid.UUID | list[uuid.UUID | None] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of string prompts.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: List of tags to associate with each prompt. If provided, the length
+ of the list must match the length of the prompts list.
+ metadata: List of metadata dictionaries to associate with each prompt. If
+ provided, the length of the list must match the length of the prompts
+ list.
+ run_name: List of run names to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ run_id: List of run IDs to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Raises:
+ ValueError: If prompts is not a list.
+ ValueError: If the length of `callbacks`, `tags`, `metadata`, or
+ `run_name` (if provided) does not match the length of prompts.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+ """
+ if not isinstance(prompts, list):
+ msg = (
+ "Argument 'prompts' is expected to be of type list[str], received"
+ f" argument of type {type(prompts)}."
+ )
+ raise ValueError(msg) # noqa: TRY004
+ # Create callback managers
+ if isinstance(metadata, list):
+ metadata = [
+ {
+ **(meta or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ for meta in metadata
+ ]
+ elif isinstance(metadata, dict):
+ metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ if (
+ isinstance(callbacks, list)
+ and callbacks
+ and (
+ isinstance(callbacks[0], (list, BaseCallbackManager))
+ or callbacks[0] is None
+ )
+ ):
+ # We've received a list of callbacks args to apply to each input
+ if len(callbacks) != len(prompts):
+ msg = "callbacks must be the same length as prompts"
+ raise ValueError(msg)
+ if tags is not None and not (
+ isinstance(tags, list) and len(tags) == len(prompts)
+ ):
+ msg = "tags must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if metadata is not None and not (
+ isinstance(metadata, list) and len(metadata) == len(prompts)
+ ):
+ msg = "metadata must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if run_name is not None and not (
+ isinstance(run_name, list) and len(run_name) == len(prompts)
+ ):
+ msg = "run_name must be a list of the same length as prompts"
+ raise ValueError(msg)
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast("list[list[str] | None]", tags or ([None] * len(prompts)))
+ metadata_list = cast(
+ "list[dict[str, Any] | None]", metadata or ([{}] * len(prompts))
+ )
+ run_name_list = run_name or cast(
+ "list[str | None]", ([None] * len(prompts))
+ )
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ CallbackManager.configure(
+ callback,
+ self.callbacks,
+ self.verbose,
+ tag,
+ self.tags,
+ meta,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ for callback, tag, meta in zip(
+ callbacks, tags_list, metadata_list, strict=False
+ )
+ ]
+ else:
+ # We've received a single callbacks arg to apply to all inputs
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ CallbackManager.configure(
+ cast("Callbacks", callbacks),
+ self.callbacks,
+ self.verbose,
+ cast("list[str]", tags),
+ self.tags,
+ cast("dict[str, Any]", metadata),
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ ] * len(prompts)
+ run_name_list = [cast("str | None", run_name)] * len(prompts)
+ run_ids_list = self._get_run_ids_list(run_id, prompts)
+ options = {"stop": stop}
+ (
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ missing_prompts,
+ ) = get_prompts(params, prompts, self.cache)
+ new_arg_supported = inspect.signature(self._generate).parameters.get(
+ "run_manager"
+ )
+ if (self.cache is None and get_llm_cache() is None) or self.cache is False:
+ run_managers = [
+ callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(prompts),
+ run_id=run_id_,
+ )[0]
+ for callback_manager, prompt, run_name, run_id_ in zip(
+ callback_managers,
+ prompts,
+ run_name_list,
+ run_ids_list,
+ strict=False,
+ )
+ ]
+ return self._generate_helper(
+ prompts,
+ stop,
+ run_managers,
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ if len(missing_prompts) > 0:
+ run_managers = [
+ callback_managers[idx].on_llm_start(
+ self._serialized,
+ [prompts[idx]],
+ invocation_params=params,
+ options=options,
+ name=run_name_list[idx],
+ batch_size=len(missing_prompts),
+ )[0]
+ for idx in missing_prompt_idxs
+ ]
+ new_results = self._generate_helper(
+ missing_prompts,
+ stop,
+ run_managers,
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ llm_output = update_cache(
+ self.cache,
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ new_results,
+ prompts,
+ )
+ run_info = (
+ [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers]
+ if run_managers
+ else None
+ )
+ else:
+ llm_output = {}
+ run_info = None
+ generations = [existing_prompts[i] for i in range(len(prompts))]
+ return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
+
+ @staticmethod
+ def _get_run_ids_list(
+ run_id: uuid.UUID | list[uuid.UUID | None] | None, prompts: list
+ ) -> list:
+ if run_id is None:
+ return [None] * len(prompts)
+ if isinstance(run_id, list):
+ if len(run_id) != len(prompts):
+ msg = (
+ "Number of manually provided run_id's does not match batch length."
+ f" {len(run_id)} != {len(prompts)}"
+ )
+ raise ValueError(msg)
+ return run_id
+ return [run_id] + [None] * (len(prompts) - 1)
+
+ async def _agenerate_helper(
+ self,
+ prompts: list[str],
+ stop: list[str] | None,
+ run_managers: list[AsyncCallbackManagerForLLMRun],
+ *,
+ new_arg_supported: bool,
+ **kwargs: Any,
+ ) -> LLMResult:
+ try:
+ output = (
+ await self._agenerate(
+ prompts,
+ stop=stop,
+ run_manager=run_managers[0] if run_managers else None,
+ **kwargs,
+ )
+ if new_arg_supported
+ else await self._agenerate(prompts, stop=stop)
+ )
+ except BaseException as e:
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_error(e, response=LLMResult(generations=[]))
+ for run_manager in run_managers
+ ]
+ )
+ raise
+ flattened_outputs = output.flatten()
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(flattened_output)
+ for run_manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ )
+ ]
+ )
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ async def agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ *,
+ tags: list[str] | list[list[str]] | None = None,
+ metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
+ run_name: str | list[str] | None = None,
+ run_id: uuid.UUID | list[uuid.UUID | None] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of string prompts.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: List of tags to associate with each prompt. If provided, the length
+ of the list must match the length of the prompts list.
+ metadata: List of metadata dictionaries to associate with each prompt. If
+ provided, the length of the list must match the length of the prompts
+ list.
+ run_name: List of run names to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ run_id: List of run IDs to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Raises:
+ ValueError: If the length of `callbacks`, `tags`, `metadata`, or
+ `run_name` (if provided) does not match the length of prompts.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+ """
+ if isinstance(metadata, list):
+ metadata = [
+ {
+ **(meta or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ for meta in metadata
+ ]
+ elif isinstance(metadata, dict):
+ metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ # Create callback managers
+ if isinstance(callbacks, list) and (
+ isinstance(callbacks[0], (list, BaseCallbackManager))
+ or callbacks[0] is None
+ ):
+ # We've received a list of callbacks args to apply to each input
+ if len(callbacks) != len(prompts):
+ msg = "callbacks must be the same length as prompts"
+ raise ValueError(msg)
+ if tags is not None and not (
+ isinstance(tags, list) and len(tags) == len(prompts)
+ ):
+ msg = "tags must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if metadata is not None and not (
+ isinstance(metadata, list) and len(metadata) == len(prompts)
+ ):
+ msg = "metadata must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if run_name is not None and not (
+ isinstance(run_name, list) and len(run_name) == len(prompts)
+ ):
+ msg = "run_name must be a list of the same length as prompts"
+ raise ValueError(msg)
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast("list[list[str] | None]", tags or ([None] * len(prompts)))
+ metadata_list = cast(
+ "list[dict[str, Any] | None]", metadata or ([{}] * len(prompts))
+ )
+ run_name_list = run_name or cast(
+ "list[str | None]", ([None] * len(prompts))
+ )
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ callback,
+ self.callbacks,
+ self.verbose,
+ tag,
+ self.tags,
+ meta,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ for callback, tag, meta in zip(
+ callbacks, tags_list, metadata_list, strict=False
+ )
+ ]
+ else:
+ # We've received a single callbacks arg to apply to all inputs
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ cast("Callbacks", callbacks),
+ self.callbacks,
+ self.verbose,
+ cast("list[str]", tags),
+ self.tags,
+ cast("dict[str, Any]", metadata),
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ ] * len(prompts)
+ run_name_list = [cast("str | None", run_name)] * len(prompts)
+ run_ids_list = self._get_run_ids_list(run_id, prompts)
+ options = {"stop": stop}
+ (
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ missing_prompts,
+ ) = await aget_prompts(params, prompts, self.cache)
+
+ # Verify whether the cache is set, and if the cache is set,
+ # verify whether the cache is available.
+ new_arg_supported = inspect.signature(self._agenerate).parameters.get(
+ "run_manager"
+ )
+ if (self.cache is None and get_llm_cache() is None) or self.cache is False:
+ run_managers = await asyncio.gather(
+ *[
+ callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(prompts),
+ run_id=run_id_,
+ )
+ for callback_manager, prompt, run_name, run_id_ in zip(
+ callback_managers,
+ prompts,
+ run_name_list,
+ run_ids_list,
+ strict=False,
+ )
+ ]
+ )
+ run_managers = [r[0] for r in run_managers] # type: ignore[misc]
+ return await self._agenerate_helper(
+ prompts,
+ stop,
+ run_managers, # type: ignore[arg-type]
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ if len(missing_prompts) > 0:
+ run_managers = await asyncio.gather(
+ *[
+ callback_managers[idx].on_llm_start(
+ self._serialized,
+ [prompts[idx]],
+ invocation_params=params,
+ options=options,
+ name=run_name_list[idx],
+ batch_size=len(missing_prompts),
+ )
+ for idx in missing_prompt_idxs
+ ]
+ )
+ run_managers = [r[0] for r in run_managers] # type: ignore[misc]
+ new_results = await self._agenerate_helper(
+ missing_prompts,
+ stop,
+ run_managers, # type: ignore[arg-type]
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ llm_output = await aupdate_cache(
+ self.cache,
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ new_results,
+ prompts,
+ )
+ run_info = (
+ [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers] # type: ignore[attr-defined]
+ if run_managers
+ else None
+ )
+ else:
+ llm_output = {}
+ run_info = None
+ generations = [existing_prompts[i] for i in range(len(prompts))]
+ return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
+
+ async def _call_async(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Check Cache and run the LLM on the given prompt and input."""
+ result = await self.agenerate(
+ [prompt],
+ stop=stop,
+ callbacks=callbacks,
+ tags=tags,
+ metadata=metadata,
+ **kwargs,
+ )
+ return result.generations[0][0].text
+
+ def __str__(self) -> str:
+ """Return a string representation of the object for printing."""
+ cls_name = f"\033[1m{self.__class__.__name__}\033[0m"
+ return f"{cls_name}\nParams: {self._identifying_params}"
+
+ @property
+ @abstractmethod
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+
+ @override
+ def dict(self, **kwargs: Any) -> dict:
+ """Return a dictionary of the LLM."""
+ starter_dict = dict(self._identifying_params)
+ starter_dict["_type"] = self._llm_type
+ return starter_dict
+
+ def save(self, file_path: Path | str) -> None:
+ """Save the LLM.
+
+ Args:
+ file_path: Path to file to save the LLM to.
+
+ Raises:
+ ValueError: If the file path is not a string or Path object.
+
+ Example:
+ ```python
+ llm.save(file_path="path/llm.yaml")
+ ```
+ """
+ # Convert file to Path object.
+ save_path = Path(file_path)
+
+ directory_path = save_path.parent
+ directory_path.mkdir(parents=True, exist_ok=True)
+
+ # Fetch dictionary to save
+ prompt_dict = self.dict()
+
+ if save_path.suffix == ".json":
+ with save_path.open("w", encoding="utf-8") as f:
+ json.dump(prompt_dict, f, indent=4)
+ elif save_path.suffix.endswith((".yaml", ".yml")):
+ with save_path.open("w", encoding="utf-8") as f:
+ yaml.dump(prompt_dict, f, default_flow_style=False)
+ else:
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
+
+
+class LLM(BaseLLM):
+ """Simple interface for implementing a custom LLM.
+
+ You should subclass this class and implement the following:
+
+ - `_call` method: Run the LLM on the given prompt and input (used by `invoke`).
+ - `_identifying_params` property: Return a dictionary of the identifying parameters
+ This is critical for caching and tracing purposes. Identifying parameters
+ is a dict that identifies the LLM.
+ It should mostly include a `model_name`.
+
+ Optional: Override the following methods to provide more optimizations:
+
+ - `_acall`: Provide a native async version of the `_call` method.
+ If not provided, will delegate to the synchronous version using
+ `run_in_executor`. (Used by `ainvoke`).
+ - `_stream`: Stream the LLM on the given prompt and input.
+ `stream` will use `_stream` if provided, otherwise it
+ use `_call` and output will arrive in one chunk.
+ - `_astream`: Override to provide a native async version of the `_stream` method.
+ `astream` will use `_astream` if provided, otherwise it will implement
+ a fallback behavior that will use `_stream` if `_stream` is implemented,
+ and use `_acall` if `_stream` is not implemented.
+ """
+
+ @abstractmethod
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Run the LLM on the given input.
+
+ Override this method to implement the LLM logic.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ The model output as a string. SHOULD NOT include the prompt.
+ """
+
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Async version of the _call method.
+
+ The default implementation delegates to the synchronous _call method using
+ `run_in_executor`. Subclasses that need to provide a true async implementation
+ should override this method to reduce the overhead of using `run_in_executor`.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ The model output as a string. SHOULD NOT include the prompt.
+ """
+ return await run_in_executor(
+ None,
+ self._call,
+ prompt,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ # TODO: add caching here.
+ generations = []
+ new_arg_supported = inspect.signature(self._call).parameters.get("run_manager")
+ for prompt in prompts:
+ text = (
+ self._call(prompt, stop=stop, run_manager=run_manager, **kwargs)
+ if new_arg_supported
+ else self._call(prompt, stop=stop, **kwargs)
+ )
+ generations.append([Generation(text=text)])
+ return LLMResult(generations=generations)
+
+ async def _agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ generations = []
+ new_arg_supported = inspect.signature(self._acall).parameters.get("run_manager")
+ for prompt in prompts:
+ text = (
+ await self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs)
+ if new_arg_supported
+ else await self._acall(prompt, stop=stop, **kwargs)
+ )
+ generations.append([Generation(text=text)])
+ return LLMResult(generations=generations)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/language_models/model_profile.py b/python/user_packages/Python313/site-packages/langchain_core/language_models/model_profile.py
new file mode 100644
index 0000000000000000000000000000000000000000..b556c0a6467f0dfb540bacbec040e08e3a236fc0
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/language_models/model_profile.py
@@ -0,0 +1,156 @@
+"""Model profile types and utilities."""
+
+import logging
+import warnings
+from typing import get_type_hints
+
+from pydantic import ConfigDict
+from typing_extensions import TypedDict
+
+logger = logging.getLogger(__name__)
+
+
+class ModelProfile(TypedDict, total=False):
+ """Model profile.
+
+ !!! warning "Beta feature"
+
+ This is a beta feature. The format of model profiles is subject to change.
+
+ Provides information about chat model capabilities, such as context window sizes
+ and supported features.
+ """
+
+ __pydantic_config__ = ConfigDict(extra="allow") # type: ignore[misc]
+
+ # --- Model metadata ---
+
+ name: str
+ """Human-readable model name."""
+
+ status: str
+ """Model status (e.g., `'active'`, `'deprecated'`)."""
+
+ release_date: str
+ """Model release date (ISO 8601 format, e.g., `'2025-06-01'`)."""
+
+ last_updated: str
+ """Date the model was last updated (ISO 8601 format)."""
+
+ open_weights: bool
+ """Whether the model weights are openly available."""
+
+ # --- Input constraints ---
+
+ max_input_tokens: int
+ """Maximum context window (tokens)"""
+
+ text_inputs: bool
+ """Whether text inputs are supported."""
+
+ image_inputs: bool
+ """Whether image inputs are supported."""
+ # TODO: add more detail about formats?
+
+ image_url_inputs: bool
+ """Whether [image URL inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ pdf_inputs: bool
+ """Whether [PDF inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ audio_inputs: bool
+ """Whether [audio inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ video_inputs: bool
+ """Whether [video inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ image_tool_message: bool
+ """Whether images can be included in tool messages."""
+
+ pdf_tool_message: bool
+ """Whether PDFs can be included in tool messages."""
+
+ # --- Output constraints ---
+
+ max_output_tokens: int
+ """Maximum output tokens"""
+
+ reasoning_output: bool
+ """Whether the model supports [reasoning / chain-of-thought](https://docs.langchain.com/oss/python/langchain/models#reasoning)"""
+
+ text_outputs: bool
+ """Whether text outputs are supported."""
+
+ image_outputs: bool
+ """Whether [image outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ audio_outputs: bool
+ """Whether [audio outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ video_outputs: bool
+ """Whether [video outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ # --- Tool calling ---
+ tool_calling: bool
+ """Whether the model supports [tool calling](https://docs.langchain.com/oss/python/langchain/models#tool-calling)"""
+
+ tool_choice: bool
+ """Whether the model supports [tool choice](https://docs.langchain.com/oss/python/langchain/models#forcing-tool-calls)"""
+
+ # --- Structured output ---
+ structured_output: bool
+ """Whether the model supports a native [structured output](https://docs.langchain.com/oss/python/langchain/models#structured-outputs)
+ feature"""
+
+ # --- Other capabilities ---
+
+ attachment: bool
+ """Whether the model supports file attachments."""
+
+ temperature: bool
+ """Whether the model supports a temperature parameter."""
+
+
+ModelProfileRegistry = dict[str, ModelProfile]
+"""Registry mapping model identifiers or names to their ModelProfile."""
+
+
+def _warn_unknown_profile_keys(profile: ModelProfile) -> None:
+ """Warn if `profile` contains keys not declared on `ModelProfile`.
+
+ Args:
+ profile: The model profile dict to check for undeclared keys.
+ """
+ if not isinstance(profile, dict):
+ return
+
+ try:
+ declared = frozenset(get_type_hints(ModelProfile).keys())
+ except (TypeError, NameError):
+ # get_type_hints raises NameError on unresolvable forward refs and
+ # TypeError when annotations evaluate to non-type objects.
+ logger.debug(
+ "Could not resolve type hints for ModelProfile; "
+ "skipping unknown-key check.",
+ exc_info=True,
+ )
+ return
+
+ extra = sorted(set(profile) - declared)
+ if extra:
+ warnings.warn(
+ f"Unrecognized keys in model profile: {extra}. "
+ f"This may indicate a version mismatch between langchain-core "
+ f"and your provider package. Consider upgrading langchain-core.",
+ stacklevel=2,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/load/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e656fedaa19fe19189adf68474cdcd7e7cb39ada
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/__init__.py
@@ -0,0 +1,44 @@
+"""**Load** module helps with serialization and deserialization."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.load.dump import dumpd, dumps
+ from langchain_core.load.load import InitValidator, loads
+ from langchain_core.load.serializable import Serializable
+
+# Unfortunately, we have to eagerly import load from langchain_core/load/load.py
+# eagerly to avoid a namespace conflict. We want users to still be able to use
+# `from langchain_core.load import load` to get the load function, but
+# the `from langchain_core.load.load import load` absolute import should also work.
+from langchain_core.load.load import load
+
+__all__ = (
+ "InitValidator",
+ "Serializable",
+ "dumpd",
+ "dumps",
+ "load",
+ "loads",
+)
+
+_dynamic_imports = {
+ "dumpd": "dump",
+ "dumps": "dump",
+ "InitValidator": "load",
+ "loads": "load",
+ "Serializable": "serializable",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f2674f369f02eae99c555a7305939c150b0e710
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/_validation.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/_validation.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8df38d58d162e9c65538dd0ec6ddbf3f53b5ae0e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/_validation.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/dump.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/dump.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..632ce0ff31e458091690722889609b0f84f241db
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/dump.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/load.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/load.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c11f8cf9f80854047414d00727b0c422a1c27ff9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/load.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/mapping.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/mapping.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e820522a5f8a215eec22f7d66c5a801026d929c1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/mapping.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/serializable.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/serializable.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39899f7d84b597368afa96de21634e700d9555d7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/serializable.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/validators.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/validators.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df6e8fbf3b38ea510d4aa919afe918519a47dd64
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/load/__pycache__/validators.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/_validation.py b/python/user_packages/Python313/site-packages/langchain_core/load/_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bf9f76a486da577a00c84741d4dab0b5088b5f8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/_validation.py
@@ -0,0 +1,191 @@
+"""Validation utilities for LangChain serialization.
+
+Provides escape-based protection against injection attacks in serialized objects. The
+approach uses an allowlist design: only dicts explicitly produced by
+`Serializable.to_json()` are treated as LC objects during deserialization.
+
+## How escaping works
+
+During serialization, plain dicts (user data) that contain an `'lc'` key are wrapped:
+
+```python
+{"lc": 1, ...} # user data that looks like LC object
+# becomes:
+{"__lc_escaped__": {"lc": 1, ...}}
+```
+
+During deserialization, escaped dicts are unwrapped and returned as plain dicts,
+NOT instantiated as LC objects.
+"""
+
+from typing import Any, cast
+
+from langchain_core.load.serializable import (
+ Serializable,
+ to_json_not_implemented,
+)
+
+_LC_ESCAPED_KEY = "__lc_escaped__"
+"""Sentinel key used to mark escaped user dicts during serialization.
+
+When a plain dict contains 'lc' key (which could be confused with LC objects),
+we wrap it as {"__lc_escaped__": {...original...}}.
+"""
+
+
+def _needs_escaping(obj: dict[str, Any]) -> bool:
+ """Check if a dict needs escaping to prevent confusion with LC objects.
+
+ A dict needs escaping if:
+
+ 1. It has an `'lc'` key (could be confused with LC serialization format)
+ 2. It has only the escape key (would be mistaken for an escaped dict)
+ """
+ return "lc" in obj or (len(obj) == 1 and _LC_ESCAPED_KEY in obj)
+
+
+def _escape_dict(obj: dict[str, Any]) -> dict[str, Any]:
+ """Wrap a dict in the escape marker.
+
+ Example:
+ ```python
+ {"key": "value"} # becomes {"__lc_escaped__": {"key": "value"}}
+ ```
+ """
+ return {_LC_ESCAPED_KEY: obj}
+
+
+def _is_escaped_dict(obj: dict[str, Any]) -> bool:
+ """Check if a dict is an escaped user dict.
+
+ Example:
+ ```python
+ {"__lc_escaped__": {...}} # is an escaped dict
+ ```
+ """
+ return len(obj) == 1 and _LC_ESCAPED_KEY in obj
+
+
+def _serialize_value(obj: Any) -> Any:
+ """Serialize a value with escaping of user dicts.
+
+ Called recursively on kwarg values to escape any plain dicts that could be confused
+ with LC objects.
+
+ Args:
+ obj: The value to serialize.
+
+ Returns:
+ The serialized value with user dicts escaped as needed.
+ """
+ if isinstance(obj, Serializable):
+ # This is an LC object - serialize it properly (not escaped)
+ return _serialize_lc_object(obj)
+ if isinstance(obj, dict):
+ if not all(isinstance(k, (str, int, float, bool, type(None))) for k in obj):
+ # if keys are not json serializable
+ return to_json_not_implemented(obj)
+ # Check if dict needs escaping BEFORE recursing into values.
+ # If it needs escaping, wrap it as-is - the contents are user data that
+ # will be returned as-is during deserialization (no instantiation).
+ # This prevents re-escaping of already-escaped nested content.
+ if _needs_escaping(obj):
+ return _escape_dict(obj)
+ # Safe dict (no 'lc' key) - recurse into values
+ return {k: _serialize_value(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_serialize_value(item) for item in obj]
+ if isinstance(obj, (str, int, float, bool, type(None))):
+ return obj
+
+ # Non-JSON-serializable object (datetime, custom objects, etc.)
+ return to_json_not_implemented(obj)
+
+
+def _get_secret_keys(obj: Serializable) -> set[str]:
+ """Return the merged set of constructor kwarg names declared as secrets.
+
+ Mirrors the MRO walk in `Serializable.to_json` so the keys returned here
+ match the keys whose values `_replace_secrets` rewrites into secret
+ markers. Used by `_serialize_lc_object` to decide which kwargs to skip
+ when escaping user data.
+ """
+ secrets: dict[str, str] = {}
+ model_fields = type(obj).model_fields
+ for cls in [None, *obj.__class__.mro()]:
+ if cls is Serializable:
+ break
+ this = cast("Serializable", obj if cls is None else super(cls, obj))
+ secrets.update(this.lc_secrets)
+ for key in list(secrets):
+ if (key in model_fields) and (alias := model_fields[key].alias) is not None:
+ secrets[alias] = secrets[key]
+ return set(secrets)
+
+
+def _serialize_lc_object(obj: Any) -> dict[str, Any]:
+ """Serialize a `Serializable` object with escaping of user data in kwargs.
+
+ Args:
+ obj: The `Serializable` object to serialize.
+
+ Returns:
+ The serialized dict with user data in kwargs escaped as needed.
+
+ Note:
+ Kwargs values are processed with `_serialize_value` to escape user data
+ (like metadata) that contains `'lc'` keys. Secret fields are identified
+ by the class's declared `lc_secrets` and skipped because `to_json()`
+ already converted their values to secret markers.
+
+ The check is key-based rather than shape-based. A shape-based check
+ ("this dict looks like a secret marker") can be forged by user data,
+ letting attacker-controlled free-form dicts bypass escaping and reach
+ the Reviver.
+ """
+ if not isinstance(obj, Serializable):
+ msg = f"Expected Serializable, got {type(obj)}"
+ raise TypeError(msg)
+
+ serialized: dict[str, Any] = dict(obj.to_json())
+
+ # Process kwargs to escape user data that could be confused with LC objects.
+ # Skip kwargs declared as secrets - `to_json()` already replaced their
+ # values with secret markers via `_replace_secrets`.
+ if serialized.get("type") == "constructor" and "kwargs" in serialized:
+ secret_keys = _get_secret_keys(obj)
+ serialized["kwargs"] = {
+ k: v if k in secret_keys else _serialize_value(v)
+ for k, v in serialized["kwargs"].items()
+ }
+
+ return serialized
+
+
+def _unescape_value(obj: Any) -> Any:
+ """Unescape a value, processing escape markers in dict values and lists.
+
+ When an escaped dict is encountered (`{"__lc_escaped__": ...}`), it's
+ unwrapped and the contents are returned AS-IS (no further processing).
+ The contents represent user data that should not be modified.
+
+ For regular dicts and lists, we recurse to find any nested escape markers.
+
+ Args:
+ obj: The value to unescape.
+
+ Returns:
+ The unescaped value.
+ """
+ if isinstance(obj, dict):
+ if _is_escaped_dict(obj):
+ # Unwrap and return the user data as-is (no further unescaping).
+ # The contents are user data that may contain more escape keys,
+ # but those are part of the user's actual data.
+ return obj[_LC_ESCAPED_KEY]
+
+ # Regular dict - recurse into values to find nested escape markers
+ return {k: _unescape_value(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [_unescape_value(item) for item in obj]
+ return obj
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/dump.py b/python/user_packages/Python313/site-packages/langchain_core/load/dump.py
new file mode 100644
index 0000000000000000000000000000000000000000..07bc3099b6c35f83cb149c887e3799d64a7dad5a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/dump.py
@@ -0,0 +1,120 @@
+"""Serialize LangChain objects to JSON.
+
+Provides `dumps` (to JSON string) and `dumpd` (to dict) for serializing
+`Serializable` objects.
+
+## Escaping
+
+During serialization, plain dicts (user data) that contain an `'lc'` key are escaped
+by wrapping them: `{"__lc_escaped__": {...original...}}`. This prevents injection
+attacks where malicious data could trick the deserializer into instantiating
+arbitrary classes. The escape marker is removed during deserialization.
+
+This is an allowlist approach: only dicts explicitly produced by
+`Serializable.to_json()` are treated as LC objects; everything else is escaped if it
+could be confused with the LC format.
+"""
+
+import json
+from typing import Any
+
+from pydantic import BaseModel
+
+from langchain_core.load._validation import _serialize_value
+from langchain_core.load.serializable import Serializable, to_json_not_implemented
+from langchain_core.messages import AIMessage
+from langchain_core.outputs import ChatGeneration
+
+
+def default(obj: Any) -> Any:
+ """Return a default value for an object.
+
+ Args:
+ obj: The object to serialize to json if it is a Serializable object.
+
+ Returns:
+ A JSON serializable object or a SerializedNotImplemented object.
+ """
+ if isinstance(obj, Serializable):
+ return obj.to_json()
+ return to_json_not_implemented(obj)
+
+
+def _dump_pydantic_models(obj: Any) -> Any:
+ """Convert nested Pydantic models to dicts for JSON serialization.
+
+ Handles the special case where a `ChatGeneration` contains an `AIMessage`
+ with a parsed Pydantic model in `additional_kwargs["parsed"]`. Since
+ Pydantic models aren't directly JSON serializable, this converts them to
+ dicts.
+
+ Args:
+ obj: The object to process.
+
+ Returns:
+ A copy of the object with nested Pydantic models converted to dicts, or
+ the original object unchanged if no conversion was needed.
+ """
+ if (
+ isinstance(obj, ChatGeneration)
+ and isinstance(obj.message, AIMessage)
+ and (parsed := obj.message.additional_kwargs.get("parsed"))
+ and isinstance(parsed, BaseModel)
+ ):
+ obj_copy = obj.model_copy(deep=True)
+ obj_copy.message.additional_kwargs["parsed"] = parsed.model_dump()
+ return obj_copy
+ return obj
+
+
+def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
+ """Return a JSON string representation of an object.
+
+ Note:
+ Plain dicts containing an `'lc'` key are automatically escaped to prevent
+ confusion with LC serialization format. The escape marker is removed during
+ deserialization.
+
+ Args:
+ obj: The object to dump.
+ pretty: Whether to pretty print the json.
+
+ If `True`, the json will be indented by either 2 spaces or the amount
+ provided in the `indent` kwarg.
+ **kwargs: Additional arguments to pass to `json.dumps`
+
+ Returns:
+ A JSON string representation of the object.
+
+ Raises:
+ ValueError: If `default` is passed as a kwarg.
+ """
+ if "default" in kwargs:
+ msg = "`default` should not be passed to dumps"
+ raise ValueError(msg)
+
+ obj = _dump_pydantic_models(obj)
+ serialized = _serialize_value(obj)
+
+ if pretty:
+ indent = kwargs.pop("indent", 2)
+ return json.dumps(serialized, indent=indent, **kwargs)
+ return json.dumps(serialized, **kwargs)
+
+
+def dumpd(obj: Any) -> Any:
+ """Return a dict representation of an object.
+
+ Note:
+ Plain dicts containing an `'lc'` key are automatically escaped to prevent
+ confusion with LC serialization format. The escape marker is removed during
+ deserialization.
+
+ Args:
+ obj: The object to dump.
+
+ Returns:
+ Dictionary that can be serialized to json using `json.dumps`.
+ """
+ obj = _dump_pydantic_models(obj)
+ return _serialize_value(obj)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/load.py b/python/user_packages/Python313/site-packages/langchain_core/load/load.py
new file mode 100644
index 0000000000000000000000000000000000000000..c58189837a8f92dbb9abcecdf7269181c4fd6fbb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/load.py
@@ -0,0 +1,819 @@
+"""Load LangChain objects from JSON strings or objects.
+
+## How it works
+
+Each `Serializable` LangChain object has a unique identifier (its "class path"), which
+is a list of strings representing the module path and class name. For example:
+
+- `AIMessage` -> `["langchain_core", "messages", "ai", "AIMessage"]`
+- `ChatPromptTemplate` -> `["langchain_core", "prompts", "chat", "ChatPromptTemplate"]`
+
+When deserializing, the class path from the JSON `'id'` field is checked against an
+allowlist. If the class is not in the allowlist, deserialization raises a `ValueError`.
+
+## Threat model
+
+A serialized LangChain payload crosses a trust boundary because the manifest
+may contain serialized objects and configuration that affect runtime behavior.
+For example, a payload can configure a chat model with a custom `base_url`,
+custom headers, a different model name, or other constructor arguments. These
+are supported features, but they also mean the payload contents should be
+treated as executable configuration rather than plain text.
+
+Concretely, deserialization instantiates Python objects, so any constructor
+(`__init__`) or validator on an allowed class can run during `load()`. A
+crafted payload that is allowed to reach an unintended class — or an intended
+class with attacker-controlled kwargs — could cause network calls, file
+operations, or environment-variable access while the object is being built.
+
+!!! warning "Do not use with untrusted input"
+
+ If the source is untrusted, avoid calling `load()` / `loads()` on it. If
+ you must, restrict `allowed_objects` to types that do not execute logic
+ during init — `allowed_objects='messages'` (or an explicit list of
+ message classes) is the safe choice. Keep `secrets_from_env=False`.
+
+The `allowed_objects` parameter controls which classes can be deserialized:
+
+- **Explicit list of classes** (recommended for untrusted input): only those
+ specific classes are allowed.
+- **`'messages'`**: chat-message classes only (e.g. `AIMessage`,
+ `HumanMessage`). Safe for untrusted input.
+- **`'core'` (current default)** — *unsafe with untrusted manifests.*
+ Classes defined in the serialization mappings under `langchain_core`
+ (messages, documents, prompts, etc.).
+- **`'all'`** — *unsafe with untrusted manifests.* Every class in the
+ serialization mappings, including partner chat models and LLMs and their
+ constructor kwargs (endpoint URLs, headers, model names, etc.).
+
+!!! note "Side effects in allowed classes"
+
+ Deserialization calls `__init__` on allowed classes. If those classes perform
+ side effects during initialization (network calls, file operations, etc.),
+ those side effects will occur. The allowlist prevents instantiation of
+ classes outside the allowlist, but does not sandbox the allowed classes
+ themselves or constrain their constructor kwargs.
+
+Import paths are also validated against trusted namespaces before any module is
+imported.
+
+### Best practices
+
+- Use the most restrictive `allowed_objects` possible. For untrusted input,
+ pass an explicit list of classes or `'messages'`. `'core'` and `'all'`
+ are unsafe with untrusted manifests — only use them when the source
+ serves the entire payload, including its configuration.
+- Keep `secrets_from_env` set to `False` (the default). If you must use it,
+ ensure the serialized data comes from a fully trusted source, as a crafted
+ payload can read arbitrary environment variables.
+- When using `secrets_map`, include only the specific secrets that the
+ serialized object requires.
+
+### Injection protection (escape-based)
+
+During serialization, plain dicts that contain an `'lc'` key are escaped by wrapping
+them: `{"__lc_escaped__": {...}}`. During deserialization, escaped dicts are unwrapped
+and returned as plain dicts, NOT instantiated as LC objects.
+
+This is an allowlist approach: only dicts explicitly produced by
+`Serializable.to_json()` (which are NOT escaped) are treated as LC objects;
+everything else is user data.
+
+Even if an attacker's payload includes `__lc_escaped__` wrappers, it will be unwrapped
+to plain dicts and NOT instantiated as malicious objects.
+
+## Examples
+
+```python
+from langchain_core.load import load
+from langchain_core.prompts import ChatPromptTemplate
+from langchain_core.messages import AIMessage, HumanMessage
+
+# Use default allowlist (classes from mappings) - recommended
+obj = load(data)
+
+# Allow only specific classes (most restrictive)
+obj = load(
+ data,
+ allowed_objects=[
+ ChatPromptTemplate,
+ AIMessage,
+ HumanMessage,
+ ],
+)
+```
+"""
+
+import importlib
+import json
+import os
+from collections.abc import Callable, Iterable
+from typing import Any, Literal, cast
+
+from langchain_core._api import beta
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.load._validation import _is_escaped_dict, _unescape_value
+from langchain_core.load.mapping import (
+ _JS_SERIALIZABLE_MAPPING,
+ _OG_SERIALIZABLE_MAPPING,
+ OLD_CORE_NAMESPACES_MAPPING,
+ SERIALIZABLE_MAPPING,
+)
+from langchain_core.load.serializable import Serializable
+from langchain_core.load.validators import CLASS_INIT_VALIDATORS
+
+DEFAULT_NAMESPACES = [
+ "langchain",
+ "langchain_core",
+ "langchain_community",
+ "langchain_anthropic",
+ "langchain_groq",
+ "langchain_google_genai",
+ "langchain_aws",
+ "langchain_openai",
+ "langchain_google_vertexai",
+ "langchain_mistralai",
+ "langchain_fireworks",
+ "langchain_xai",
+ "langchain_sambanova",
+ "langchain_perplexity",
+]
+# Namespaces for which only deserializing via the SERIALIZABLE_MAPPING is allowed.
+# Load by path is not allowed.
+DISALLOW_LOAD_FROM_PATH = [
+ "langchain_community",
+ "langchain",
+]
+
+ALL_SERIALIZABLE_MAPPINGS = {
+ **SERIALIZABLE_MAPPING,
+ **OLD_CORE_NAMESPACES_MAPPING,
+ **_OG_SERIALIZABLE_MAPPING,
+ **_JS_SERIALIZABLE_MAPPING,
+}
+
+# Modern message classes admitted by `allowed_objects='messages'`. Legacy types
+# (BaseMessage / BaseMessageChunk, ChatMessage / ChatMessageChunk, FunctionMessage /
+# FunctionMessageChunk) are intentionally excluded — `BaseMessage` is abstract and
+# the chat/function variants are superseded by `ToolMessage` and tool calling.
+_MESSAGES_ALLOWED_CLASS_NAMES = frozenset(
+ {
+ "AIMessage",
+ "AIMessageChunk",
+ "HumanMessage",
+ "HumanMessageChunk",
+ "SystemMessage",
+ "SystemMessageChunk",
+ "ToolMessage",
+ "ToolMessageChunk",
+ "RemoveMessage",
+ }
+)
+
+# Cache for the default allowed class paths computed from mappings
+# Maps mode ("all", "core", or "messages") to the cached set of paths
+_default_class_paths_cache: dict[str, set[tuple[str, ...]]] = {}
+
+
+def _get_default_allowed_class_paths(
+ allowed_object_mode: Literal["all", "core", "messages"],
+) -> set[tuple[str, ...]]:
+ """Get the default allowed class paths from the serialization mappings.
+
+ This uses the mappings as the source of truth for what classes are allowed
+ by default. Both the legacy paths (keys) and current paths (values) are included.
+
+ Args:
+ allowed_object_mode: either `'all'`, `'core'`, or `'messages'`.
+
+ Returns:
+ Set of class path tuples that are allowed by default.
+ """
+ if allowed_object_mode in _default_class_paths_cache:
+ return _default_class_paths_cache[allowed_object_mode]
+
+ allowed_paths: set[tuple[str, ...]] = set()
+ for key, value in ALL_SERIALIZABLE_MAPPINGS.items():
+ if allowed_object_mode == "core" and value[0] != "langchain_core":
+ continue
+ if allowed_object_mode == "messages" and (
+ value[0] != "langchain_core"
+ or value[-1] not in _MESSAGES_ALLOWED_CLASS_NAMES
+ ):
+ continue
+ allowed_paths.add(key)
+ allowed_paths.add(value)
+
+ _default_class_paths_cache[allowed_object_mode] = allowed_paths
+ return _default_class_paths_cache[allowed_object_mode]
+
+
+def _block_jinja2_templates(
+ class_path: tuple[str, ...],
+ kwargs: dict[str, Any],
+) -> None:
+ """Block jinja2 templates during deserialization for security.
+
+ Jinja2 templates can execute arbitrary code, so they are blocked by default when
+ deserializing objects with `template_format='jinja2'`.
+
+ Note:
+ We intentionally do NOT check the `class_path` here to keep this simple and
+ future-proof. If any new class is added that accepts `template_format='jinja2'`,
+ it will be automatically blocked without needing to update this function.
+
+ Args:
+ class_path: The class path tuple being deserialized (unused).
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If `template_format` is `'jinja2'`.
+ """
+ _ = class_path # Unused - see docstring for rationale. Kept to satisfy signature.
+ if kwargs.get("template_format") == "jinja2":
+ msg = (
+ "Jinja2 templates are not allowed during deserialization for security "
+ "reasons. Use 'f-string' template format instead, or explicitly allow "
+ "jinja2 by providing a custom init_validator."
+ )
+ raise ValueError(msg)
+
+
+def default_init_validator(
+ class_path: tuple[str, ...],
+ kwargs: dict[str, Any],
+) -> None:
+ """Default init validator that blocks jinja2 templates.
+
+ This is the default validator used by `load()` and `loads()` when no custom
+ validator is provided.
+
+ Args:
+ class_path: The class path tuple being deserialized.
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If template_format is `'jinja2'`.
+ """
+ _block_jinja2_templates(class_path, kwargs)
+
+
+AllowedObject = type[Serializable]
+"""Type alias for classes that can be included in the `allowed_objects` parameter.
+
+Must be a `Serializable` subclass (the class itself, not an instance).
+"""
+
+InitValidator = Callable[[tuple[str, ...], dict[str, Any]], None]
+"""Type alias for a callable that validates kwargs during deserialization.
+
+The callable receives:
+
+- `class_path`: A tuple of strings identifying the class being instantiated
+ (e.g., `('langchain', 'schema', 'messages', 'AIMessage')`).
+- `kwargs`: The kwargs dict that will be passed to the constructor.
+
+The validator should raise an exception if the object should not be deserialized.
+"""
+
+
+def _compute_allowed_class_paths(
+ allowed_objects: Iterable[AllowedObject],
+ import_mappings: dict[tuple[str, ...], tuple[str, ...]],
+) -> set[tuple[str, ...]]:
+ """Return allowed class paths from an explicit list of classes.
+
+ A class path is a tuple of strings identifying a serializable class, derived from
+ `Serializable.lc_id()`. For example: `('langchain_core', 'messages', 'AIMessage')`.
+
+ Args:
+ allowed_objects: Iterable of `Serializable` subclasses to allow.
+ import_mappings: Mapping of legacy class paths to current class paths.
+
+ Returns:
+ Set of allowed class paths.
+
+ Example:
+ ```python
+ # Allow a specific class
+ _compute_allowed_class_paths([MyPrompt], {}) ->
+ {("langchain_core", "prompts", "MyPrompt")}
+
+ # Include legacy paths that map to the same class
+ import_mappings = {("old", "Prompt"): ("langchain_core", "prompts", "MyPrompt")}
+ _compute_allowed_class_paths([MyPrompt], import_mappings) ->
+ {("langchain_core", "prompts", "MyPrompt"), ("old", "Prompt")}
+ ```
+ """
+ allowed_objects_list = list(allowed_objects)
+
+ allowed_class_paths: set[tuple[str, ...]] = set()
+ for allowed_obj in allowed_objects_list:
+ if not isinstance(allowed_obj, type) or not issubclass(
+ allowed_obj, Serializable
+ ):
+ msg = "allowed_objects must contain Serializable subclasses."
+ raise TypeError(msg)
+
+ class_path = tuple(allowed_obj.lc_id())
+ allowed_class_paths.add(class_path)
+ # Add legacy paths that map to the same class.
+ for mapping_key, mapping_value in import_mappings.items():
+ if tuple(mapping_value) == class_path:
+ allowed_class_paths.add(mapping_key)
+ return allowed_class_paths
+
+
+class Reviver:
+ """Reviver for JSON objects.
+
+ Used as the `object_hook` for `json.loads` to reconstruct LangChain objects from
+ their serialized JSON representation.
+
+ Only classes in the allowlist can be instantiated.
+ """
+
+ def __init__(
+ self,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False, # noqa: FBT001,FBT002
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]]
+ | None = None,
+ *,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+ ) -> None:
+ """Initialize the reviver.
+
+ See the module docstring for the threat model around `load()`/`loads()`:
+ a serialized payload may carry constructor configuration that affects
+ runtime behavior (custom `base_url`, headers, model name, etc.). Do not
+ use `'core'` or `'all'` with untrusted manifests.
+
+ Args:
+ allowed_objects: Allowlist of classes that can be deserialized.
+ - Explicit list of classes (recommended for untrusted input):
+ only those specific classes are allowed.
+ - `'messages'`: chat-message classes only (e.g. `AIMessage`,
+ `HumanMessage`). Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and
+ LLMs and their constructor kwargs. See
+ `langchain_core.load.mapping` for the full list.
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object
+ requires. If a secret is not found in the map, it will be loaded
+ from the environment if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in
+ its `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit value (e.g., "
+ "allowed_objects='messages' or allowed_objects='core') to suppress "
+ "this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ self.secrets_from_env = secrets_from_env
+ self.secrets_map = secrets_map or {}
+ # By default, only support langchain, but user can pass in additional namespaces
+ self.valid_namespaces = (
+ [*DEFAULT_NAMESPACES, *valid_namespaces]
+ if valid_namespaces
+ else DEFAULT_NAMESPACES
+ )
+ self.additional_import_mappings = additional_import_mappings or {}
+ self.import_mappings = (
+ {
+ **ALL_SERIALIZABLE_MAPPINGS,
+ **self.additional_import_mappings,
+ }
+ if self.additional_import_mappings
+ else ALL_SERIALIZABLE_MAPPINGS
+ )
+ # Compute allowed class paths:
+ # - "all" -> use default paths from mappings (+ additional_import_mappings)
+ # - Explicit list -> compute from those classes
+ if allowed_objects in ("all", "core", "messages"):
+ self.allowed_class_paths: set[tuple[str, ...]] | None = (
+ _get_default_allowed_class_paths(
+ cast("Literal['all', 'core', 'messages']", allowed_objects)
+ ).copy()
+ )
+ # Add paths from additional_import_mappings to the defaults
+ if self.additional_import_mappings:
+ for key, value in self.additional_import_mappings.items():
+ self.allowed_class_paths.add(key)
+ self.allowed_class_paths.add(value)
+ else:
+ self.allowed_class_paths = _compute_allowed_class_paths(
+ cast("Iterable[AllowedObject]", allowed_objects), self.import_mappings
+ )
+ self.ignore_unserializable_fields = ignore_unserializable_fields
+ self.init_validator = init_validator
+
+ def __call__(self, value: dict[str, Any]) -> Any:
+ """Revive the value.
+
+ Args:
+ value: The value to revive.
+
+ Returns:
+ The revived value.
+
+ Raises:
+ ValueError: If the namespace is invalid.
+ ValueError: If trying to deserialize something that cannot
+ be deserialized in the current version of langchain-core.
+ NotImplementedError: If the object is not implemented and
+ `ignore_unserializable_fields` is False.
+ """
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "secret"
+ and value.get("id") is not None
+ ):
+ [key] = value["id"]
+ if key in self.secrets_map:
+ return self.secrets_map[key]
+ if self.secrets_from_env and key in os.environ and os.environ[key]:
+ return os.environ[key]
+ return None
+
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "not_implemented"
+ and value.get("id") is not None
+ ):
+ if self.ignore_unserializable_fields:
+ return None
+ msg = (
+ "Trying to load an object that doesn't implement "
+ f"serialization: {value}"
+ )
+ raise NotImplementedError(msg)
+
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "constructor"
+ and value.get("id") is not None
+ ):
+ [*namespace, name] = value["id"]
+ mapping_key = tuple(value["id"])
+
+ if (
+ self.allowed_class_paths is not None
+ and mapping_key not in self.allowed_class_paths
+ ):
+ msg = (
+ f"Deserialization of {mapping_key!r} is not allowed. "
+ "The default (allowed_objects='core') only permits core "
+ "langchain-core classes. To allow trusted partner integrations, "
+ "use allowed_objects='all'. Alternatively, pass an explicit list "
+ "of allowed classes via allowed_objects=[...]. "
+ "See langchain_core.load.mapping for the full allowlist."
+ )
+ raise ValueError(msg)
+
+ if (
+ namespace[0] not in self.valid_namespaces
+ # The root namespace ["langchain"] is not a valid identifier.
+ or namespace == ["langchain"]
+ ):
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+ # Determine explicit import path
+ if mapping_key in self.import_mappings:
+ import_path = self.import_mappings[mapping_key]
+ # Split into module and name
+ import_dir, name = import_path[:-1], import_path[-1]
+ elif namespace[0] in DISALLOW_LOAD_FROM_PATH:
+ msg = (
+ "Trying to deserialize something that cannot "
+ "be deserialized in current version of langchain-core: "
+ f"{mapping_key}."
+ )
+ raise ValueError(msg)
+ else:
+ # Otherwise, treat namespace as path.
+ import_dir = namespace
+
+ # Validate import path is in trusted namespaces before importing
+ if import_dir[0] not in self.valid_namespaces:
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+
+ # We don't need to recurse on kwargs
+ # as json.loads will do that for us.
+ kwargs = value.get("kwargs", {})
+
+ # Run class-specific validators before the general init_validator.
+ # These run before importing to fail fast on security violations.
+ if mapping_key in CLASS_INIT_VALIDATORS:
+ CLASS_INIT_VALIDATORS[mapping_key](mapping_key, kwargs)
+
+ # Also run general init_validator (e.g., jinja2 blocking)
+ if self.init_validator is not None:
+ self.init_validator(mapping_key, kwargs)
+
+ mod = importlib.import_module(".".join(import_dir))
+
+ cls = getattr(mod, name)
+
+ # The class must be a subclass of Serializable.
+ if not issubclass(cls, Serializable):
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+
+ return cls(**kwargs)
+
+ return value
+
+
+@beta()
+def loads(
+ text: str,
+ *,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False,
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+) -> Any:
+ """Revive a LangChain class from a JSON string.
+
+ Equivalent to `load(json.loads(text))`.
+
+ Only classes in the allowlist can be instantiated. The default allowlist
+ includes core LangChain types (messages, prompts, documents, etc.). See
+ `langchain_core.load.mapping` for the full list.
+
+ !!! warning "Do not use with untrusted input"
+
+ A serialized payload may carry constructor kwargs that affect runtime
+ behavior (custom `base_url`, headers, model name, etc.), so it should be
+ treated as executable configuration rather than plain text. If the
+ source is untrusted, avoid calling `loads()` on it; if you must, pass
+ `allowed_objects='messages'` or an explicit list of message classes.
+ See the module-level threat model for details.
+
+ Args:
+ text: The string to load.
+ allowed_objects: Allowlist of classes that can be deserialized.
+
+ - Explicit list of classes (recommended for untrusted input): only
+ those specific classes are allowed.
+ - `'messages'`: chat-message classes only. Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and LLMs
+ and their constructor kwargs. See `langchain_core.load.mapping`
+ for the full list.
+ - `[]`: Disallow all deserialization (will raise on any object).
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object requires. If
+ a secret is not found in the map, it will be loaded from the
+ environment if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in its
+ `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+
+ Returns:
+ Revived LangChain objects.
+
+ Raises:
+ ValueError: If an object's class path is not in the `allowed_objects` allowlist.
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit list of allowed classes (or "
+ "'messages' for untrusted input that contains only chat "
+ "messages) to suppress this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ # Parse JSON and delegate to load() for proper escape handling
+ raw_obj = json.loads(text)
+ return load(
+ raw_obj,
+ allowed_objects=allowed_objects,
+ secrets_map=secrets_map,
+ valid_namespaces=valid_namespaces,
+ secrets_from_env=secrets_from_env,
+ additional_import_mappings=additional_import_mappings,
+ ignore_unserializable_fields=ignore_unserializable_fields,
+ init_validator=init_validator,
+ )
+
+
+@beta()
+def load(
+ obj: Any,
+ *,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False,
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+) -> Any:
+ """Revive a LangChain class from a JSON object.
+
+ Use this if you already have a parsed JSON object, eg. from `json.load` or
+ `orjson.loads`.
+
+ Only classes in the allowlist can be instantiated. The default allowlist
+ includes core LangChain types (messages, prompts, documents, etc.). See
+ `langchain_core.load.mapping` for the full list.
+
+ !!! warning "Do not use with untrusted input"
+
+ A serialized payload may carry constructor kwargs that affect runtime
+ behavior (custom `base_url`, headers, model name, etc.), so it should be
+ treated as executable configuration rather than plain text. If the
+ source is untrusted, avoid calling `load()` on it; if you must, pass
+ `allowed_objects='messages'` or an explicit list of message classes.
+ See the module-level threat model for details.
+
+ Args:
+ obj: The object to load.
+ allowed_objects: Allowlist of classes that can be deserialized.
+
+ - Explicit list of classes (recommended for untrusted input): only
+ those specific classes are allowed.
+ - `'messages'`: chat-message classes only. Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and LLMs
+ and their constructor kwargs. See `langchain_core.load.mapping`
+ for the full list.
+ - `[]`: Disallow all deserialization (will raise on any object).
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object requires.
+
+ If a secret is not found in the map, it will be loaded from the environment
+ if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in its
+ `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+
+ Returns:
+ Revived LangChain objects.
+
+ Raises:
+ ValueError: If an object's class path is not in the `allowed_objects` allowlist.
+
+ Example:
+ ```python
+ from langchain_core.load import load, dumpd
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(content="Hello")
+ data = dumpd(msg)
+
+ # Deserialize using default allowlist
+ loaded = load(data)
+
+ # Or with explicit allowlist
+ loaded = load(data, allowed_objects=[AIMessage])
+
+ # Or extend defaults with additional mappings
+ loaded = load(
+ data,
+ additional_import_mappings={
+ ("my_pkg", "MyClass"): ("my_pkg", "module", "MyClass"),
+ },
+ )
+ ```
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit list of allowed classes (or "
+ "'messages' for untrusted input that contains only chat "
+ "messages) to suppress this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ reviver = Reviver(
+ allowed_objects,
+ secrets_map,
+ valid_namespaces,
+ secrets_from_env,
+ additional_import_mappings,
+ ignore_unserializable_fields=ignore_unserializable_fields,
+ init_validator=init_validator,
+ )
+
+ def _load(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ # Check for escaped dict FIRST (before recursing).
+ # Escaped dicts are user data that should NOT be processed as LC objects.
+ if _is_escaped_dict(obj):
+ return _unescape_value(obj)
+
+ # Not escaped - recurse into children then apply reviver
+ loaded_obj = {k: _load(v) for k, v in obj.items()}
+ return reviver(loaded_obj)
+ if isinstance(obj, list):
+ return [_load(o) for o in obj]
+ return obj
+
+ return _load(obj)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/mapping.py b/python/user_packages/Python313/site-packages/langchain_core/load/mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a92824858307586b3dcc9283dd8e2161f95fc6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/mapping.py
@@ -0,0 +1,1085 @@
+"""Serialization mapping.
+
+This file contains a mapping between the `lc_namespace` path for a given
+subclass that implements from `Serializable` to the namespace
+where that class is actually located.
+
+This mapping helps maintain the ability to serialize and deserialize
+well-known LangChain objects even if they are moved around in the codebase
+across different LangChain versions.
+
+For example, the code for the `AIMessage` class is located in
+`langchain_core.messages.ai.AIMessage`. This message is associated with the
+`lc_namespace` of `["langchain", "schema", "messages", "AIMessage"]`,
+because this code was originally in `langchain.schema.messages.AIMessage`.
+
+The mapping allows us to deserialize an `AIMessage` created with an older
+version of LangChain where the code was in a different location.
+"""
+
+# First value is the value that it is serialized as
+# Second value is the path to load it from
+SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain", "schema", "messages", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain", "schema", "messages", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain", "schema", "messages", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain", "schema", "messages", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain", "schema", "messages", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain", "schema", "messages", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain", "schema", "messages", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain", "schema", "messages", "RemoveMessage"): (
+ "langchain_core",
+ "messages",
+ "modifier",
+ "RemoveMessage",
+ ),
+ ("langchain", "schema", "agent", "AgentAction"): (
+ "langchain_core",
+ "agents",
+ "AgentAction",
+ ),
+ ("langchain", "schema", "agent", "AgentFinish"): (
+ "langchain_core",
+ "agents",
+ "AgentFinish",
+ ),
+ ("langchain", "schema", "prompt_template", "BasePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "base",
+ "BasePromptTemplate",
+ ),
+ ("langchain", "chains", "llm", "LLMChain"): (
+ "langchain",
+ "chains",
+ "llm",
+ "LLMChain",
+ ),
+ ("langchain", "prompts", "prompt", "PromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "prompt",
+ "PromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "MessagesPlaceholder"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "MessagesPlaceholder",
+ ),
+ ("langchain", "llms", "openai", "OpenAI"): (
+ "langchain_openai",
+ "llms",
+ "base",
+ "OpenAI",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatPromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "HumanMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "HumanMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "SystemMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "SystemMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "image", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "schema", "agent", "AgentActionMessageLog"): (
+ "langchain_core",
+ "agents",
+ "AgentActionMessageLog",
+ ),
+ ("langchain", "schema", "agent", "ToolAgentAction"): (
+ "langchain",
+ "agents",
+ "output_parsers",
+ "tools",
+ "ToolAgentAction",
+ ),
+ ("langchain", "prompts", "chat", "BaseMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseMessagePromptTemplate",
+ ),
+ ("langchain", "schema", "output", "ChatGeneration"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGeneration",
+ ),
+ ("langchain", "schema", "output", "Generation"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "Generation",
+ ),
+ ("langchain", "schema", "document", "Document"): (
+ "langchain_core",
+ "documents",
+ "base",
+ "Document",
+ ),
+ ("langchain", "output_parsers", "fix", "OutputFixingParser"): (
+ "langchain",
+ "output_parsers",
+ "fix",
+ "OutputFixingParser",
+ ),
+ ("langchain", "prompts", "chat", "AIMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "AIMessagePromptTemplate",
+ ),
+ ("langchain", "output_parsers", "regex", "RegexParser"): (
+ "langchain",
+ "output_parsers",
+ "regex",
+ "RegexParser",
+ ),
+ ("langchain", "schema", "runnable", "DynamicRunnable"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "DynamicRunnable",
+ ),
+ ("langchain", "schema", "prompt", "PromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "PromptValue",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBinding"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBinding",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBranch"): (
+ "langchain_core",
+ "runnables",
+ "branch",
+ "RunnableBranch",
+ ),
+ ("langchain", "schema", "runnable", "RunnableWithFallbacks"): (
+ "langchain_core",
+ "runnables",
+ "fallbacks",
+ "RunnableWithFallbacks",
+ ),
+ ("langchain", "schema", "output_parser", "StrOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "string",
+ "StrOutputParser",
+ ),
+ ("langchain", "chat_models", "openai", "ChatOpenAI"): (
+ "langchain_openai",
+ "chat_models",
+ "base",
+ "ChatOpenAI",
+ ),
+ ("langchain", "output_parsers", "list", "CommaSeparatedListOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "list",
+ "CommaSeparatedListOutputParser",
+ ),
+ ("langchain", "schema", "runnable", "RunnableParallel"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableParallel",
+ ),
+ ("langchain", "chat_models", "azure_openai", "AzureChatOpenAI"): (
+ "langchain_openai",
+ "chat_models",
+ "azure",
+ "AzureChatOpenAI",
+ ),
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock",
+ "ChatBedrock",
+ ),
+ ("langchain", "chat_models", "anthropic", "ChatAnthropic"): (
+ "langchain_anthropic",
+ "chat_models",
+ "ChatAnthropic",
+ ),
+ ("langchain_groq", "chat_models", "ChatGroq"): (
+ "langchain_groq",
+ "chat_models",
+ "ChatGroq",
+ ),
+ ("langchain_openrouter", "chat_models", "ChatOpenRouter"): (
+ "langchain_openrouter",
+ "chat_models",
+ "ChatOpenRouter",
+ ),
+ ("langchain_xai", "chat_models", "ChatXAI"): (
+ "langchain_xai",
+ "chat_models",
+ "ChatXAI",
+ ),
+ ("langchain_baseten", "chat_models", "ChatBaseten"): (
+ "langchain_baseten",
+ "chat_models",
+ "ChatBaseten",
+ ),
+ ("langchain", "chat_models", "fireworks", "ChatFireworks"): (
+ "langchain_fireworks",
+ "chat_models",
+ "ChatFireworks",
+ ),
+ ("langchain", "chat_models", "google_palm", "ChatGooglePalm"): (
+ "langchain",
+ "chat_models",
+ "google_palm",
+ "ChatGooglePalm",
+ ),
+ ("langchain", "chat_models", "vertexai", "ChatVertexAI"): (
+ "langchain_google_vertexai",
+ "chat_models",
+ "ChatVertexAI",
+ ),
+ ("langchain", "chat_models", "mistralai", "ChatMistralAI"): (
+ "langchain_mistralai",
+ "chat_models",
+ "ChatMistralAI",
+ ),
+ ("langchain", "chat_models", "anthropic_bedrock", "ChatAnthropicBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "anthropic",
+ "ChatAnthropicBedrock",
+ ),
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock",
+ "ChatBedrock",
+ ),
+ ("langchain_aws", "chat_models", "ChatBedrockConverse"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock_converse",
+ "ChatBedrockConverse",
+ ),
+ ("langchain_google_genai", "chat_models", "ChatGoogleGenerativeAI"): (
+ "langchain_google_genai",
+ "chat_models",
+ "ChatGoogleGenerativeAI",
+ ),
+ ("langchain", "schema", "output", "ChatGenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGenerationChunk",
+ ),
+ ("langchain", "schema", "messages", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain", "schema", "output", "GenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "GenerationChunk",
+ ),
+ ("langchain", "llms", "openai", "BaseOpenAI"): (
+ "langchain",
+ "llms",
+ "openai",
+ "BaseOpenAI",
+ ),
+ ("langchain", "llms", "bedrock", "Bedrock"): (
+ "langchain_aws",
+ "llms",
+ "bedrock",
+ "BedrockLLM",
+ ),
+ ("langchain", "llms", "bedrock", "BedrockLLM"): (
+ "langchain_aws",
+ "llms",
+ "bedrock",
+ "BedrockLLM",
+ ),
+ ("langchain", "llms", "fireworks", "Fireworks"): (
+ "langchain_fireworks",
+ "llms",
+ "Fireworks",
+ ),
+ ("langchain", "llms", "google_palm", "GooglePalm"): (
+ "langchain",
+ "llms",
+ "google_palm",
+ "GooglePalm",
+ ),
+ ("langchain", "llms", "openai", "AzureOpenAI"): (
+ "langchain_openai",
+ "llms",
+ "azure",
+ "AzureOpenAI",
+ ),
+ ("langchain", "llms", "replicate", "Replicate"): (
+ "langchain",
+ "llms",
+ "replicate",
+ "Replicate",
+ ),
+ ("langchain", "llms", "vertexai", "VertexAI"): (
+ "langchain_vertexai",
+ "llms",
+ "VertexAI",
+ ),
+ ("langchain", "output_parsers", "combining", "CombiningOutputParser"): (
+ "langchain",
+ "output_parsers",
+ "combining",
+ "CombiningOutputParser",
+ ),
+ ("langchain", "schema", "prompt_template", "BaseChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseChatPromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "ChatMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "few_shot_with_templates", "FewShotPromptWithTemplates"): (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ),
+ ("langchain", "prompts", "pipeline"): (
+ "langchain_core",
+ "prompts",
+ "pipeline",
+ ),
+ ("langchain", "prompts", "base", "StringPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "string",
+ "StringPromptTemplate",
+ ),
+ ("langchain", "prompts", "base", "StringPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "StringPromptValue",
+ ),
+ ("langchain", "prompts", "chat", "BaseStringMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseStringMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValue",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptValueConcrete"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValueConcrete",
+ ),
+ ("langchain", "schema", "runnable", "HubRunnable"): (
+ "langchain",
+ "runnables",
+ "hub",
+ "HubRunnable",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBindingBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBindingBase",
+ ),
+ ("langchain", "schema", "runnable", "OpenAIFunctionsRouter"): (
+ "langchain",
+ "runnables",
+ "openai_functions",
+ "OpenAIFunctionsRouter",
+ ),
+ ("langchain", "schema", "runnable", "RouterRunnable"): (
+ "langchain_core",
+ "runnables",
+ "router",
+ "RouterRunnable",
+ ),
+ ("langchain", "schema", "runnable", "RunnablePassthrough"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnablePassthrough",
+ ),
+ ("langchain", "schema", "runnable", "RunnableSequence"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableSequence",
+ ),
+ ("langchain", "schema", "runnable", "RunnableEach"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEach",
+ ),
+ ("langchain", "schema", "runnable", "RunnableEachBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEachBase",
+ ),
+ ("langchain", "schema", "runnable", "RunnableConfigurableAlternatives"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ),
+ ("langchain", "schema", "runnable", "RunnableConfigurableFields"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableFields",
+ ),
+ ("langchain", "schema", "runnable", "RunnableWithMessageHistory"): (
+ "langchain_core",
+ "runnables",
+ "history",
+ "RunnableWithMessageHistory",
+ ),
+ ("langchain", "schema", "runnable", "RunnableAssign"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnableAssign",
+ ),
+ ("langchain", "schema", "runnable", "RunnableRetry"): (
+ "langchain_core",
+ "runnables",
+ "retry",
+ "RunnableRetry",
+ ),
+ ("langchain_core", "prompts", "structured", "StructuredPrompt"): (
+ "langchain_core",
+ "prompts",
+ "structured",
+ "StructuredPrompt",
+ ),
+ ("langchain_core", "prompts", "message", "_DictMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "dict",
+ "DictPromptTemplate",
+ ),
+}
+
+# Needed for backwards compatibility for old versions of LangChain where things
+# Were in different place
+_OG_SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain", "schema", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain", "schema", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain", "schema", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain", "schema", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain", "schema", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain", "schema", "prompt_template", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "schema", "agent", "OpenAIToolAgentAction"): (
+ "langchain",
+ "agents",
+ "output_parsers",
+ "openai_tools",
+ "OpenAIToolAgentAction",
+ ),
+}
+
+# Needed for backwards compatibility for a few versions where we serialized
+# with langchain_core paths.
+OLD_CORE_NAMESPACES_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain_core", "messages", "ai", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain_core", "messages", "ai", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain_core", "messages", "base", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain_core", "messages", "base", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain_core", "messages", "chat", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain_core", "messages", "function", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain_core", "messages", "human", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain_core", "messages", "system", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain_core", "messages", "tool", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain_core", "agents", "AgentAction"): (
+ "langchain_core",
+ "agents",
+ "AgentAction",
+ ),
+ ("langchain_core", "agents", "AgentFinish"): (
+ "langchain_core",
+ "agents",
+ "AgentFinish",
+ ),
+ ("langchain_core", "prompts", "base", "BasePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "base",
+ "BasePromptTemplate",
+ ),
+ ("langchain_core", "prompts", "prompt", "PromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "prompt",
+ "PromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "MessagesPlaceholder"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "MessagesPlaceholder",
+ ),
+ ("langchain_core", "prompts", "chat", "ChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatPromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "HumanMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "HumanMessagePromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "SystemMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "SystemMessagePromptTemplate",
+ ),
+ ("langchain_core", "agents", "AgentActionMessageLog"): (
+ "langchain_core",
+ "agents",
+ "AgentActionMessageLog",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseMessagePromptTemplate",
+ ),
+ ("langchain_core", "outputs", "chat_generation", "ChatGeneration"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGeneration",
+ ),
+ ("langchain_core", "outputs", "generation", "Generation"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "Generation",
+ ),
+ ("langchain_core", "documents", "base", "Document"): (
+ "langchain_core",
+ "documents",
+ "base",
+ "Document",
+ ),
+ ("langchain_core", "prompts", "chat", "AIMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "AIMessagePromptTemplate",
+ ),
+ ("langchain_core", "runnables", "configurable", "DynamicRunnable"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "DynamicRunnable",
+ ),
+ ("langchain_core", "prompt_values", "PromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "PromptValue",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableBinding"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBinding",
+ ),
+ ("langchain_core", "runnables", "branch", "RunnableBranch"): (
+ "langchain_core",
+ "runnables",
+ "branch",
+ "RunnableBranch",
+ ),
+ ("langchain_core", "runnables", "fallbacks", "RunnableWithFallbacks"): (
+ "langchain_core",
+ "runnables",
+ "fallbacks",
+ "RunnableWithFallbacks",
+ ),
+ ("langchain_core", "output_parsers", "string", "StrOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "string",
+ "StrOutputParser",
+ ),
+ ("langchain_core", "output_parsers", "list", "CommaSeparatedListOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "list",
+ "CommaSeparatedListOutputParser",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableParallel"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableParallel",
+ ),
+ ("langchain_core", "outputs", "chat_generation", "ChatGenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGenerationChunk",
+ ),
+ ("langchain_core", "messages", "chat", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain_core", "messages", "human", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain_core", "messages", "function", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain_core", "messages", "system", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain_core", "messages", "tool", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain_core", "outputs", "generation", "GenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "GenerationChunk",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseChatPromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "ChatMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatMessagePromptTemplate",
+ ),
+ (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ): (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ),
+ ("langchain_core", "prompts", "pipeline"): (
+ "langchain_core",
+ "prompts",
+ "pipeline",
+ ),
+ ("langchain_core", "prompts", "string", "StringPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "string",
+ "StringPromptTemplate",
+ ),
+ ("langchain_core", "prompt_values", "StringPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "StringPromptValue",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseStringMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseStringMessagePromptTemplate",
+ ),
+ ("langchain_core", "prompt_values", "ChatPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValue",
+ ),
+ ("langchain_core", "prompt_values", "ChatPromptValueConcrete"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValueConcrete",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableBindingBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBindingBase",
+ ),
+ ("langchain_core", "runnables", "router", "RouterRunnable"): (
+ "langchain_core",
+ "runnables",
+ "router",
+ "RouterRunnable",
+ ),
+ ("langchain_core", "runnables", "passthrough", "RunnablePassthrough"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnablePassthrough",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableSequence"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableSequence",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableEach"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEach",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableEachBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEachBase",
+ ),
+ (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ),
+ ("langchain_core", "runnables", "configurable", "RunnableConfigurableFields"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableFields",
+ ),
+ ("langchain_core", "runnables", "history", "RunnableWithMessageHistory"): (
+ "langchain_core",
+ "runnables",
+ "history",
+ "RunnableWithMessageHistory",
+ ),
+ ("langchain_core", "runnables", "passthrough", "RunnableAssign"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnableAssign",
+ ),
+ ("langchain_core", "runnables", "retry", "RunnableRetry"): (
+ "langchain_core",
+ "runnables",
+ "retry",
+ "RunnableRetry",
+ ),
+}
+
+_JS_SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain_core", "messages", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain_core", "messages", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain_core", "messages", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain_core", "messages", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain_core", "messages", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain_core", "messages", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain_core", "messages", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain_core", "messages", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain_core", "messages", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain_core", "messages", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain_core", "messages", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain_core", "messages", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain_core", "messages", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain_core", "messages", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain_core", "prompts", "image", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "ChatBedrock",
+ ),
+ ("langchain", "chat_models", "google_genai", "ChatGoogleGenerativeAI"): (
+ "langchain_google_genai",
+ "chat_models",
+ "ChatGoogleGenerativeAI",
+ ),
+ ("langchain", "chat_models", "groq", "ChatGroq"): (
+ "langchain_groq",
+ "chat_models",
+ "ChatGroq",
+ ),
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): (
+ "langchain_aws",
+ "chat_models",
+ "ChatBedrock",
+ ),
+}
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/serializable.py b/python/user_packages/Python313/site-packages/langchain_core/load/serializable.py
new file mode 100644
index 0000000000000000000000000000000000000000..429a5e8f88a0cac9b9c46a8e2d3ff1b2ae32218f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/serializable.py
@@ -0,0 +1,388 @@
+"""Serializable base class."""
+
+import contextlib
+import logging
+from abc import ABC
+from typing import (
+ Any,
+ Literal,
+ TypedDict,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict
+from pydantic.fields import FieldInfo
+from typing_extensions import NotRequired, override
+
+logger = logging.getLogger(__name__)
+
+
+class BaseSerialized(TypedDict):
+ """Base class for serialized objects."""
+
+ lc: int
+ """The version of the serialization format."""
+ id: list[str]
+ """The unique identifier of the object."""
+ name: NotRequired[str]
+ """The name of the object."""
+ graph: NotRequired[dict[str, Any]]
+ """The graph of the object."""
+
+
+class SerializedConstructor(BaseSerialized):
+ """Serialized constructor."""
+
+ type: Literal["constructor"]
+ """The type of the object. Must be `'constructor'`."""
+ kwargs: dict[str, Any]
+ """The constructor arguments."""
+
+
+class SerializedSecret(BaseSerialized):
+ """Serialized secret."""
+
+ type: Literal["secret"]
+ """The type of the object. Must be `'secret'`."""
+
+
+class SerializedNotImplemented(BaseSerialized):
+ """Serialized not implemented."""
+
+ type: Literal["not_implemented"]
+ """The type of the object. Must be `'not_implemented'`."""
+ repr: str | None
+ """The representation of the object."""
+
+
+def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
+ """Try to determine if a value is different from the default.
+
+ Args:
+ value: The value.
+ key: The key.
+ model: The Pydantic model.
+
+ Returns:
+ Whether the value is different from the default.
+ """
+ field = type(model).model_fields[key]
+ return _try_neq_default(value, field)
+
+
+def _try_neq_default(value: Any, field: FieldInfo) -> bool:
+ # Handle edge case: inequality of two objects does not evaluate to a bool (e.g. two
+ # Pandas DataFrames).
+ try:
+ return bool(field.get_default() != value)
+ except Exception as _:
+ try:
+ return all(field.get_default() != value)
+ except Exception as _:
+ try:
+ return value is not field.default
+ except Exception as _:
+ return False
+
+
+class Serializable(BaseModel, ABC):
+ """Serializable base class.
+
+ This class is used to serialize objects to JSON.
+
+ It relies on the following methods and properties:
+
+ - [`is_lc_serializable`][langchain_core.load.serializable.Serializable.is_lc_serializable]: Is this class serializable?
+
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
+ - [`get_lc_namespace`][langchain_core.load.serializable.Serializable.get_lc_namespace]: Get the namespace of the LangChain object.
+
+ During deserialization, this namespace is used to identify
+ the correct class to instantiate.
+
+ Please see the `Reviver` class in `langchain_core.load.load` for more details.
+
+ During deserialization an additional mapping is handle classes that have moved
+ or been renamed across package versions.
+
+ - [`lc_secrets`][langchain_core.load.serializable.Serializable.lc_secrets]: A map of constructor argument names to secret ids.
+ - [`lc_attributes`][langchain_core.load.serializable.Serializable.lc_attributes]: List of additional attribute names that should be included
+ as part of the serialized representation.
+ """ # noqa: E501
+
+ # Remove default BaseModel init docstring.
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """""" # noqa: D419 # Intentional blank docstring
+ super().__init__(*args, **kwargs)
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Is this class serializable?
+
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
+
+ Returns:
+ Whether the class is serializable. Default is `False`.
+ """
+ return False
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ The default implementation splits `cls.__module__` on `'.'`, e.g.
+ `langchain_openai.chat_models` becomes
+ `["langchain_openai", "chat_models"]`. This value is used by `lc_id` to
+ build the serialization identifier.
+
+ New partner packages should **not** override this method. The default
+ behavior is correct for any class whose module path already reflects
+ its package name. Some older packages (e.g. `langchain-openai`,
+ `langchain-anthropic`) override it to return a legacy-style namespace
+ like `["langchain", "chat_models", "openai"]`, matching the module
+ paths that existed before those integrations were split out of the
+ main `langchain` package. Those overrides are kept for
+ backwards-compatible deserialization; new packages should not copy them.
+
+ Deserialization mapping is handled separately by
+ `SERIALIZABLE_MAPPING` in `langchain_core.load.mapping`.
+
+ Returns:
+ The namespace.
+ """
+ return cls.__module__.split(".")
+
+ @property
+ def lc_secrets(self) -> dict[str, str]:
+ """A map of constructor argument names to secret ids.
+
+ For example, `{"openai_api_key": "OPENAI_API_KEY"}`
+ """
+ return {}
+
+ @property
+ def lc_attributes(self) -> dict:
+ """List of attribute names that should be included in the serialized kwargs.
+
+ These attributes must be accepted by the constructor.
+
+ Default is an empty dictionary.
+ """
+ return {}
+
+ @classmethod
+ def lc_id(cls) -> list[str]:
+ """Return a unique identifier for this class for serialization purposes.
+
+ The unique identifier is a list of strings that describes the path
+ to the object.
+
+ For example, for the class `langchain.llms.openai.OpenAI`, the id is
+ `["langchain", "llms", "openai", "OpenAI"]`.
+ """
+ # Pydantic generics change the class name. So we need to do the following
+ if (
+ "origin" in cls.__pydantic_generic_metadata__
+ and cls.__pydantic_generic_metadata__["origin"] is not None
+ ):
+ original_name = cls.__pydantic_generic_metadata__["origin"].__name__
+ else:
+ original_name = cls.__name__
+ return [*cls.get_lc_namespace(), original_name]
+
+ model_config = ConfigDict(
+ extra="ignore",
+ )
+
+ @override
+ def __repr_args__(self) -> Any:
+ return [
+ (k, v)
+ for k, v in super().__repr_args__()
+ if (k not in type(self).model_fields or try_neq_default(v, k, self))
+ ]
+
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
+ """Serialize the object to JSON.
+
+ Raises:
+ ValueError: If the class has deprecated attributes.
+
+ Returns:
+ A JSON serializable object or a `SerializedNotImplemented` object.
+ """
+ if not self.is_lc_serializable():
+ return self.to_json_not_implemented()
+
+ model_fields = type(self).model_fields
+ secrets = {}
+ # Get latest values for kwargs if there is an attribute with same name
+ lc_kwargs = {}
+ for k, v in self:
+ if not _is_field_useful(self, k, v):
+ continue
+ # Do nothing if the field is excluded
+ if k in model_fields and model_fields[k].exclude:
+ continue
+
+ lc_kwargs[k] = getattr(self, k, v)
+
+ # Merge the lc_secrets and lc_attributes from every class in the MRO
+ for cls in [None, *self.__class__.mro()]:
+ # Once we get to Serializable, we're done
+ if cls is Serializable:
+ break
+
+ if cls:
+ deprecated_attributes = [
+ "lc_namespace",
+ "lc_serializable",
+ ]
+
+ for attr in deprecated_attributes:
+ if hasattr(cls, attr):
+ msg = (
+ f"Class {self.__class__} has a deprecated "
+ f"attribute {attr}. Please use the corresponding "
+ f"classmethod instead."
+ )
+ raise ValueError(msg)
+
+ # Get a reference to self bound to each class in the MRO
+ this = cast("Serializable", self if cls is None else super(cls, self))
+
+ secrets.update(this.lc_secrets)
+ # Now also add the aliases for the secrets
+ # This ensures known secret aliases are hidden.
+ # Note: this does NOT hide any other extra kwargs
+ # that are not present in the fields.
+ for key in list(secrets):
+ value = secrets[key]
+ if (key in model_fields) and (
+ alias := model_fields[key].alias
+ ) is not None:
+ secrets[alias] = value
+ lc_kwargs.update(this.lc_attributes)
+
+ # include all secrets, even if not specified in kwargs
+ # as these secrets may be passed as an environment variable instead
+ for key in secrets:
+ secret_value = getattr(self, key, None) or lc_kwargs.get(key)
+ if secret_value is not None:
+ lc_kwargs.update({key: secret_value})
+
+ return {
+ "lc": 1,
+ "type": "constructor",
+ "id": self.lc_id(),
+ "kwargs": lc_kwargs
+ if not secrets
+ else _replace_secrets(lc_kwargs, secrets),
+ }
+
+ def to_json_not_implemented(self) -> SerializedNotImplemented:
+ """Serialize a "not implemented" object.
+
+ Returns:
+ `SerializedNotImplemented`.
+ """
+ return to_json_not_implemented(self)
+
+
+def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
+ """Check if a field is useful as a constructor argument.
+
+ Args:
+ inst: The instance.
+ key: The key.
+ value: The value.
+
+ Returns:
+ Whether the field is useful. If the field is required, it is useful.
+ If the field is not required, it is useful if the value is not `None`.
+ If the field is not required and the value is `None`, it is useful if the
+ default value is different from the value.
+ """
+ field = type(inst).model_fields.get(key)
+ if not field:
+ return False
+
+ if field.is_required():
+ return True
+
+ # Handle edge case: a value cannot be converted to a boolean (e.g. a
+ # Pandas DataFrame).
+ try:
+ value_is_truthy = bool(value)
+ except Exception as _:
+ value_is_truthy = False
+
+ if value_is_truthy:
+ return True
+
+ # Value is still falsy here!
+ if field.default_factory is dict and isinstance(value, dict):
+ return False
+
+ # Value is still falsy here!
+ if field.default_factory is list and isinstance(value, list):
+ return False
+
+ value_neq_default = _try_neq_default(value, field)
+
+ # If value is falsy and does not match the default
+ return value_is_truthy or value_neq_default
+
+
+def _replace_secrets(
+ root: dict[Any, Any], secrets_map: dict[str, str]
+) -> dict[Any, Any]:
+ result = root.copy()
+ for path, secret_id in secrets_map.items():
+ [*parts, last] = path.split(".")
+ current = result
+ for part in parts:
+ if part not in current:
+ break
+ current[part] = current[part].copy()
+ current = current[part]
+ if last in current:
+ current[last] = {
+ "lc": 1,
+ "type": "secret",
+ "id": [secret_id],
+ }
+ return result
+
+
+def to_json_not_implemented(obj: object) -> SerializedNotImplemented:
+ """Serialize a "not implemented" object.
+
+ Args:
+ obj: Object to serialize.
+
+ Returns:
+ `SerializedNotImplemented`
+ """
+ id_: list[str] = []
+ try:
+ if hasattr(obj, "__name__"):
+ id_ = [*obj.__module__.split("."), obj.__name__]
+ elif hasattr(obj, "__class__"):
+ id_ = [*obj.__class__.__module__.split("."), obj.__class__.__name__]
+ except Exception:
+ logger.debug("Failed to serialize object", exc_info=True)
+
+ result: SerializedNotImplemented = {
+ "lc": 1,
+ "type": "not_implemented",
+ "id": id_,
+ "repr": None,
+ }
+ with contextlib.suppress(Exception):
+ result["repr"] = repr(obj)
+ return result
diff --git a/python/user_packages/Python313/site-packages/langchain_core/load/validators.py b/python/user_packages/Python313/site-packages/langchain_core/load/validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f470649c04b3cfcfecf2b4ad65d59440368b0ac
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/load/validators.py
@@ -0,0 +1,77 @@
+"""Init validators for deserialization security.
+
+This module contains extra validators that are called during deserialization,
+ex. to prevent security issues such as SSRF attacks.
+
+Each validator is a callable matching the `InitValidator` protocol: it takes a
+class path tuple and kwargs dict, returns `None` on success, and raises
+`ValueError` if the deserialization should be blocked.
+"""
+
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_core.load.load import InitValidator
+
+
+def _bedrock_validator(class_path: tuple[str, ...], kwargs: dict[str, Any]) -> None:
+ """Constructor kwargs validator for AWS Bedrock integrations.
+
+ Blocks deserialization if `endpoint_url` or `base_url` parameters are
+ present, which could enable SSRF attacks.
+
+ Args:
+ class_path: The class path tuple being deserialized.
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If `endpoint_url` or `base_url` parameters are present.
+ """
+ dangerous_params = ["endpoint_url", "base_url"]
+ found_params = [p for p in dangerous_params if p in kwargs]
+
+ if found_params:
+ class_name = class_path[-1] if class_path else "Unknown"
+ param_str = ", ".join(found_params)
+ msg = (
+ f"Deserialization of {class_name} with {param_str} is not allowed "
+ f"for security reasons. These parameters can enable Server-Side Request "
+ f"Forgery (SSRF) attacks by directing network requests to arbitrary "
+ f"endpoints during initialization. If you need to use a custom endpoint, "
+ f"instantiate {class_name} directly rather than deserializing it."
+ )
+ raise ValueError(msg)
+
+
+# Keys must cover both serialized IDs (SERIALIZABLE_MAPPING keys) and resolved
+# import paths (SERIALIZABLE_MAPPING values) to prevent bypass via direct paths.
+CLASS_INIT_VALIDATORS: dict[tuple[str, ...], "InitValidator"] = {
+ # Serialized (legacy) keys
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): _bedrock_validator,
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): _bedrock_validator,
+ (
+ "langchain",
+ "chat_models",
+ "anthropic_bedrock",
+ "ChatAnthropicBedrock",
+ ): _bedrock_validator,
+ ("langchain_aws", "chat_models", "ChatBedrockConverse"): _bedrock_validator,
+ ("langchain", "llms", "bedrock", "Bedrock"): _bedrock_validator,
+ ("langchain", "llms", "bedrock", "BedrockLLM"): _bedrock_validator,
+ # Resolved import paths (from ALL_SERIALIZABLE_MAPPINGS values) to defend
+ # against payloads that use the target tuple directly as the "id".
+ (
+ "langchain_aws",
+ "chat_models",
+ "bedrock_converse",
+ "ChatBedrockConverse",
+ ): _bedrock_validator,
+ (
+ "langchain_aws",
+ "chat_models",
+ "anthropic",
+ "ChatAnthropicBedrock",
+ ): _bedrock_validator,
+ ("langchain_aws", "chat_models", "ChatBedrock"): _bedrock_validator,
+ ("langchain_aws", "llms", "bedrock", "BedrockLLM"): _bedrock_validator,
+}
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/messages/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..97171f56b165378342df121325dae89e5af80556
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/__init__.py
@@ -0,0 +1,198 @@
+"""**Messages** are objects used in prompts and chat conversations."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+from langchain_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX, ensure_id
+
+if TYPE_CHECKING:
+ from langchain_core.messages.ai import (
+ AIMessage,
+ AIMessageChunk,
+ InputTokenDetails,
+ OutputTokenDetails,
+ UsageMetadata,
+ )
+ from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+ message_to_dict,
+ messages_to_dict,
+ )
+ from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_data_block,
+ convert_to_openai_image_block,
+ )
+ from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
+ from langchain_core.messages.content import (
+ Annotation,
+ AudioContentBlock,
+ Citation,
+ ContentBlock,
+ DataContentBlock,
+ FileContentBlock,
+ ImageContentBlock,
+ InvalidToolCall,
+ NonStandardAnnotation,
+ NonStandardContentBlock,
+ PlainTextContentBlock,
+ ReasoningContentBlock,
+ ServerToolCall,
+ ServerToolCallChunk,
+ ServerToolResult,
+ TextContentBlock,
+ VideoContentBlock,
+ is_data_content_block,
+ )
+ from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
+ from langchain_core.messages.human import HumanMessage, HumanMessageChunk
+ from langchain_core.messages.modifier import RemoveMessage
+ from langchain_core.messages.system import SystemMessage, SystemMessageChunk
+ from langchain_core.messages.tool import (
+ ToolCall,
+ ToolCallChunk,
+ ToolMessage,
+ ToolMessageChunk,
+ )
+ from langchain_core.messages.utils import (
+ AnyMessage,
+ MessageLikeRepresentation,
+ _message_from_dict,
+ convert_to_messages,
+ convert_to_openai_messages,
+ filter_messages,
+ get_buffer_string,
+ merge_message_runs,
+ message_chunk_to_message,
+ messages_from_dict,
+ trim_messages,
+ )
+
+__all__ = (
+ "LC_AUTO_PREFIX",
+ "LC_ID_PREFIX",
+ "AIMessage",
+ "AIMessageChunk",
+ "Annotation",
+ "AnyMessage",
+ "AudioContentBlock",
+ "BaseMessage",
+ "BaseMessageChunk",
+ "ChatMessage",
+ "ChatMessageChunk",
+ "Citation",
+ "ContentBlock",
+ "DataContentBlock",
+ "FileContentBlock",
+ "FunctionMessage",
+ "FunctionMessageChunk",
+ "HumanMessage",
+ "HumanMessageChunk",
+ "ImageContentBlock",
+ "InputTokenDetails",
+ "InvalidToolCall",
+ "MessageLikeRepresentation",
+ "NonStandardAnnotation",
+ "NonStandardContentBlock",
+ "OutputTokenDetails",
+ "PlainTextContentBlock",
+ "ReasoningContentBlock",
+ "RemoveMessage",
+ "ServerToolCall",
+ "ServerToolCallChunk",
+ "ServerToolResult",
+ "SystemMessage",
+ "SystemMessageChunk",
+ "TextContentBlock",
+ "ToolCall",
+ "ToolCallChunk",
+ "ToolMessage",
+ "ToolMessageChunk",
+ "UsageMetadata",
+ "VideoContentBlock",
+ "_message_from_dict",
+ "convert_to_messages",
+ "convert_to_openai_data_block",
+ "convert_to_openai_image_block",
+ "convert_to_openai_messages",
+ "ensure_id",
+ "filter_messages",
+ "get_buffer_string",
+ "is_data_content_block",
+ "merge_content",
+ "merge_message_runs",
+ "message_chunk_to_message",
+ "message_to_dict",
+ "messages_from_dict",
+ "messages_to_dict",
+ "trim_messages",
+)
+
+_dynamic_imports = {
+ "AIMessage": "ai",
+ "AIMessageChunk": "ai",
+ "Annotation": "content",
+ "AudioContentBlock": "content",
+ "BaseMessage": "base",
+ "BaseMessageChunk": "base",
+ "merge_content": "base",
+ "message_to_dict": "base",
+ "messages_to_dict": "base",
+ "Citation": "content",
+ "ContentBlock": "content",
+ "ChatMessage": "chat",
+ "ChatMessageChunk": "chat",
+ "DataContentBlock": "content",
+ "FileContentBlock": "content",
+ "FunctionMessage": "function",
+ "FunctionMessageChunk": "function",
+ "HumanMessage": "human",
+ "HumanMessageChunk": "human",
+ "NonStandardAnnotation": "content",
+ "NonStandardContentBlock": "content",
+ "OutputTokenDetails": "ai",
+ "PlainTextContentBlock": "content",
+ "ReasoningContentBlock": "content",
+ "RemoveMessage": "modifier",
+ "ServerToolCall": "content",
+ "ServerToolCallChunk": "content",
+ "ServerToolResult": "content",
+ "SystemMessage": "system",
+ "SystemMessageChunk": "system",
+ "ImageContentBlock": "content",
+ "InputTokenDetails": "ai",
+ "InvalidToolCall": "tool",
+ "TextContentBlock": "content",
+ "ToolCall": "tool",
+ "ToolCallChunk": "tool",
+ "ToolMessage": "tool",
+ "ToolMessageChunk": "tool",
+ "UsageMetadata": "ai",
+ "VideoContentBlock": "content",
+ "AnyMessage": "utils",
+ "MessageLikeRepresentation": "utils",
+ "_message_from_dict": "utils",
+ "convert_to_messages": "utils",
+ "convert_to_openai_data_block": "block_translators.openai",
+ "convert_to_openai_image_block": "block_translators.openai",
+ "convert_to_openai_messages": "utils",
+ "filter_messages": "utils",
+ "get_buffer_string": "utils",
+ "is_data_content_block": "content",
+ "merge_message_runs": "utils",
+ "message_chunk_to_message": "utils",
+ "messages_from_dict": "utils",
+ "trim_messages": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..201b27557f9c908f530aef84c4e0136bae84e4e8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/ai.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/ai.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b056b89b9f0466bb362bc2bab4886b6fe7a2233
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/ai.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47728f6c662cc5eef5485d5b5961cd5dce5f3ae2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/chat.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/chat.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccc9b68aa40dfa42c209553e29f604efaf15ca8c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/chat.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/content.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/content.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c6a12480c3ad17a1874661f6056105ec20baff5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/content.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/function.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/function.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..812888ee46506124715c7ea30c34329a12564165
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/function.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/human.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/human.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..913396d63d5914993f01dd53ee3f7c610a527890
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/human.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/modifier.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/modifier.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2ee28a36a7fb47aa1fdd4de302cc28faf45e4f8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/modifier.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/system.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/system.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0aa03db9fcf9e03857128853c52b0f7f5f17e264
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/system.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/tool.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/tool.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a23e29b2f548b2782580315f4b7265a97ab1db43
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/tool.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..919af10f871e56f394d8f4f60c0b1f3fec9c64f4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/__pycache__/utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/ai.py b/python/user_packages/Python313/site-packages/langchain_core/messages/ai.py
new file mode 100644
index 0000000000000000000000000000000000000000..92bac634d69145166c5e3b1b3f2f61e4ce007aee
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/ai.py
@@ -0,0 +1,840 @@
+"""AI message."""
+
+import itertools
+import json
+import logging
+import operator
+from collections.abc import Sequence
+from typing import Any, Literal, cast, overload
+
+from pydantic import Field, model_validator
+from typing_extensions import NotRequired, Self, TypedDict, override
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ _extract_reasoning_from_additional_kwargs,
+ merge_content,
+)
+from langchain_core.messages.content import InvalidToolCall
+from langchain_core.messages.tool import (
+ ToolCall,
+ ToolCallChunk,
+ default_tool_chunk_parser,
+ default_tool_parser,
+)
+from langchain_core.messages.tool import invalid_tool_call as create_invalid_tool_call
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.messages.tool import tool_call_chunk as create_tool_call_chunk
+from langchain_core.utils._merge import merge_dicts, merge_lists
+from langchain_core.utils.json import parse_partial_json
+from langchain_core.utils.usage import _dict_int_op
+from langchain_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX
+
+logger = logging.getLogger(__name__)
+
+
+class InputTokenDetails(TypedDict, total=False):
+ """Breakdown of input token counts.
+
+ Does *not* need to sum to full input token count. Does *not* need to have all keys.
+
+ Example:
+ ```python
+ {
+ "audio": 10,
+ "cache_creation": 200,
+ "cache_read": 100,
+ }
+ ```
+
+ May also hold extra provider-specific keys.
+
+ !!! version-added "Added in `langchain-core` 0.3.9"
+ """
+
+ audio: int
+ """Audio input tokens."""
+
+ cache_creation: int
+ """Input tokens that were cached and there was a cache miss.
+
+ Since there was a cache miss, the cache was created from these tokens.
+ """
+
+ cache_read: int
+ """Input tokens that were cached and there was a cache hit.
+
+ Since there was a cache hit, the tokens were read from the cache. More precisely,
+ the model state given these tokens was read from the cache.
+ """
+
+
+class OutputTokenDetails(TypedDict, total=False):
+ """Breakdown of output token counts.
+
+ Does *not* need to sum to full output token count. Does *not* need to have all keys.
+
+ Example:
+ ```python
+ {
+ "audio": 10,
+ "reasoning": 200,
+ }
+ ```
+
+ May also hold extra provider-specific keys.
+
+ !!! version-added "Added in `langchain-core` 0.3.9"
+
+ """
+
+ audio: int
+ """Audio output tokens."""
+
+ reasoning: int
+ """Reasoning output tokens.
+
+ Tokens generated by the model in a chain of thought process (i.e. by OpenAI's o1
+ models) that are not returned as part of model output.
+ """
+
+
+class UsageMetadata(TypedDict):
+ """Usage metadata for a message, such as token counts.
+
+ This is a standard representation of token usage that is consistent across models.
+
+ Example:
+ ```python
+ {
+ "input_tokens": 350,
+ "output_tokens": 240,
+ "total_tokens": 590,
+ "input_token_details": {
+ "audio": 10,
+ "cache_creation": 200,
+ "cache_read": 100,
+ },
+ "output_token_details": {
+ "audio": 10,
+ "reasoning": 200,
+ },
+ }
+ ```
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.9"
+
+ Added `input_token_details` and `output_token_details`.
+
+ !!! note "LangSmith SDK"
+
+ The LangSmith SDK also has a `UsageMetadata` class. While the two share fields,
+ LangSmith's `UsageMetadata` has additional fields to capture cost information
+ used by the LangSmith platform.
+ """
+
+ input_tokens: int
+ """Count of input (or prompt) tokens. Sum of all input token types."""
+
+ output_tokens: int
+ """Count of output (or completion) tokens. Sum of all output token types."""
+
+ total_tokens: int
+ """Total token count. Sum of `input_tokens` + `output_tokens`."""
+
+ input_token_details: NotRequired[InputTokenDetails]
+ """Breakdown of input token counts.
+
+ Does *not* need to sum to full input token count. Does *not* need to have all keys.
+ """
+
+ output_token_details: NotRequired[OutputTokenDetails]
+ """Breakdown of output token counts.
+
+ Does *not* need to sum to full output token count. Does *not* need to have all keys.
+ """
+
+
+class AIMessage(BaseMessage):
+ """Message from an AI.
+
+ An `AIMessage` is returned from a chat model as a response to a prompt.
+
+ This message represents the output of the model and consists of both
+ the raw output as returned by the model and standardized fields
+ (e.g., tool calls, usage metadata) added by the LangChain framework.
+ """
+
+ tool_calls: list[ToolCall] = Field(default_factory=list)
+ """If present, tool calls associated with the message."""
+
+ invalid_tool_calls: list[InvalidToolCall] = Field(default_factory=list)
+ """If present, tool calls with parsing errors associated with the message."""
+
+ usage_metadata: UsageMetadata | None = None
+ """If present, usage metadata for a message, such as token counts.
+
+ This is a standard representation of token usage that is consistent across models.
+ """
+
+ type: Literal["ai"] = "ai"
+ """The type of the message (used for deserialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize an `AIMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The content of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional arguments to pass to the parent class.
+ """
+ if content_blocks is not None:
+ # If there are tool calls in content_blocks, but not in tool_calls, add them
+ content_tool_calls = [
+ block for block in content_blocks if block.get("type") == "tool_call"
+ ]
+ if content_tool_calls and "tool_calls" not in kwargs:
+ kwargs["tool_calls"] = content_tool_calls
+
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+ @property
+ def lc_attributes(self) -> dict:
+ """Attributes to be serialized.
+
+ Includes all attributes, even if they are derived from other initialization
+ arguments.
+ """
+ return {
+ "tool_calls": self.tool_calls,
+ "invalid_tool_calls": self.invalid_tool_calls,
+ }
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ """Return standard, typed `ContentBlock` dicts from the message.
+
+ If the message has a known model provider, use the provider-specific translator
+ first before falling back to best-effort parsing. For details, see the property
+ on `BaseMessage`.
+ """
+ if self.response_metadata.get("output_version") == "v1":
+ return cast("list[types.ContentBlock]", self.content)
+
+ model_provider = self.response_metadata.get("model_provider")
+ if model_provider:
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ get_translator,
+ )
+
+ translator = get_translator(model_provider)
+ if translator:
+ try:
+ return translator["translate_content"](self)
+ except NotImplementedError:
+ pass
+
+ # Otherwise, use best-effort parsing
+ blocks = super().content_blocks
+
+ if self.tool_calls:
+ # Add from tool_calls if missing from content
+ content_tool_call_ids = {
+ block.get("id")
+ for block in self.content
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in self.tool_calls:
+ if (id_ := tool_call.get("id")) and id_ not in content_tool_call_ids:
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ if "index" in tool_call:
+ tool_call_block["index"] = tool_call["index"] # type: ignore[typeddict-item]
+ if "extras" in tool_call:
+ tool_call_block["extras"] = tool_call["extras"] # type: ignore[typeddict-item]
+ blocks.append(tool_call_block)
+
+ # Best-effort reasoning extraction from additional_kwargs
+ # Only add reasoning if not already present
+ # Insert before all other blocks to keep reasoning at the start
+ has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
+ if not has_reasoning and (
+ reasoning_block := _extract_reasoning_from_additional_kwargs(self)
+ ):
+ blocks.insert(0, reasoning_block)
+
+ return blocks
+
+ # TODO: remove this logic if possible, reducing breaking nature of changes
+ @model_validator(mode="before")
+ @classmethod
+ def _backwards_compat_tool_calls(cls, values: dict) -> Any:
+ check_additional_kwargs = not any(
+ values.get(k)
+ for k in ("tool_calls", "invalid_tool_calls", "tool_call_chunks")
+ )
+ if check_additional_kwargs and (
+ raw_tool_calls := values.get("additional_kwargs", {}).get("tool_calls")
+ ):
+ try:
+ if issubclass(cls, AIMessageChunk):
+ values["tool_call_chunks"] = default_tool_chunk_parser(
+ raw_tool_calls
+ )
+ else:
+ parsed_tool_calls, parsed_invalid_tool_calls = default_tool_parser(
+ raw_tool_calls
+ )
+ values["tool_calls"] = parsed_tool_calls
+ values["invalid_tool_calls"] = parsed_invalid_tool_calls
+ except Exception:
+ logger.debug("Failed to parse tool calls", exc_info=True)
+
+ # Ensure "type" is properly set on all tool call-like dicts.
+ if tool_calls := values.get("tool_calls"):
+ values["tool_calls"] = [
+ create_tool_call(
+ **{k: v for k, v in tc.items() if k not in {"type", "extras"}}
+ )
+ for tc in tool_calls
+ ]
+ if invalid_tool_calls := values.get("invalid_tool_calls"):
+ values["invalid_tool_calls"] = [
+ create_invalid_tool_call(**{k: v for k, v in tc.items() if k != "type"})
+ for tc in invalid_tool_calls
+ ]
+
+ if tool_call_chunks := values.get("tool_call_chunks"):
+ values["tool_call_chunks"] = [
+ create_tool_call_chunk(**{k: v for k, v in tc.items() if k != "type"})
+ for tc in tool_call_chunks
+ ]
+
+ return values
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Return a pretty representation of the message for display.
+
+ Args:
+ html: Whether to return an HTML-formatted string.
+
+ Returns:
+ A pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(
+ content="Let me check the weather.",
+ tool_calls=[
+ {"name": "get_weather", "args": {"city": "Paris"}, "id": "1"}
+ ],
+ )
+ ```
+
+ Results in:
+ ```python
+ >>> print(msg.pretty_repr())
+ ================================== Ai Message ==================================
+
+ Let me check the weather.
+ Tool Calls:
+ get_weather (1)
+ Call ID: 1
+ Args:
+ city: Paris
+ ```
+ """ # noqa: E501
+ base = super().pretty_repr(html=html)
+ lines = []
+
+ def _format_tool_args(tc: ToolCall | InvalidToolCall) -> list[str]:
+ lines = [
+ f" {tc.get('name', 'Tool')} ({tc.get('id')})",
+ f" Call ID: {tc.get('id')}",
+ ]
+ if tc.get("error"):
+ lines.append(f" Error: {tc.get('error')}")
+ lines.append(" Args:")
+ args = tc.get("args")
+ if isinstance(args, str):
+ lines.append(f" {args}")
+ elif isinstance(args, dict):
+ for arg, value in args.items():
+ lines.append(f" {arg}: {value}")
+ return lines
+
+ if self.tool_calls:
+ lines.append("Tool Calls:")
+ for tc in self.tool_calls:
+ lines.extend(_format_tool_args(tc))
+ if self.invalid_tool_calls:
+ lines.append("Invalid Tool Calls:")
+ for itc in self.invalid_tool_calls:
+ lines.extend(_format_tool_args(itc))
+ return (base.strip() + "\n" + "\n".join(lines)).strip()
+
+
+class AIMessageChunk(AIMessage, BaseMessageChunk):
+ """Message chunk from an AI (yielded when streaming)."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for deserialization)."""
+
+ tool_call_chunks: list[ToolCallChunk] = Field(default_factory=list)
+ """If provided, tool call chunks associated with the message."""
+
+ chunk_position: Literal["last"] | None = None
+ """Optional span represented by an aggregated `AIMessageChunk`.
+
+ If a chunk with `chunk_position="last"` is aggregated into a stream,
+ `tool_call_chunks` in message content will be parsed into `tool_calls`.
+ """
+
+ @property
+ @override
+ def lc_attributes(self) -> dict:
+ return {
+ "tool_calls": self.tool_calls,
+ "invalid_tool_calls": self.invalid_tool_calls,
+ }
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ """Return standard, typed `ContentBlock` dicts from the message."""
+ if self.response_metadata.get("output_version") == "v1":
+ return cast("list[types.ContentBlock]", self.content)
+
+ model_provider = self.response_metadata.get("model_provider")
+ if model_provider:
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ get_translator,
+ )
+
+ translator = get_translator(model_provider)
+ if translator:
+ try:
+ return translator["translate_content_chunk"](self)
+ except NotImplementedError:
+ pass
+
+ # Otherwise, use best-effort parsing
+ blocks = super().content_blocks
+
+ if (
+ self.tool_call_chunks
+ and not self.content
+ and self.chunk_position != "last" # keep tool_calls if aggregated
+ ):
+ blocks = [
+ block
+ for block in blocks
+ if block["type"] not in {"tool_call", "invalid_tool_call"}
+ ]
+ for tool_call_chunk in self.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ blocks.append(tc)
+
+ # Best-effort reasoning extraction from additional_kwargs
+ # Only add reasoning if not already present
+ # Insert before all other blocks to keep reasoning at the start
+ has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
+ if not has_reasoning and (
+ reasoning_block := _extract_reasoning_from_additional_kwargs(self)
+ ):
+ blocks.insert(0, reasoning_block)
+
+ return blocks
+
+ @model_validator(mode="after")
+ def init_tool_calls(self) -> Self:
+ """Initialize tool calls from tool call chunks.
+
+ Returns:
+ The values with tool calls initialized.
+
+ Raises:
+ ValueError: If the tool call chunks are malformed.
+ """
+ if not self.tool_call_chunks:
+ if self.tool_calls:
+ self.tool_call_chunks = [
+ create_tool_call_chunk(
+ name=tc["name"],
+ args=json.dumps(tc["args"]),
+ id=tc["id"],
+ index=None,
+ )
+ for tc in self.tool_calls
+ ]
+ if self.invalid_tool_calls:
+ tool_call_chunks = self.tool_call_chunks
+ tool_call_chunks.extend(
+ [
+ create_tool_call_chunk(
+ name=tc["name"], args=tc["args"], id=tc["id"], index=None
+ )
+ for tc in self.invalid_tool_calls
+ ]
+ )
+ self.tool_call_chunks = tool_call_chunks
+
+ return self
+ tool_calls = []
+ invalid_tool_calls = []
+
+ def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:
+ invalid_tool_calls.append(
+ create_invalid_tool_call(
+ name=chunk["name"],
+ args=chunk["args"],
+ id=chunk["id"],
+ error=None,
+ )
+ )
+
+ for chunk in self.tool_call_chunks:
+ try:
+ args_ = parse_partial_json(chunk["args"]) if chunk["args"] else {}
+ if isinstance(args_, dict):
+ tool_calls.append(
+ create_tool_call(
+ name=chunk["name"] or "",
+ args=args_,
+ id=chunk["id"],
+ )
+ )
+ else:
+ add_chunk_to_invalid_tool_calls(chunk)
+ except Exception:
+ add_chunk_to_invalid_tool_calls(chunk)
+ self.tool_calls = tool_calls
+ self.invalid_tool_calls = invalid_tool_calls
+
+ if (
+ self.chunk_position == "last"
+ and self.tool_call_chunks
+ and self.response_metadata.get("output_version") == "v1"
+ and isinstance(self.content, list)
+ ):
+ id_to_tc: dict[str, types.ToolCall] = {
+ cast("str", tc.get("id")): {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ for tc in self.tool_calls
+ if "id" in tc
+ }
+ for idx, block in enumerate(self.content):
+ if (
+ isinstance(block, dict)
+ and block.get("type") == "tool_call_chunk"
+ and (call_id := block.get("id"))
+ and call_id in id_to_tc
+ ):
+ self.content[idx] = cast("dict[str, Any]", id_to_tc[call_id])
+ if "extras" in block:
+ # mypy does not account for instance check for dict above
+ self.content[idx]["extras"] = block["extras"] # type: ignore[index]
+
+ return self
+
+ @model_validator(mode="after")
+ def init_server_tool_calls(self) -> Self:
+ """Initialize server tool calls.
+
+ Parse `server_tool_call_chunks` from
+ [`ServerToolCallChunk`][langchain.messages.ServerToolCallChunk] objects.
+ """
+ if (
+ self.chunk_position == "last"
+ and self.response_metadata.get("output_version") == "v1"
+ and isinstance(self.content, list)
+ ):
+ for idx, block in enumerate(self.content):
+ if (
+ isinstance(block, dict)
+ and block.get("type")
+ in {"server_tool_call", "server_tool_call_chunk"}
+ and (args_str := block.get("args"))
+ and isinstance(args_str, str)
+ ):
+ try:
+ args = json.loads(args_str)
+ if isinstance(args, dict):
+ self.content[idx]["type"] = "server_tool_call" # type: ignore[index]
+ self.content[idx]["args"] = args # type: ignore[index]
+ except json.JSONDecodeError:
+ pass
+ return self
+
+ @overload # type: ignore[override] # summing BaseMessages gives ChatPromptTemplate
+ def __add__(self, other: "AIMessageChunk") -> "AIMessageChunk": ...
+
+ @overload
+ def __add__(self, other: Sequence["AIMessageChunk"]) -> "AIMessageChunk": ...
+
+ @overload
+ def __add__(self, other: Any) -> BaseMessageChunk: ...
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk:
+ if isinstance(other, AIMessageChunk):
+ return add_ai_message_chunks(self, other)
+ if isinstance(other, (list, tuple)) and all(
+ isinstance(o, AIMessageChunk) for o in other
+ ):
+ return add_ai_message_chunks(self, *other)
+ return super().__add__(other)
+
+
+def add_ai_message_chunks(
+ left: AIMessageChunk, *others: AIMessageChunk
+) -> AIMessageChunk:
+ """Add multiple `AIMessageChunk`s together.
+
+ Args:
+ left: The first `AIMessageChunk`.
+ *others: Other `AIMessageChunk`s to add.
+
+ Returns:
+ The resulting `AIMessageChunk`.
+
+ """
+ content = merge_content(left.content, *(o.content for o in others))
+ additional_kwargs = merge_dicts(
+ left.additional_kwargs, *(o.additional_kwargs for o in others)
+ )
+ response_metadata = merge_dicts(
+ left.response_metadata, *(o.response_metadata for o in others)
+ )
+
+ # Merge tool call chunks
+ if raw_tool_calls := merge_lists(
+ left.tool_call_chunks, *(o.tool_call_chunks for o in others)
+ ):
+ tool_call_chunks = [
+ create_tool_call_chunk(
+ name=rtc.get("name"),
+ args=rtc.get("args"),
+ index=rtc.get("index"),
+ id=rtc.get("id"),
+ )
+ for rtc in raw_tool_calls
+ ]
+ else:
+ tool_call_chunks = []
+
+ # Token usage
+ if left.usage_metadata or any(o.usage_metadata is not None for o in others):
+ usage_metadata: UsageMetadata | None = left.usage_metadata
+ for other in others:
+ usage_metadata = add_usage(usage_metadata, other.usage_metadata)
+ else:
+ usage_metadata = None
+
+ # Ranks are defined by the order of preference. Higher is better:
+ # 2. Provider-assigned IDs (non lc_* and non lc_run-*)
+ # 1. lc_run-* IDs
+ # 0. lc_* and other remaining IDs
+ best_rank = -1
+ chunk_id = None
+ candidates = itertools.chain([left.id], (o.id for o in others))
+
+ for id_ in candidates:
+ if not id_:
+ continue
+
+ if not id_.startswith(LC_ID_PREFIX) and not id_.startswith(LC_AUTO_PREFIX):
+ chunk_id = id_
+ # Highest rank, return instantly
+ break
+
+ rank = 1 if id_.startswith(LC_ID_PREFIX) else 0
+
+ if rank > best_rank:
+ best_rank = rank
+ chunk_id = id_
+
+ chunk_position: Literal["last"] | None = (
+ "last" if any(x.chunk_position == "last" for x in [left, *others]) else None
+ )
+
+ return left.__class__(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_call_chunks,
+ response_metadata=response_metadata,
+ usage_metadata=usage_metadata,
+ id=chunk_id,
+ chunk_position=chunk_position,
+ )
+
+
+def add_usage(left: UsageMetadata | None, right: UsageMetadata | None) -> UsageMetadata:
+ """Recursively add two UsageMetadata objects.
+
+ Example:
+ ```python
+ from langchain_core.messages.ai import add_usage
+
+ left = UsageMetadata(
+ input_tokens=5,
+ output_tokens=0,
+ total_tokens=5,
+ input_token_details=InputTokenDetails(cache_read=3),
+ )
+ right = UsageMetadata(
+ input_tokens=0,
+ output_tokens=10,
+ total_tokens=10,
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+
+ add_usage(left, right)
+ ```
+
+ results in
+
+ ```python
+ UsageMetadata(
+ input_tokens=5,
+ output_tokens=10,
+ total_tokens=15,
+ input_token_details=InputTokenDetails(cache_read=3),
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+ ```
+ Args:
+ left: The first `UsageMetadata` object.
+ right: The second `UsageMetadata` object.
+
+ Returns:
+ The sum of the two `UsageMetadata` objects.
+
+ """
+ if not (left or right):
+ return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
+ if not (left and right):
+ return cast("UsageMetadata", left or right)
+
+ return UsageMetadata(
+ **cast(
+ "UsageMetadata",
+ _dict_int_op(
+ cast("dict", left),
+ cast("dict", right),
+ operator.add,
+ ),
+ )
+ )
+
+
+def subtract_usage(
+ left: UsageMetadata | None, right: UsageMetadata | None
+) -> UsageMetadata:
+ """Recursively subtract two `UsageMetadata` objects.
+
+ Token counts cannot be negative so the actual operation is `max(left - right, 0)`.
+
+ Example:
+ ```python
+ from langchain_core.messages.ai import subtract_usage
+
+ left = UsageMetadata(
+ input_tokens=5,
+ output_tokens=10,
+ total_tokens=15,
+ input_token_details=InputTokenDetails(cache_read=4),
+ )
+ right = UsageMetadata(
+ input_tokens=3,
+ output_tokens=8,
+ total_tokens=11,
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+
+ subtract_usage(left, right)
+ ```
+
+ results in
+
+ ```python
+ UsageMetadata(
+ input_tokens=2,
+ output_tokens=2,
+ total_tokens=4,
+ input_token_details=InputTokenDetails(cache_read=4),
+ output_token_details=OutputTokenDetails(reasoning=0),
+ )
+ ```
+ Args:
+ left: The first `UsageMetadata` object.
+ right: The second `UsageMetadata` object.
+
+ Returns:
+ The resulting `UsageMetadata` after subtraction.
+
+ """
+ if not (left or right):
+ return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
+ if not (left and right):
+ return cast("UsageMetadata", left or right)
+
+ return UsageMetadata(
+ **cast(
+ "UsageMetadata",
+ _dict_int_op(
+ cast("dict", left),
+ cast("dict", right),
+ (lambda le, ri: max(le - ri, 0)),
+ ),
+ )
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/base.py b/python/user_packages/Python313/site-packages/langchain_core/messages/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b0e998c70fdb9a94d91cd0f73a9165e53ca0f19
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/base.py
@@ -0,0 +1,518 @@
+"""Base message."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast, overload
+
+from pydantic import ConfigDict, Field
+
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.load.serializable import Serializable
+from langchain_core.messages import content as types
+from langchain_core.utils import get_bolded_text
+from langchain_core.utils._merge import merge_dicts, merge_lists
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from typing_extensions import Self
+
+ from langchain_core.prompts.chat import ChatPromptTemplate
+
+
+def _extract_reasoning_from_additional_kwargs(
+ message: BaseMessage,
+) -> types.ReasoningContentBlock | None:
+ """Extract `reasoning_content` from `additional_kwargs`.
+
+ Handles reasoning content stored in various formats:
+ - `additional_kwargs["reasoning_content"]` (string) - Ollama, DeepSeek, XAI, Groq
+
+ Args:
+ message: The message to extract reasoning from.
+
+ Returns:
+ A `ReasoningContentBlock` if reasoning content is found, None otherwise.
+ """
+ additional_kwargs = getattr(message, "additional_kwargs", {})
+
+ reasoning_content = additional_kwargs.get("reasoning_content")
+ if reasoning_content is not None and isinstance(reasoning_content, str):
+ return {"type": "reasoning", "reasoning": reasoning_content}
+
+ return None
+
+
+class TextAccessor(str):
+ """String-like object that supports both property and method access patterns.
+
+ Exists to maintain backward compatibility while transitioning from method-based to
+ property-based text access in message objects. In LangChain Self:
+ """Create new TextAccessor instance."""
+ return str.__new__(cls, value)
+
+ def __call__(self) -> str:
+ """Enable method-style text access for backward compatibility.
+
+ This method exists solely to support legacy code that calls `.text()`
+ as a method. New code should use property access (`.text`) instead.
+
+ !!! deprecated
+ As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated.
+ Use `.text` as a property instead. This method will be removed in 2.0.0.
+
+ Returns:
+ The string content, identical to property access.
+
+ """
+ warn_deprecated(
+ since="1.0.0",
+ message=(
+ "Calling .text() as a method is deprecated. "
+ "Use .text as a property instead (e.g., message.text)."
+ ),
+ removal="2.0.0",
+ )
+ return str(self)
+
+
+class BaseMessage(Serializable):
+ """Base abstract message class.
+
+ Messages are the inputs and outputs of a chat model.
+
+ Examples include [`HumanMessage`][langchain.messages.HumanMessage],
+ [`AIMessage`][langchain.messages.AIMessage], and
+ [`SystemMessage`][langchain.messages.SystemMessage].
+ """
+
+ content: str | list[str | dict]
+ """The contents of the message."""
+
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Reserved for additional payload data associated with the message.
+
+ For example, for a message from an AI, this could include tool calls as
+ encoded by the model provider.
+
+ """
+
+ response_metadata: dict = Field(default_factory=dict)
+ """Examples: response headers, logprobs, token counts, model name."""
+
+ type: str
+ """The type of the message. Must be a string that is unique to the message type.
+
+ The purpose of this field is to allow for easy identification of the message type
+ when deserializing messages.
+
+ """
+
+ name: str | None = None
+ """An optional name for the message.
+
+ This can be used to provide a human-readable name for the message.
+
+ Usage of this field is optional, and whether it's used or not is up to the
+ model implementation.
+
+ """
+
+ id: str | None = Field(default=None, coerce_numbers_to_str=True)
+ """An optional unique identifier for the message.
+
+ This should ideally be provided by the provider/model which created the message.
+
+ """
+
+ model_config = ConfigDict(
+ extra="allow",
+ )
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize a `BaseMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The contents of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional arguments to pass to the parent class.
+ """
+ if content_blocks is not None:
+ super().__init__(content=content_blocks, **kwargs)
+ else:
+ super().__init__(content=content, **kwargs)
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """`BaseMessage` is serializable.
+
+ Returns:
+ True
+ """
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "messages"]`
+ """
+ return ["langchain", "schema", "messages"]
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ r"""Load content blocks from the message content.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+
+ """
+ # Needed here to avoid circular import, as these classes import BaseMessages
+ from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
+ _convert_to_v1_from_anthropic_input,
+ )
+ from langchain_core.messages.block_translators.bedrock_converse import ( # noqa: PLC0415
+ _convert_to_v1_from_converse_input,
+ )
+ from langchain_core.messages.block_translators.google_genai import ( # noqa: PLC0415
+ _convert_to_v1_from_genai_input,
+ )
+ from langchain_core.messages.block_translators.langchain_v0 import ( # noqa: PLC0415
+ _convert_v0_multimodal_input_to_v1,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _convert_to_v1_from_chat_completions_input,
+ )
+
+ blocks: list[types.ContentBlock] = []
+ content = (
+ # Transpose string content to list, otherwise assumed to be list
+ [self.content]
+ if isinstance(self.content, str) and self.content
+ else self.content
+ )
+ for item in content:
+ if isinstance(item, str):
+ # Plain string content is treated as a text block
+ blocks.append({"type": "text", "text": item})
+ elif isinstance(item, dict):
+ item_type = item.get("type")
+ if item_type not in types.KNOWN_BLOCK_TYPES:
+ # Handle all provider-specific or None type blocks as non-standard -
+ # we'll come back to these later
+ blocks.append({"type": "non_standard", "value": item})
+ else:
+ # Guard against v0 blocks that share the same `type` keys
+ if "source_type" in item:
+ blocks.append({"type": "non_standard", "value": item})
+ continue
+
+ # This can't be a v0 block (since they require `source_type`),
+ # so it's a known v1 block type
+ blocks.append(cast("types.ContentBlock", item))
+
+ # Subsequent passes: attempt to unpack non-standard blocks.
+ # This is the last stop - if we can't parse it here, it is left as non-standard
+ for parsing_step in [
+ _convert_v0_multimodal_input_to_v1,
+ _convert_to_v1_from_chat_completions_input,
+ _convert_to_v1_from_anthropic_input,
+ _convert_to_v1_from_genai_input,
+ _convert_to_v1_from_converse_input,
+ ]:
+ blocks = parsing_step(blocks)
+ return blocks
+
+ @property
+ def text(self) -> TextAccessor:
+ """Get the text content of the message as a string.
+
+ Can be used as both property (`message.text`) and method (`message.text()`).
+
+ Handles both string and list content types (e.g. for content blocks). Only
+ extracts blocks with `type: 'text'`; other block types are ignored.
+
+ !!! deprecated
+ As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated.
+ Use `.text` as a property instead. This method will be removed in 2.0.0.
+
+ Returns:
+ The text content of the message.
+
+ """
+ if isinstance(self.content, str):
+ text_value = self.content
+ else:
+ # Must be a list
+ blocks = [
+ block
+ for block in self.content
+ if isinstance(block, str)
+ or (block.get("type") == "text" and isinstance(block.get("text"), str))
+ ]
+ text_value = "".join(
+ block if isinstance(block, str) else block["text"] for block in blocks
+ )
+ return TextAccessor(text_value)
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Concatenate this message with another message.
+
+ Args:
+ other: Another message to concatenate with this one.
+
+ Returns:
+ A ChatPromptTemplate containing both messages.
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
+
+ prompt = ChatPromptTemplate(messages=[self])
+ return prompt.__add__(other)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Get a pretty representation of the message.
+
+ Args:
+ html: Whether to format the message as HTML. If `True`, the message will be
+ formatted with HTML tags.
+
+ Returns:
+ A pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage
+
+ msg = HumanMessage(content="What is the capital of France?")
+ print(msg.pretty_repr())
+ ```
+
+ Results in:
+
+ ```txt
+ ================================ Human Message =================================
+
+ What is the capital of France?
+ ```
+ """ # noqa: E501
+ title = get_msg_title_repr(self.type.title() + " Message", bold=html)
+ # TODO: handle non-string content.
+ if self.name is not None:
+ title += f"\nName: {self.name}"
+ return f"{title}\n\n{self.content}"
+
+ def pretty_print(self) -> None:
+ """Print a pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(content="The capital of France is Paris.")
+ msg.pretty_print()
+ ```
+
+ Results in:
+
+ ```txt
+ ================================== Ai Message ==================================
+
+ The capital of France is Paris.
+ ```
+ """ # noqa: E501
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+def merge_content(
+ first_content: str | list[str | dict],
+ *contents: str | list[str | dict],
+) -> str | list[str | dict]:
+ """Merge multiple message contents.
+
+ Args:
+ first_content: The first `content`. Can be a string or a list.
+ contents: The other `content`s. Can be a string or a list.
+
+ Returns:
+ The merged content.
+
+ """
+ merged: str | list[str | dict]
+ merged = "" if first_content is None else first_content
+
+ for content in contents:
+ # If current is a string
+ if isinstance(merged, str):
+ # If the next chunk is also a string, then merge them naively
+ if isinstance(content, str):
+ merged += content
+ # If the next chunk is a list, add the current to the start of the list
+ else:
+ merged = [merged, *content]
+ elif isinstance(content, list):
+ # If both are lists
+ merged = merge_lists(cast("list", merged), content) # type: ignore[assignment]
+ # If the first content is a list, and the second content is a string
+ # If the last element of the first content is a string
+ # Add the second content to the last element
+ elif merged and isinstance(merged[-1], str):
+ merged[-1] += content
+ # If second content is an empty string, treat as a no-op
+ elif content == "":
+ pass
+ # Otherwise, add the second content as a new element of the list
+ elif merged:
+ merged.append(content)
+ return merged
+
+
+class BaseMessageChunk(BaseMessage):
+ """Message chunk, which can be concatenated with other Message chunks."""
+
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ """Message chunks support concatenation with other message chunks.
+
+ This functionality is useful to combine message chunks yielded from
+ a streaming model into a complete message.
+
+ Args:
+ other: Another message chunk to concatenate with this one.
+
+ Returns:
+ A new message chunk that is the concatenation of this message chunk
+ and the other message chunk.
+
+ Raises:
+ TypeError: If the other object is not a message chunk.
+
+ Example:
+ ```txt
+ AIMessageChunk(content="Hello", ...)
+ + AIMessageChunk(content=" World", ...)
+ = AIMessageChunk(content="Hello World", ...)
+ ```
+ """
+ if isinstance(other, BaseMessageChunk):
+ # If both are (subclasses of) BaseMessageChunk,
+ # concat into a single BaseMessageChunk
+
+ return self.__class__(
+ id=self.id,
+ type=self.type,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ )
+ if isinstance(other, list) and all(
+ isinstance(o, BaseMessageChunk) for o in other
+ ):
+ content = merge_content(self.content, *(o.content for o in other))
+ additional_kwargs = merge_dicts(
+ self.additional_kwargs, *(o.additional_kwargs for o in other)
+ )
+ response_metadata = merge_dicts(
+ self.response_metadata, *(o.response_metadata for o in other)
+ )
+ return self.__class__( # type: ignore[call-arg]
+ id=self.id,
+ content=content,
+ additional_kwargs=additional_kwargs,
+ response_metadata=response_metadata,
+ )
+ msg = (
+ 'unsupported operand type(s) for +: "'
+ f"{self.__class__.__name__}"
+ f'" and "{other.__class__.__name__}"'
+ )
+ raise TypeError(msg)
+
+
+def message_to_dict(message: BaseMessage) -> dict:
+ """Convert a Message to a dictionary.
+
+ Args:
+ message: Message to convert.
+
+ Returns:
+ Message as a dict. The dict will have a `type` key with the message type
+ and a `data` key with the message data as a dict.
+
+ """
+ return {"type": message.type, "data": message.model_dump()}
+
+
+def messages_to_dict(messages: Sequence[BaseMessage]) -> list[dict]:
+ """Convert a sequence of Messages to a list of dictionaries.
+
+ Args:
+ messages: Sequence of messages (as `BaseMessage`s) to convert.
+
+ Returns:
+ List of messages as dicts.
+
+ """
+ return [message_to_dict(m) for m in messages]
+
+
+def get_msg_title_repr(title: str, *, bold: bool = False) -> str:
+ """Get a title representation for a message.
+
+ Args:
+ title: The title.
+ bold: Whether to bold the title.
+
+ Returns:
+ The title representation.
+
+ """
+ padded = " " + title + " "
+ sep_len = (80 - len(padded)) // 2
+ sep = "=" * sep_len
+ second_sep = sep + "=" if len(padded) % 2 else sep
+ if bold:
+ padded = get_bolded_text(padded)
+ return f"{sep}{padded}{second_sep}"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ddc2515c421cdc3e43b6a968ab224fe492f322
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__init__.py
@@ -0,0 +1,112 @@
+"""Derivations of standard content blocks from provider content.
+
+`AIMessage` will first attempt to use a provider-specific translator if
+`model_provider` is set in `response_metadata` on the message. Consequently, each
+provider translator must handle all possible content response types from the provider,
+including text.
+
+If no provider is set, or if the provider does not have a registered translator,
+`AIMessage` will fall back to best-effort parsing of the content into blocks using
+the implementation in `BaseMessage`.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from langchain_core.messages import AIMessage, AIMessageChunk
+ from langchain_core.messages import content as types
+
+# Provider to translator mapping
+PROVIDER_TRANSLATORS: dict[str, dict[str, Callable[..., list[types.ContentBlock]]]] = {}
+"""Map model provider names to translator functions.
+
+The dictionary maps provider names (e.g. `'openai'`, `'anthropic'`) to another
+dictionary with two keys:
+- `'translate_content'`: Function to translate `AIMessage` content.
+- `'translate_content_chunk'`: Function to translate `AIMessageChunk` content.
+
+When calling `content_blocks` on an `AIMessage` or `AIMessageChunk`, if
+`model_provider` is set in `response_metadata`, the corresponding translator
+functions will be used to parse the content into blocks. Otherwise, best-effort parsing
+in `BaseMessage` will be used.
+"""
+
+
+def register_translator(
+ provider: str,
+ translate_content: Callable[[AIMessage], list[types.ContentBlock]],
+ translate_content_chunk: Callable[[AIMessageChunk], list[types.ContentBlock]],
+) -> None:
+ """Register content translators for a provider in `PROVIDER_TRANSLATORS`.
+
+ Args:
+ provider: The model provider name (e.g. `'openai'`, `'anthropic'`).
+ translate_content: Function to translate `AIMessage` content.
+ translate_content_chunk: Function to translate `AIMessageChunk` content.
+ """
+ PROVIDER_TRANSLATORS[provider] = {
+ "translate_content": translate_content,
+ "translate_content_chunk": translate_content_chunk,
+ }
+
+
+def get_translator(
+ provider: str,
+) -> dict[str, Callable[..., list[types.ContentBlock]]] | None:
+ """Get the translator functions for a provider.
+
+ Args:
+ provider: The model provider name.
+
+ Returns:
+ Dictionary with `'translate_content'` and `'translate_content_chunk'`
+ functions, or None if no translator is registered for the provider. In such
+ case, best-effort parsing in `BaseMessage` will be used.
+ """
+ return PROVIDER_TRANSLATORS.get(provider)
+
+
+def _register_translators() -> None:
+ """Register all translators in langchain-core.
+
+ A unit test ensures all modules in `block_translators` are represented here.
+
+ For translators implemented outside langchain-core, they can be registered by
+ calling `register_translator` from within the integration package.
+ """
+ from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
+ _register_anthropic_translator,
+ )
+ from langchain_core.messages.block_translators.bedrock import ( # noqa: PLC0415
+ _register_bedrock_translator,
+ )
+ from langchain_core.messages.block_translators.bedrock_converse import ( # noqa: PLC0415
+ _register_bedrock_converse_translator,
+ )
+ from langchain_core.messages.block_translators.google_genai import ( # noqa: PLC0415
+ _register_google_genai_translator,
+ )
+ from langchain_core.messages.block_translators.google_vertexai import ( # noqa: PLC0415
+ _register_google_vertexai_translator,
+ )
+ from langchain_core.messages.block_translators.groq import ( # noqa: PLC0415
+ _register_groq_translator,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _register_openai_translator,
+ )
+
+ _register_bedrock_translator()
+ _register_bedrock_converse_translator()
+ _register_anthropic_translator()
+ _register_google_genai_translator()
+ _register_google_vertexai_translator()
+ _register_groq_translator()
+ _register_openai_translator()
+
+
+_register_translators()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6beb796b5b63db3a5d31eb5ab943a9cacc78a5c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69e20ee808414c75164d015c6aa12ea4591d77e2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a2ca4bcc5951a95c8ab29d84b1700aeefeb6cac
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bb20fe686161ce09445f4fc485888fec6fcd77a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40120aed78b88c4194deb5b4df66e6d3e2fd3e85
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a7ebd702d92af156f048e8e26828c3f0e541f70
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d14508942eb9adeb81ef2064a697e27e5272f821
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8dbd5cf0a2fa9c2160bf7bf2b2473a4d5efce9ac
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94954b4fcbbadcc49a8fb022b5c382e67b8eab9c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/anthropic.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/anthropic.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab2163f07ed58c536231d720c0822e5407ff8a1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/anthropic.py
@@ -0,0 +1,499 @@
+"""Derivations of standard content blocks from Anthropic content."""
+
+import json
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _convert_to_v1_from_anthropic_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Anthropic format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be Anthropic format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with Anthropic blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ block_type = block.get("type")
+
+ if (
+ block_type == "document"
+ and "source" in block
+ and "type" in block["source"]
+ ):
+ if block["source"]["type"] == "base64":
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": block["source"]["data"],
+ "mime_type": block["source"]["media_type"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "url":
+ file_block = {
+ "type": "file",
+ "url": block["source"]["url"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "file":
+ file_block = {
+ "type": "file",
+ "id": block["source"]["file_id"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "text":
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": block["source"]["data"],
+ "mime_type": block.get("media_type", "text/plain"),
+ }
+ _populate_extras(plain_text_block, block, {"type", "source"})
+ yield plain_text_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ block_type == "image"
+ and "source" in block
+ and "type" in block["source"]
+ ):
+ if block["source"]["type"] == "base64":
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": block["source"]["data"],
+ "mime_type": block["source"]["media_type"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ elif block["source"]["type"] == "url":
+ image_block = {
+ "type": "image",
+ "url": block["source"]["url"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ elif block["source"]["type"] == "file":
+ image_block = {
+ "type": "image",
+ "id": block["source"]["file_id"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif block_type in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_citation_to_v1(citation: dict[str, Any]) -> types.Annotation:
+ citation_type = citation.get("type")
+
+ if citation_type == "web_search_result_location":
+ url_citation: types.Citation = {
+ "type": "citation",
+ "cited_text": citation["cited_text"],
+ "url": citation["url"],
+ }
+ if title := citation.get("title"):
+ url_citation["title"] = title
+ known_fields = {"type", "cited_text", "url", "title", "index", "extras"}
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in url_citation:
+ url_citation["extras"] = {}
+ url_citation["extras"][key] = value
+
+ return url_citation
+
+ if citation_type in {
+ "char_location",
+ "content_block_location",
+ "page_location",
+ "search_result_location",
+ }:
+ document_citation: types.Citation = {
+ "type": "citation",
+ "cited_text": citation["cited_text"],
+ }
+ if "document_title" in citation:
+ document_citation["title"] = citation["document_title"]
+ elif title := citation.get("title"):
+ document_citation["title"] = title
+ known_fields = {
+ "type",
+ "cited_text",
+ "document_title",
+ "title",
+ "index",
+ "extras",
+ }
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in document_citation:
+ document_citation["extras"] = {}
+ document_citation["extras"][key] = value
+
+ return document_citation
+
+ return {
+ "type": "non_standard_annotation",
+ "value": citation,
+ }
+
+
+def _convert_to_v1_from_anthropic(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Anthropic message content to v1 format."""
+ if isinstance(message.content, str):
+ content: list[str | dict] = [{"type": "text", "text": message.content}]
+ else:
+ content = message.content
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if citations := block.get("citations"):
+ text_block: types.TextContentBlock = {
+ "type": "text",
+ "text": block.get("text", ""),
+ "annotations": [_convert_citation_to_v1(a) for a in citations],
+ }
+ else:
+ text_block = {"type": "text", "text": block["text"]}
+ if "index" in block:
+ text_block["index"] = block["index"]
+ yield text_block
+
+ elif block_type == "thinking":
+ reasoning_block: types.ReasoningContentBlock = {
+ "type": "reasoning",
+ "reasoning": block.get("thinking", ""),
+ }
+ if "index" in block:
+ reasoning_block["index"] = block["index"]
+ known_fields = {"type", "thinking", "index", "extras"}
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"][key] = block[key]
+ yield reasoning_block
+
+ elif block_type == "tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ chunk = message.tool_call_chunks[0]
+
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ if "caller" in block:
+ tool_call_chunk["extras"] = {"caller": block["caller"]}
+
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+ else:
+ tool_call_block: types.ToolCall | None = None
+ # Non-streaming or gathered chunk
+ if len(message.tool_calls) == 1:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": message.tool_calls[0]["name"],
+ "args": message.tool_calls[0]["args"],
+ "id": message.tool_calls[0].get("id"),
+ }
+ elif call_id := block.get("id"):
+ for tc in message.tool_calls:
+ if tc.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ break
+ if not tool_call_block:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": block.get("name", ""),
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ tool_call_block["index"] = block["index"]
+ if "caller" in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"]["caller"] = block["caller"]
+
+ yield tool_call_block
+
+ elif block_type == "input_json_delta" and isinstance(
+ message, AIMessageChunk
+ ):
+ if len(message.tool_call_chunks) == 1:
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+
+ else:
+ server_tool_call_chunk: types.ServerToolCallChunk = {
+ "type": "server_tool_call_chunk",
+ "args": block.get("partial_json", ""),
+ }
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ yield server_tool_call_chunk
+
+ elif block_type == "server_tool_use":
+ if block.get("name") == "code_execution":
+ server_tool_use_name = "code_interpreter"
+ else:
+ server_tool_use_name = block.get("name", "")
+ if (
+ isinstance(message, AIMessageChunk)
+ and block.get("input") == {}
+ and "partial_json" not in block
+ and message.chunk_position != "last"
+ ):
+ # First chunk in a stream
+ server_tool_call_chunk = {
+ "type": "server_tool_call_chunk",
+ "name": server_tool_use_name,
+ "args": "",
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ known_fields = {"type", "name", "input", "id", "index"}
+ _populate_extras(server_tool_call_chunk, block, known_fields)
+ yield server_tool_call_chunk
+ else:
+ server_tool_call: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": server_tool_use_name,
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+
+ if block.get("input") == {} and "partial_json" in block:
+ try:
+ input_ = json.loads(block["partial_json"])
+ if isinstance(input_, dict):
+ server_tool_call["args"] = input_
+ except json.JSONDecodeError:
+ pass
+
+ if "index" in block:
+ server_tool_call["index"] = block["index"]
+ known_fields = {
+ "type",
+ "name",
+ "input",
+ "partial_json",
+ "id",
+ "index",
+ }
+ _populate_extras(server_tool_call, block, known_fields)
+
+ yield server_tool_call
+
+ elif block_type == "mcp_tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and block.get("input") == {}
+ and "partial_json" not in block
+ and message.chunk_position != "last"
+ ):
+ # First chunk in a stream
+ server_tool_call_chunk = {
+ "type": "server_tool_call_chunk",
+ "name": "remote_mcp",
+ "args": "",
+ "id": block.get("id", ""),
+ }
+ if "name" in block:
+ server_tool_call_chunk["extras"] = {"tool_name": block["name"]}
+ known_fields = {"type", "name", "input", "id", "index"}
+ _populate_extras(server_tool_call_chunk, block, known_fields)
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ yield server_tool_call_chunk
+ else:
+ server_tool_call = {
+ "type": "server_tool_call",
+ "name": "remote_mcp",
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+
+ if block.get("input") == {} and "partial_json" in block:
+ try:
+ input_ = json.loads(block["partial_json"])
+ if isinstance(input_, dict):
+ server_tool_call["args"] = input_
+ except json.JSONDecodeError:
+ pass
+
+ if "name" in block:
+ server_tool_call["extras"] = {"tool_name": block["name"]}
+ known_fields = {
+ "type",
+ "name",
+ "input",
+ "partial_json",
+ "id",
+ "index",
+ }
+ _populate_extras(server_tool_call, block, known_fields)
+ if "index" in block:
+ server_tool_call["index"] = block["index"]
+
+ yield server_tool_call
+
+ elif block_type and block_type.endswith("_tool_result"):
+ server_tool_result: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": block.get("tool_use_id", ""),
+ "status": "success",
+ "extras": {"block_type": block_type},
+ }
+ if output := block.get("content", []):
+ server_tool_result["output"] = output
+ if isinstance(output, dict) and output.get(
+ "error_code" # web_search, code_interpreter
+ ):
+ server_tool_result["status"] = "error"
+ if block.get("is_error"): # mcp_tool_result
+ server_tool_result["status"] = "error"
+ if "index" in block:
+ server_tool_result["index"] = block["index"]
+
+ known_fields = {"type", "tool_use_id", "content", "is_error", "index"}
+ _populate_extras(server_tool_result, block, known_fields)
+
+ yield server_tool_result
+
+ else:
+ new_block: types.NonStandardContentBlock = {
+ "type": "non_standard",
+ "value": block,
+ }
+ if "index" in new_block["value"]:
+ new_block["index"] = new_block["value"].pop("index")
+ yield new_block
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Anthropic content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_anthropic(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with Anthropic content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_anthropic(message)
+
+
+def _register_anthropic_translator() -> None:
+ """Register the Anthropic translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("anthropic", translate_content, translate_content_chunk)
+
+
+_register_anthropic_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37f223016b0bdbd8c611fcc1e0d31e45acfa09b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock.py
@@ -0,0 +1,108 @@
+"""Derivations of standard content blocks from Bedrock content."""
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.block_translators.anthropic import (
+ _convert_to_v1_from_anthropic,
+)
+
+
+def _convert_to_v1_from_bedrock(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert bedrock message content to v1 format."""
+ out = _convert_to_v1_from_anthropic(message)
+
+ content_tool_call_ids = {
+ block.get("id")
+ for block in out
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ if (id_ := tool_call.get("id")) and id_ not in content_tool_call_ids:
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ if "index" in tool_call:
+ tool_call_block["index"] = tool_call["index"] # type: ignore[typeddict-item]
+ if "extras" in tool_call:
+ tool_call_block["extras"] = tool_call["extras"] # type: ignore[typeddict-item]
+ out.append(tool_call_block)
+ return out
+
+
+def _convert_to_v1_from_bedrock_chunk(
+ message: AIMessageChunk,
+) -> list[types.ContentBlock]:
+ """Convert bedrock message chunk content to v1 format."""
+ if (
+ message.content == ""
+ and not message.additional_kwargs
+ and not message.tool_calls
+ ):
+ # Bedrock outputs multiple chunks containing response metadata
+ return []
+
+ out = _convert_to_v1_from_anthropic(message)
+
+ if (
+ message.tool_call_chunks
+ and not message.content
+ and message.chunk_position != "last" # keep tool_calls if aggregated
+ ):
+ for tool_call_chunk in message.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ out.append(tc)
+ return out
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Bedrock content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if "claude" not in message.response_metadata.get("model_name", "").lower():
+ raise NotImplementedError # fall back to best-effort parsing
+ return _convert_to_v1_from_bedrock(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with Bedrock content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ # TODO: add model_name to all Bedrock chunks and update core merging logic
+ # to not append during aggregation. Then raise NotImplementedError here if
+ # not an Anthropic model to fall back to best-effort parsing.
+ return _convert_to_v1_from_bedrock_chunk(message)
+
+
+def _register_bedrock_translator() -> None:
+ """Register the bedrock translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("bedrock", translate_content, translate_content_chunk)
+
+
+_register_bedrock_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock_converse.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock_converse.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2407e72fa460f43bdd889eac488830b4e777893
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/bedrock_converse.py
@@ -0,0 +1,319 @@
+"""Derivations of standard content blocks from Amazon (Bedrock Converse) content."""
+
+import base64
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _convert_to_v1_from_converse_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Bedrock Converse format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be Converse format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with Converse blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ num_keys = len(block)
+
+ if num_keys == 1 and (text := block.get("text")):
+ yield {"type": "text", "text": text}
+
+ elif (
+ num_keys == 1
+ and (document := block.get("document"))
+ and isinstance(document, dict)
+ and "format" in document
+ ):
+ if document.get("format") == "pdf":
+ if "bytes" in document.get("source", {}):
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": _bytes_to_b64_str(document["source"]["bytes"]),
+ "mime_type": "application/pdf",
+ }
+ _populate_extras(file_block, document, {"format", "source"})
+ yield file_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif document["format"] == "txt":
+ if "text" in document.get("source", {}):
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": document["source"]["text"],
+ "mime_type": "text/plain",
+ }
+ _populate_extras(
+ plain_text_block, document, {"format", "source"}
+ )
+ yield plain_text_block
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ num_keys == 1
+ and (image := block.get("image"))
+ and isinstance(image, dict)
+ and "format" in image
+ ):
+ if "bytes" in image.get("source", {}):
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": _bytes_to_b64_str(image["source"]["bytes"]),
+ "mime_type": f"image/{image['format']}",
+ }
+ _populate_extras(image_block, image, {"format", "source"})
+ yield image_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_citation_to_v1(citation: dict[str, Any]) -> types.Annotation:
+ standard_citation: types.Citation = {"type": "citation"}
+ if "title" in citation:
+ standard_citation["title"] = citation["title"]
+ if (
+ (source_content := citation.get("source_content"))
+ and isinstance(source_content, list)
+ and all(isinstance(item, dict) for item in source_content)
+ ):
+ standard_citation["cited_text"] = "".join(
+ item.get("text", "") for item in source_content
+ )
+
+ known_fields = {"type", "source_content", "title", "index", "extras"}
+
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in standard_citation:
+ standard_citation["extras"] = {}
+ standard_citation["extras"][key] = value
+
+ return standard_citation
+
+
+def _convert_to_v1_from_converse(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Bedrock Converse message content to v1 format."""
+ if (
+ message.content == ""
+ and not message.additional_kwargs
+ and not message.tool_calls
+ ):
+ # Converse outputs multiple chunks containing response metadata
+ return []
+
+ if isinstance(message.content, str):
+ message.content = [{"type": "text", "text": message.content}]
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for block in message.content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if citations := block.get("citations"):
+ text_block: types.TextContentBlock = {
+ "type": "text",
+ "text": block.get("text", ""),
+ "annotations": [_convert_citation_to_v1(a) for a in citations],
+ }
+ else:
+ text_block = {"type": "text", "text": block["text"]}
+ if "index" in block:
+ text_block["index"] = block["index"]
+ yield text_block
+
+ elif block_type == "reasoning_content":
+ reasoning_block: types.ReasoningContentBlock = {"type": "reasoning"}
+ if reasoning_content := block.get("reasoning_content"):
+ if reasoning := reasoning_content.get("text"):
+ reasoning_block["reasoning"] = reasoning
+ if signature := reasoning_content.get("signature"):
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"]["signature"] = signature
+
+ if "index" in block:
+ reasoning_block["index"] = block["index"]
+
+ known_fields = {"type", "reasoning_content", "index", "extras"}
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"][key] = block[key]
+ yield reasoning_block
+
+ elif block_type == "tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+ else:
+ tool_call_block: types.ToolCall | None = None
+ # Non-streaming or gathered chunk
+ if len(message.tool_calls) == 1:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": message.tool_calls[0]["name"],
+ "args": message.tool_calls[0]["args"],
+ "id": message.tool_calls[0].get("id"),
+ }
+ elif call_id := block.get("id"):
+ for tc in message.tool_calls:
+ if tc.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ break
+ if not tool_call_block:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": block.get("name", ""),
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ tool_call_block["index"] = block["index"]
+ yield tool_call_block
+
+ elif (
+ block_type == "input_json_delta"
+ and isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ ):
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+
+ else:
+ new_block: types.NonStandardContentBlock = {
+ "type": "non_standard",
+ "value": block,
+ }
+ if "index" in new_block["value"]:
+ new_block["index"] = new_block["value"].pop("index")
+ yield new_block
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Bedrock Converse content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_converse(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a chunk with Bedrock Converse content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_converse(message)
+
+
+def _register_bedrock_converse_translator() -> None:
+ """Register the Bedrock Converse translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("bedrock_converse", translate_content, translate_content_chunk)
+
+
+_register_bedrock_converse_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_genai.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_genai.py
new file mode 100644
index 0000000000000000000000000000000000000000..321de2f2df4a9413507411169a8078f065d5ede9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_genai.py
@@ -0,0 +1,566 @@
+"""Derivations of standard content blocks from Google (GenAI) content."""
+
+import base64
+import re
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.content import Citation, create_citation
+
+try:
+ import filetype # type: ignore[import-not-found]
+
+ _HAS_FILETYPE = True
+except ImportError:
+ _HAS_FILETYPE = False
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ """Convert bytes to base64 encoded string."""
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def translate_grounding_metadata_to_citations(
+ grounding_metadata: dict[str, Any],
+) -> list[Citation]:
+ """Translate Google AI grounding metadata to LangChain Citations.
+
+ Args:
+ grounding_metadata: Google AI grounding metadata containing web search
+ queries, grounding chunks, and grounding supports.
+
+ Returns:
+ List of Citation content blocks derived from the grounding metadata.
+
+ Example:
+ >>> metadata = {
+ ... "web_search_queries": ["UEFA Euro 2024 winner"],
+ ... "grounding_chunks": [
+ ... {
+ ... "web": {
+ ... "uri": "https://uefa.com/euro2024",
+ ... "title": "UEFA Euro 2024 Results",
+ ... }
+ ... }
+ ... ],
+ ... "grounding_supports": [
+ ... {
+ ... "segment": {
+ ... "start_index": 0,
+ ... "end_index": 47,
+ ... "text": "Spain won the UEFA Euro 2024 championship",
+ ... },
+ ... "grounding_chunk_indices": [0],
+ ... }
+ ... ],
+ ... }
+ >>> citations = translate_grounding_metadata_to_citations(metadata)
+ >>> len(citations)
+ 1
+ >>> citations[0]["url"]
+ 'https://uefa.com/euro2024'
+ """
+ if not grounding_metadata:
+ return []
+
+ grounding_chunks = grounding_metadata.get("grounding_chunks", [])
+ grounding_supports = grounding_metadata.get("grounding_supports", [])
+ web_search_queries = grounding_metadata.get("web_search_queries", [])
+
+ citations: list[Citation] = []
+
+ for support in grounding_supports:
+ segment = support.get("segment", {})
+ chunk_indices = support.get("grounding_chunk_indices", [])
+
+ start_index = segment.get("start_index")
+ end_index = segment.get("end_index")
+ cited_text = segment.get("text")
+
+ # Create a citation for each referenced chunk
+ for chunk_index in chunk_indices:
+ if chunk_index < len(grounding_chunks):
+ chunk = grounding_chunks[chunk_index]
+
+ # Handle web and maps grounding
+ web_info = chunk.get("web") or {}
+ maps_info = chunk.get("maps") or {}
+
+ # Extract citation info depending on source
+ url = maps_info.get("uri") or web_info.get("uri")
+ title = maps_info.get("title") or web_info.get("title")
+
+ # Note: confidence_scores is a legacy field from Gemini 2.0 and earlier
+ # that indicated confidence (0.0-1.0) for each grounding chunk.
+ #
+ # In Gemini 2.5+, this field is always None/empty and should be ignored.
+ extras_metadata = {
+ "web_search_queries": web_search_queries,
+ "grounding_chunk_index": chunk_index,
+ "confidence_scores": support.get("confidence_scores") or [],
+ }
+
+ # Add maps-specific metadata if present
+ if maps_info.get("placeId"):
+ extras_metadata["place_id"] = maps_info["placeId"]
+
+ citation = create_citation(
+ url=url,
+ title=title,
+ start_index=start_index,
+ end_index=end_index,
+ cited_text=cited_text,
+ google_ai_metadata=extras_metadata,
+ )
+ citations.append(citation)
+
+ return citations
+
+
+def _convert_to_v1_from_genai_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Google GenAI format blocks to v1 format.
+
+ Called when message isn't an `AIMessage` or `model_provider` isn't set on
+ `response_metadata`.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be GenAI format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with GenAI blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ num_keys = len(block)
+ block_type = block.get("type")
+
+ if num_keys == 1 and (text := block.get("text")):
+ # This is probably a TextContentBlock
+ yield {"type": "text", "text": text}
+
+ elif (
+ num_keys == 1
+ and (document := block.get("document"))
+ and isinstance(document, dict)
+ and "format" in document
+ ):
+ # Handle document format conversion
+ doc_format = document.get("format")
+ source = document.get("source", {})
+
+ if doc_format == "pdf" and "bytes" in source:
+ # PDF document with byte data
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": source["bytes"]
+ if isinstance(source["bytes"], str)
+ else _bytes_to_b64_str(source["bytes"]),
+ "mime_type": "application/pdf",
+ }
+ # Preserve extra fields
+ extras = {
+ key: value
+ for key, value in document.items()
+ if key not in {"format", "source"}
+ }
+ if extras:
+ file_block["extras"] = extras
+ yield file_block
+
+ elif doc_format == "txt" and "text" in source:
+ # Text document
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": source["text"],
+ "mime_type": "text/plain",
+ }
+ # Preserve extra fields
+ extras = {
+ key: value
+ for key, value in document.items()
+ if key not in {"format", "source"}
+ }
+ if extras:
+ plain_text_block["extras"] = extras
+ yield plain_text_block
+
+ else:
+ # Unknown document format
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ num_keys == 1
+ and (image := block.get("image"))
+ and isinstance(image, dict)
+ and "format" in image
+ ):
+ # Handle image format conversion
+ img_format = image.get("format")
+ source = image.get("source", {})
+
+ if "bytes" in source:
+ # Image with byte data
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": source["bytes"]
+ if isinstance(source["bytes"], str)
+ else _bytes_to_b64_str(source["bytes"]),
+ "mime_type": f"image/{img_format}",
+ }
+ # Preserve extra fields
+ extras = {}
+ for key, value in image.items():
+ if key not in {"format", "source"}:
+ extras[key] = value
+ if extras:
+ image_block["extras"] = extras
+ yield image_block
+
+ else:
+ # Image without byte data
+ yield {"type": "non_standard", "value": block}
+
+ elif block_type == "file_data" and "file_uri" in block:
+ # Handle FileData URI-based content
+ uri_file_block: types.FileContentBlock = {
+ "type": "file",
+ "url": block["file_uri"],
+ }
+ if mime_type := block.get("mime_type"):
+ uri_file_block["mime_type"] = mime_type
+ yield uri_file_block
+
+ elif block_type == "function_call" and "name" in block:
+ # Handle function calls
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "name": block["name"],
+ "args": block.get("args", {}),
+ "id": block.get("id", ""),
+ }
+ yield tool_call_block
+
+ elif block_type == "executable_code":
+ server_tool_call_input: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "args": {
+ "code": block.get("executable_code", ""),
+ "language": block.get("language", "python"),
+ },
+ "id": block.get("id", ""),
+ }
+ yield server_tool_call_input
+
+ elif block_type == "code_execution_result":
+ outcome = block.get("outcome", 1)
+ status = "success" if outcome == 1 else "error"
+ server_tool_result_input: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": block.get("tool_call_id", ""),
+ "status": status, # type: ignore[typeddict-item]
+ "output": block.get("code_execution_result", ""),
+ }
+ if outcome is not None:
+ server_tool_result_input["extras"] = {"outcome": outcome}
+ yield server_tool_result_input
+
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ # We see a standard block type, so we just cast it, even if
+ # we don't fully understand it. This may be dangerous, but
+ # it's better than losing information.
+ yield cast("types.ContentBlock", block)
+
+ else:
+ # We don't understand this block at all.
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_to_v1_from_genai(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Google GenAI message content to v1 format.
+
+ Calling `.content_blocks` on an `AIMessage` where `response_metadata.model_provider`
+ is set to `'google_genai'` will invoke this function to parse the content into
+ standard content blocks for returning.
+
+ Args:
+ message: The `AIMessage` or `AIMessageChunk` to convert.
+
+ Returns:
+ List of standard content blocks derived from the message content.
+ """
+ if isinstance(message.content, str):
+ # String content -> TextContentBlock (only add if non-empty in case of audio)
+ string_blocks: list[types.ContentBlock] = []
+ if message.content:
+ string_blocks.append({"type": "text", "text": message.content})
+
+ # Add any missing tool calls from message.tool_calls field
+ content_tool_call_ids = {
+ block.get("id")
+ for block in string_blocks
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ id_ = tool_call.get("id")
+ if id_ and id_ not in content_tool_call_ids:
+ string_tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ string_blocks.append(string_tool_call_block)
+
+ # Handle audio from additional_kwargs if present (for empty content cases)
+ audio_data = message.additional_kwargs.get("audio")
+ if audio_data and isinstance(audio_data, bytes):
+ audio_block: types.AudioContentBlock = {
+ "type": "audio",
+ "base64": _bytes_to_b64_str(audio_data),
+ "mime_type": "audio/wav", # Default to WAV for Google GenAI
+ }
+ string_blocks.append(audio_block)
+
+ grounding_metadata = message.response_metadata.get("grounding_metadata")
+ if grounding_metadata:
+ citations = translate_grounding_metadata_to_citations(grounding_metadata)
+
+ for block in string_blocks:
+ if block["type"] == "text" and citations:
+ # Add citations to the first text block only
+ block["annotations"] = cast("list[types.Annotation]", citations)
+ break
+
+ return string_blocks
+
+ if not isinstance(message.content, list):
+ # Unexpected content type, attempt to represent as text
+ return [{"type": "text", "text": str(message.content)}]
+
+ converted_blocks: list[types.ContentBlock] = []
+
+ for item in message.content:
+ if isinstance(item, str):
+ # Conversation history strings
+
+ # Citations are handled below after all blocks are converted
+ converted_blocks.append({"type": "text", "text": item}) # TextContentBlock
+
+ elif isinstance(item, dict):
+ item_type = item.get("type")
+ if item_type == "image_url":
+ # Convert image_url to standard image block (base64)
+ # (since the original implementation returned as url-base64 CC style)
+ image_url = item.get("image_url", {})
+ url = image_url.get("url", "")
+ if url:
+ # Extract base64 data
+ match = re.match(r"data:([^;]+);base64,(.+)", url)
+ if match:
+ # Data URI provided
+ mime_type, base64_data = match.groups()
+ converted_blocks.append(
+ {
+ "type": "image",
+ "base64": base64_data,
+ "mime_type": mime_type,
+ }
+ )
+ else:
+ # Assume it's raw base64 without data URI
+ try:
+ # Validate base64 and decode for MIME type detection
+ decoded_bytes = base64.b64decode(url, validate=True)
+
+ image_url_b64_block = {
+ "type": "image",
+ "base64": url,
+ }
+
+ if _HAS_FILETYPE:
+ # Guess MIME type based on file bytes
+ mime_type = None
+ kind = filetype.guess(decoded_bytes)
+ if kind:
+ mime_type = kind.mime
+ if mime_type:
+ image_url_b64_block["mime_type"] = mime_type
+
+ converted_blocks.append(
+ cast("types.ImageContentBlock", image_url_b64_block)
+ )
+ except Exception:
+ # Not valid base64, treat as non-standard
+ converted_blocks.append(
+ {
+ "type": "non_standard",
+ "value": item,
+ }
+ )
+ else:
+ # This likely won't be reached according to previous implementations
+ converted_blocks.append({"type": "non_standard", "value": item})
+ msg = "Image URL not a data URI; appending as non-standard block."
+ raise ValueError(msg)
+ elif item_type == "function_call":
+ # Handle Google GenAI function calls
+ function_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "name": item.get("name", ""),
+ "args": item.get("args", {}),
+ "id": item.get("id", ""),
+ }
+ converted_blocks.append(function_call_block)
+ elif item_type == "file_data":
+ # Handle FileData URI-based content
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "url": item.get("file_uri", ""),
+ }
+ if mime_type := item.get("mime_type"):
+ file_block["mime_type"] = mime_type
+ converted_blocks.append(file_block)
+ elif item_type == "thinking":
+ # Handling for the 'thinking' type we package thoughts as
+ reasoning_block: types.ReasoningContentBlock = {
+ "type": "reasoning",
+ "reasoning": item.get("thinking", ""),
+ }
+ if signature := item.get("signature"):
+ reasoning_block["extras"] = {"signature": signature}
+
+ converted_blocks.append(reasoning_block)
+ elif item_type == "executable_code":
+ # Convert to standard server tool call block at the moment
+ server_tool_call_block: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "args": {
+ "code": item.get("executable_code", ""),
+ "language": item.get("language", "python"), # Default to python
+ },
+ "id": item.get("id", ""),
+ }
+ converted_blocks.append(server_tool_call_block)
+ elif item_type == "code_execution_result":
+ # Map outcome to status: OUTCOME_OK (1) → success, else → error
+ outcome = item.get("outcome", 1)
+ status = "success" if outcome == 1 else "error"
+ server_tool_result_block: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": item.get("tool_call_id", ""),
+ "status": status, # type: ignore[typeddict-item]
+ "output": item.get("code_execution_result", ""),
+ }
+ server_tool_result_block["extras"] = {"block_type": item_type}
+ # Preserve original outcome in extras
+ if outcome is not None:
+ server_tool_result_block["extras"]["outcome"] = outcome
+ converted_blocks.append(server_tool_result_block)
+ elif item_type == "text":
+ converted_blocks.append(cast("types.TextContentBlock", item))
+ else:
+ # Unknown type, preserve as non-standard
+ converted_blocks.append({"type": "non_standard", "value": item})
+ else:
+ # Non-dict, non-string content
+ converted_blocks.append({"type": "non_standard", "value": item})
+
+ grounding_metadata = message.response_metadata.get("grounding_metadata")
+ if grounding_metadata:
+ citations = translate_grounding_metadata_to_citations(grounding_metadata)
+
+ for block in converted_blocks:
+ if block["type"] == "text" and citations:
+ # Add citations to text blocks (only the first text block)
+ block["annotations"] = cast("list[types.Annotation]", citations)
+ break
+
+ # Audio is stored on the message.additional_kwargs
+ audio_data = message.additional_kwargs.get("audio")
+ if audio_data and isinstance(audio_data, bytes):
+ audio_block_kwargs: types.AudioContentBlock = {
+ "type": "audio",
+ "base64": _bytes_to_b64_str(audio_data),
+ "mime_type": "audio/wav", # Default to WAV for Google GenAI
+ }
+ converted_blocks.append(audio_block_kwargs)
+
+ # Add any missing tool calls from message.tool_calls field
+ content_tool_call_ids = {
+ block.get("id")
+ for block in converted_blocks
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ id_ = tool_call.get("id")
+ if id_ and id_ not in content_tool_call_ids:
+ missing_tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ converted_blocks.append(missing_tool_call_block)
+
+ return converted_blocks
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Google (GenAI) content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_genai(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a chunk with Google (GenAI) content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_genai(message)
+
+
+def _register_google_genai_translator() -> None:
+ """Register the Google (GenAI) translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("google_genai", translate_content, translate_content_chunk)
+
+
+_register_google_genai_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_vertexai.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_vertexai.py
new file mode 100644
index 0000000000000000000000000000000000000000..016f146164ece69d481444f8df0342784949d1c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/google_vertexai.py
@@ -0,0 +1,21 @@
+"""Derivations of standard content blocks from Google (VertexAI) content."""
+
+from langchain_core.messages.block_translators.google_genai import (
+ translate_content,
+ translate_content_chunk,
+)
+
+
+def _register_google_vertexai_translator() -> None:
+ """Register the Google (VertexAI) translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("google_vertexai", translate_content, translate_content_chunk)
+
+
+_register_google_vertexai_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/groq.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/groq.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcaa1a15b7d40d252f612ff4869de1d972af20dd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/groq.py
@@ -0,0 +1,157 @@
+"""Derivations of standard content blocks from Groq content."""
+
+import json
+import re
+from typing import Any
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.base import _extract_reasoning_from_additional_kwargs
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _parse_code_json(s: str) -> dict:
+ """Extract Python code from Groq built-in tool content.
+
+ Extracts the value of the 'code' field from a string of the form:
+ {"code": some_arbitrary_text_with_unescaped_quotes}
+
+ As Groq may not escape quotes in the executed tools, e.g.:
+ ```
+ '{"code": "import math; print("The square root of 101 is: "); print(math.sqrt(101))"}'
+ ```
+ """ # noqa: E501
+ m = re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags=re.DOTALL)
+ if not m:
+ msg = (
+ "Could not extract Python code from Groq tool arguments. "
+ "Expected a JSON object with a 'code' field."
+ )
+ raise ValueError(msg)
+ return {"code": m.group(1)}
+
+
+def _convert_to_v1_from_groq(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert groq message content to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+
+ if reasoning_block := _extract_reasoning_from_additional_kwargs(message):
+ content_blocks.append(reasoning_block)
+
+ if executed_tools := message.additional_kwargs.get("executed_tools"):
+ for idx, executed_tool in enumerate(executed_tools):
+ args: dict[str, Any] | None = None
+ if arguments := executed_tool.get("arguments"):
+ try:
+ args = json.loads(arguments)
+ except json.JSONDecodeError:
+ if executed_tool.get("type") == "python":
+ try:
+ args = _parse_code_json(arguments)
+ except ValueError:
+ continue
+ elif (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ # GPT-OSS
+ args = {"code": arguments}
+ else:
+ continue
+ if isinstance(args, dict):
+ name = ""
+ if executed_tool.get("type") == "search":
+ name = "web_search"
+ elif executed_tool.get("type") == "python" or (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ name = "code_interpreter"
+ server_tool_call: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": name,
+ "id": str(idx),
+ "args": args,
+ }
+ content_blocks.append(server_tool_call)
+ if tool_output := executed_tool.get("output"):
+ tool_result: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": str(idx),
+ "output": tool_output,
+ "status": "success",
+ }
+ known_fields = {"type", "arguments", "index", "output"}
+ _populate_extras(tool_result, executed_tool, known_fields)
+ content_blocks.append(tool_result)
+
+ if isinstance(message.content, str) and message.content:
+ content_blocks.append({"type": "text", "text": message.content})
+
+ content_blocks.extend(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ for tool_call in message.tool_calls
+ )
+
+ return content_blocks
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with groq content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_groq(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with groq content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_groq(message)
+
+
+def _register_groq_translator() -> None:
+ """Register the groq translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("groq", translate_content, translate_content_chunk)
+
+
+_register_groq_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/langchain_v0.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/langchain_v0.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7cb03839e8904df69a10da1a831ee2c03b2c7e3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/langchain_v0.py
@@ -0,0 +1,301 @@
+"""Derivations of standard content blocks from LangChain v0 multimodal content."""
+
+from typing import Any, cast
+
+from langchain_core.messages import content as types
+
+
+def _convert_v0_multimodal_input_to_v1(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert v0 multimodal blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any v0 format
+ blocks to v1 format.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ v1 content blocks.
+ """
+ converted_blocks = []
+ unpacked_blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in unpacked_blocks:
+ if block.get("type") in {"image", "audio", "file"} and "source_type" in block:
+ converted_block = _convert_legacy_v0_content_block_to_v1(block)
+ converted_blocks.append(cast("types.ContentBlock", converted_block))
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ # Guard in case this function is used outside of the .content_blocks flow
+ converted_blocks.append(cast("types.ContentBlock", block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+
+ return converted_blocks
+
+
+def _convert_legacy_v0_content_block_to_v1(
+ block: dict,
+) -> types.ContentBlock | dict:
+ """Convert a LangChain v0 content block to v1 format.
+
+ Preserves unknown keys as extras to avoid data loss.
+
+ Returns the original block unchanged if it's not in v0 format.
+ """
+
+ def _extract_v0_extras(block_dict: dict, known_keys: set[str]) -> dict[str, Any]:
+ """Extract unknown keys from v0 block to preserve as extras.
+
+ Args:
+ block_dict: The original v0 block dictionary.
+ known_keys: Set of keys known to be part of the v0 format for this block.
+
+ Returns:
+ A dictionary of extra keys not part of the known v0 format.
+ """
+ return {k: v for k, v in block_dict.items() if k not in known_keys}
+
+ # Check if this is actually a v0 format block
+ block_type = block.get("type")
+ if block_type not in {"image", "audio", "file"} or "source_type" not in block:
+ # Not a v0 format block, return unchanged
+ return block
+
+ if block.get("type") == "image":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # image-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_image_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ # Don't construct with an ID if not present in original block
+ v1_image_url = types.ImageContentBlock(type="image", url=block["url"])
+ if block.get("mime_type"):
+ v1_image_url["mime_type"] = block["mime_type"]
+
+ v1_image_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_url["extras"][key] = value
+ if v1_image_url["extras"] == {}:
+ del v1_image_url["extras"]
+
+ return v1_image_url
+ if source_type == "base64":
+ # image-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_image_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_image_base64 = types.ImageContentBlock(
+ type="image", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_image_base64["mime_type"] = block["mime_type"]
+
+ v1_image_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_base64["extras"][key] = value
+ if v1_image_base64["extras"] == {}:
+ del v1_image_base64["extras"]
+
+ return v1_image_base64
+ if source_type == "id":
+ # image-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ # For id `source_type`, `id` is the file reference, not block ID
+ v1_image_id = types.ImageContentBlock(type="image", file_id=block["id"])
+
+ v1_image_id["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_id["extras"][key] = value
+ if v1_image_id["extras"] == {}:
+ del v1_image_id["extras"]
+
+ return v1_image_id
+ elif block.get("type") == "audio":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # audio-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_audio_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ # Don't construct with an ID if not present in original block
+ v1_audio_url: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", url=block["url"]
+ )
+ if block.get("mime_type"):
+ v1_audio_url["mime_type"] = block["mime_type"]
+
+ v1_audio_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_url["extras"][key] = value
+ if v1_audio_url["extras"] == {}:
+ del v1_audio_url["extras"]
+
+ return v1_audio_url
+ if source_type == "base64":
+ # audio-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_audio_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_audio_base64: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_audio_base64["mime_type"] = block["mime_type"]
+
+ v1_audio_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_base64["extras"][key] = value
+ if v1_audio_base64["extras"] == {}:
+ del v1_audio_base64["extras"]
+
+ return v1_audio_base64
+ if source_type == "id":
+ # audio-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ v1_audio_id: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", file_id=block["id"]
+ )
+
+ v1_audio_id["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_id["extras"][key] = value
+ if v1_audio_id["extras"] == {}:
+ del v1_audio_id["extras"]
+
+ return v1_audio_id
+ elif block.get("type") == "file":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # file-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_file_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_url: types.FileContentBlock = types.FileContentBlock(
+ type="file", url=block["url"]
+ )
+ if block.get("mime_type"):
+ v1_file_url["mime_type"] = block["mime_type"]
+
+ v1_file_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_url["extras"][key] = value
+ if v1_file_url["extras"] == {}:
+ del v1_file_url["extras"]
+
+ return v1_file_url
+ if source_type == "base64":
+ # file-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_file_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_base64: types.FileContentBlock = types.FileContentBlock(
+ type="file", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_file_base64["mime_type"] = block["mime_type"]
+
+ v1_file_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_base64["extras"][key] = value
+ if v1_file_base64["extras"] == {}:
+ del v1_file_base64["extras"]
+
+ return v1_file_base64
+ if source_type == "id":
+ # file-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ return types.create_file_block(file_id=block["id"], **extras)
+ if source_type == "text":
+ # file-text
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_plaintext_block(
+ # In v0, URL points to the text file content
+ # TODO: attribute this claim
+ text=block["url"],
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_text: types.PlainTextContentBlock = types.PlainTextContentBlock(
+ type="text-plain", text=block["url"], mime_type="text/plain"
+ )
+ if block.get("mime_type"):
+ v1_file_text["mime_type"] = block["mime_type"]
+
+ v1_file_text["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_text["extras"][key] = value
+ if v1_file_text["extras"] == {}:
+ del v1_file_text["extras"]
+
+ return v1_file_text
+
+ # If we can't convert, return the block unchanged
+ return block
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/openai.py b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..627459254c5ea2d59c197047abfeab36f0ab0a07
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/block_translators/openai.py
@@ -0,0 +1,1086 @@
+"""Derivations of standard content blocks from OpenAI content."""
+
+from __future__ import annotations
+
+import json
+import warnings
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from langchain_core.language_models._utils import (
+ _parse_data_uri,
+ is_openai_data_block,
+)
+from langchain_core.messages import AIMessageChunk
+from langchain_core.messages import content as types
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ from langchain_core.messages import AIMessage
+
+
+def convert_to_openai_image_block(block: dict[str, Any]) -> dict:
+ """Convert `ImageContentBlock` to format expected by OpenAI Chat Completions.
+
+ Args:
+ block: The image content block to convert.
+
+ Raises:
+ ValueError: If required keys are missing.
+ ValueError: If source type is unsupported.
+
+ Returns:
+ The formatted image content block.
+ """
+ if "url" in block:
+ return {
+ "type": "image_url",
+ "image_url": {
+ "url": block["url"],
+ },
+ }
+ if "base64" in block or block.get("source_type") == "base64":
+ if "mime_type" not in block:
+ error_message = "mime_type key is required for base64 data."
+ raise ValueError(error_message)
+ mime_type = block["mime_type"]
+ base64_data = block["data"] if "data" in block else block["base64"]
+ return {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:{mime_type};base64,{base64_data}",
+ },
+ }
+ error_message = "Unsupported source type. Only 'url' and 'base64' are supported."
+ raise ValueError(error_message)
+
+
+def convert_to_openai_data_block(
+ block: dict, api: Literal["chat/completions", "responses"] = "chat/completions"
+) -> dict:
+ """Format standard data content block to format expected by OpenAI.
+
+ "Standard data content block" can include old-style LangChain v0 blocks
+ (URLContentBlock, Base64ContentBlock, IDContentBlock) or new ones.
+
+ Args:
+ block: The content block to convert.
+ api: The OpenAI API being targeted. Either "chat/completions" or "responses".
+
+ Raises:
+ ValueError: If required keys are missing.
+ ValueError: If file URLs are used with Chat Completions API.
+ ValueError: If block type is unsupported.
+
+ Returns:
+ The formatted content block.
+ """
+ if block["type"] == "image":
+ chat_completions_block = convert_to_openai_image_block(block)
+ if api == "responses":
+ formatted_block = {
+ "type": "input_image",
+ "image_url": chat_completions_block["image_url"]["url"],
+ }
+ if chat_completions_block["image_url"].get("detail"):
+ formatted_block["detail"] = chat_completions_block["image_url"][
+ "detail"
+ ]
+ else:
+ formatted_block = chat_completions_block
+
+ elif block["type"] == "file":
+ if block.get("source_type") == "base64" or "base64" in block:
+ # Handle v0 format (Base64CB): {"source_type": "base64", "data": "...", ...}
+ # Handle v1 format (IDCB): {"base64": "...", ...}
+ base64_data = block["data"] if "source_type" in block else block["base64"]
+ file = {"file_data": f"data:{block['mime_type']};base64,{base64_data}"}
+ if filename := block.get("filename"):
+ file["filename"] = filename
+ elif (extras := block.get("extras")) and ("filename" in extras):
+ file["filename"] = extras["filename"]
+ elif (extras := block.get("metadata")) and ("filename" in extras):
+ # Backward compat
+ file["filename"] = extras["filename"]
+ else:
+ # Can't infer filename; set a placeholder default for compatibility.
+ file["filename"] = "LC_AUTOGENERATED"
+ warnings.warn(
+ "OpenAI may require a filename for file uploads. Specify a filename"
+ " in the content block, e.g.: {'type': 'file', 'mime_type': "
+ "'...', 'base64': '...', 'filename': 'my-file.pdf'}. "
+ "Using placeholder filename 'LC_AUTOGENERATED'.",
+ stacklevel=1,
+ )
+ formatted_block = {"type": "file", "file": file}
+ if api == "responses":
+ formatted_block = {"type": "input_file", **formatted_block["file"]}
+ elif block.get("source_type") == "id" or "file_id" in block:
+ # Handle v0 format (IDContentBlock): {"source_type": "id", "id": "...", ...}
+ # Handle v1 format (IDCB): {"file_id": "...", ...}
+ file_id = block["id"] if "source_type" in block else block["file_id"]
+ formatted_block = {"type": "file", "file": {"file_id": file_id}}
+ if api == "responses":
+ formatted_block = {"type": "input_file", **formatted_block["file"]}
+ elif "url" in block: # Intentionally do not check for source_type="url"
+ if api == "chat/completions":
+ error_msg = "OpenAI Chat Completions does not support file URLs."
+ raise ValueError(error_msg)
+ # Only supported by Responses API; return in that format
+ formatted_block = {"type": "input_file", "file_url": block["url"]}
+ else:
+ error_msg = "Keys base64, url, or file_id required for file blocks."
+ raise ValueError(error_msg)
+
+ elif block["type"] == "audio":
+ if "base64" in block or block.get("source_type") == "base64":
+ # Handle v0 format: {"source_type": "base64", "data": "...", ...}
+ # Handle v1 format: {"base64": "...", ...}
+ base64_data = block["data"] if "source_type" in block else block["base64"]
+ audio_format = block["mime_type"].split("/")[-1]
+ formatted_block = {
+ "type": "input_audio",
+ "input_audio": {"data": base64_data, "format": audio_format},
+ }
+ else:
+ error_msg = "Key base64 is required for audio blocks."
+ raise ValueError(error_msg)
+ else:
+ error_msg = f"Block of type {block['type']} is not supported."
+ raise ValueError(error_msg)
+
+ return formatted_block
+
+
+# v1 / Chat Completions
+def _convert_to_v1_from_chat_completions(
+ message: AIMessage,
+) -> list[types.ContentBlock]:
+ """Mutate a Chat Completions message to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+ if isinstance(message.content, str):
+ if message.content:
+ content_blocks = [{"type": "text", "text": message.content}]
+ else:
+ content_blocks = []
+
+ for tool_call in message.tool_calls:
+ content_blocks.append(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ )
+
+ return content_blocks
+
+
+def _convert_to_v1_from_chat_completions_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert OpenAI Chat Completions format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be OpenAI format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with OpenAI blocks converted to v1 format.
+ """
+ converted_blocks = []
+ unpacked_blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in unpacked_blocks:
+ if block.get("type") in {
+ "image_url",
+ "input_audio",
+ "file",
+ } and is_openai_data_block(block):
+ converted_block = _convert_openai_format_to_data_block(block)
+ # If conversion succeeded, use it; otherwise keep as non_standard
+ if (
+ isinstance(converted_block, dict)
+ and converted_block.get("type") in types.KNOWN_BLOCK_TYPES
+ ):
+ converted_blocks.append(cast("types.ContentBlock", converted_block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ converted_blocks.append(cast("types.ContentBlock", block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+
+ return converted_blocks
+
+
+def _convert_to_v1_from_chat_completions_chunk(
+ chunk: AIMessageChunk,
+) -> list[types.ContentBlock]:
+ """Mutate a Chat Completions chunk to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+ if isinstance(chunk.content, str):
+ if chunk.content:
+ content_blocks = [{"type": "text", "text": chunk.content}]
+ else:
+ content_blocks = []
+
+ if chunk.chunk_position == "last":
+ for tool_call in chunk.tool_calls:
+ content_blocks.append(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ )
+
+ else:
+ for tool_call_chunk in chunk.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ content_blocks.append(tc)
+
+ return content_blocks
+
+
+def _convert_from_v1_to_chat_completions(message: AIMessage) -> AIMessage:
+ """Convert a v1 message to the Chat Completions format."""
+ if isinstance(message.content, list):
+ new_content: list = []
+ for block in message.content:
+ if isinstance(block, dict):
+ block_type = block.get("type")
+ if block_type == "text":
+ # Strip annotations
+ new_content.append({"type": "text", "text": block["text"]})
+ elif block_type in {"reasoning", "tool_call"}:
+ pass
+ else:
+ new_content.append(block)
+ else:
+ new_content.append(block)
+ return message.model_copy(update={"content": new_content})
+
+ return message
+
+
+# Responses
+_FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"
+
+
+def _convert_from_v03_ai_message(message: AIMessage) -> AIMessage:
+ """Convert v0 AIMessage into `output_version="responses/v1"` format."""
+ # Only update ChatOpenAI v0.3 AIMessages
+ is_chatopenai_v03 = (
+ isinstance(message.content, list)
+ and all(isinstance(b, dict) for b in message.content)
+ ) and (
+ any(
+ item in message.additional_kwargs
+ for item in [
+ "reasoning",
+ "tool_outputs",
+ "refusal",
+ _FUNCTION_CALL_IDS_MAP_KEY,
+ ]
+ )
+ or (
+ isinstance(message.id, str)
+ and message.id.startswith("msg_")
+ and (response_id := message.response_metadata.get("id"))
+ and isinstance(response_id, str)
+ and response_id.startswith("resp_")
+ )
+ )
+ if not is_chatopenai_v03:
+ return message
+
+ content_order = [
+ "reasoning",
+ "code_interpreter_call",
+ "mcp_call",
+ "image_generation_call",
+ "text",
+ "refusal",
+ "function_call",
+ "computer_call",
+ "mcp_list_tools",
+ "mcp_approval_request",
+ # N. B. "web_search_call" and "file_search_call" were not passed back in
+ # in v0.3
+ ]
+
+ # Build a bucket for every known block type
+ buckets: dict[str, list] = {key: [] for key in content_order}
+ unknown_blocks = []
+
+ # Reasoning
+ if reasoning := message.additional_kwargs.get("reasoning"):
+ if "type" not in reasoning:
+ reasoning = {**reasoning, "type": "reasoning"}
+ buckets["reasoning"].append(reasoning)
+
+ # Refusal
+ if refusal := message.additional_kwargs.get("refusal"):
+ buckets["refusal"].append({"type": "refusal", "refusal": refusal})
+
+ # Text
+ for block in message.content:
+ if isinstance(block, dict) and block.get("type") == "text":
+ block_copy = block.copy()
+ if isinstance(message.id, str) and message.id.startswith("msg_"):
+ block_copy["id"] = message.id
+ buckets["text"].append(block_copy)
+ else:
+ unknown_blocks.append(block)
+
+ # Function calls
+ function_call_ids = message.additional_kwargs.get(_FUNCTION_CALL_IDS_MAP_KEY)
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ tool_call_chunk = message.tool_call_chunks[0]
+ function_call = {
+ "type": "function_call",
+ "name": tool_call_chunk.get("name"),
+ "arguments": tool_call_chunk.get("args"),
+ "call_id": tool_call_chunk.get("id"),
+ }
+ if function_call_ids is not None and (
+ id_ := function_call_ids.get(tool_call_chunk.get("id"))
+ ):
+ function_call["id"] = id_
+ buckets["function_call"].append(function_call)
+ else:
+ for tool_call in message.tool_calls:
+ function_call = {
+ "type": "function_call",
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ "call_id": tool_call["id"],
+ }
+ if function_call_ids is not None and (
+ id_ := function_call_ids.get(tool_call["id"])
+ ):
+ function_call["id"] = id_
+ buckets["function_call"].append(function_call)
+
+ # Tool outputs
+ tool_outputs = message.additional_kwargs.get("tool_outputs", [])
+ for block in tool_outputs:
+ if isinstance(block, dict) and (key := block.get("type")) and key in buckets:
+ buckets[key].append(block)
+ else:
+ unknown_blocks.append(block)
+
+ # Re-assemble the content list in the canonical order
+ new_content = []
+ for key in content_order:
+ new_content.extend(buckets[key])
+ new_content.extend(unknown_blocks)
+
+ new_additional_kwargs = dict(message.additional_kwargs)
+ new_additional_kwargs.pop("reasoning", None)
+ new_additional_kwargs.pop("refusal", None)
+ new_additional_kwargs.pop("tool_outputs", None)
+
+ if "id" in message.response_metadata:
+ new_id = message.response_metadata["id"]
+ else:
+ new_id = message.id
+
+ return message.model_copy(
+ update={
+ "content": new_content,
+ "additional_kwargs": new_additional_kwargs,
+ "id": new_id,
+ },
+ deep=False,
+ )
+
+
+def _convert_openai_format_to_data_block(
+ block: dict,
+) -> types.ContentBlock | dict[Any, Any]:
+ """Convert OpenAI image/audio/file content block to respective v1 multimodal block.
+
+ We expect that the incoming block is verified to be in OpenAI Chat Completions
+ format.
+
+ If parsing fails, passes block through unchanged.
+
+ Mappings (Chat Completions to LangChain v1):
+ - Image -> `ImageContentBlock`
+ - Audio -> `AudioContentBlock`
+ - File -> `FileContentBlock`
+
+ """
+
+ # Extract extra keys to put them in `extras`
+ def _extract_extras(block_dict: dict, known_keys: set[str]) -> dict[str, Any]:
+ """Extract unknown keys from block to preserve as extras."""
+ return {k: v for k, v in block_dict.items() if k not in known_keys}
+
+ # base64-style image block
+ if (block["type"] == "image_url") and (
+ parsed := _parse_data_uri(block["image_url"]["url"])
+ ):
+ known_keys = {"type", "image_url"}
+ extras = _extract_extras(block, known_keys)
+
+ # Also extract extras from nested image_url dict
+ image_url_known_keys = {"url"}
+ image_url_extras = _extract_extras(block["image_url"], image_url_known_keys)
+
+ # Merge extras
+ all_extras = {**extras}
+ for key, value in image_url_extras.items():
+ if key == "detail": # Don't rename
+ all_extras["detail"] = value
+ else:
+ all_extras[f"image_url_{key}"] = value
+
+ return types.create_image_block(
+ # Even though this is labeled as `url`, it can be base64-encoded
+ base64=parsed["data"],
+ mime_type=parsed["mime_type"],
+ **all_extras,
+ )
+
+ # url-style image block
+ if (block["type"] == "image_url") and isinstance(
+ block["image_url"].get("url"), str
+ ):
+ known_keys = {"type", "image_url"}
+ extras = _extract_extras(block, known_keys)
+
+ image_url_known_keys = {"url"}
+ image_url_extras = _extract_extras(block["image_url"], image_url_known_keys)
+
+ all_extras = {**extras}
+ for key, value in image_url_extras.items():
+ if key == "detail": # Don't rename
+ all_extras["detail"] = value
+ else:
+ all_extras[f"image_url_{key}"] = value
+
+ return types.create_image_block(
+ url=block["image_url"]["url"],
+ **all_extras,
+ )
+
+ # base64-style audio block
+ # audio is only represented via raw data, no url or ID option
+ if block["type"] == "input_audio":
+ known_keys = {"type", "input_audio"}
+ extras = _extract_extras(block, known_keys)
+
+ # Also extract extras from nested audio dict
+ audio_known_keys = {"data", "format"}
+ audio_extras = _extract_extras(block["input_audio"], audio_known_keys)
+
+ all_extras = {**extras}
+ for key, value in audio_extras.items():
+ all_extras[f"audio_{key}"] = value
+
+ return types.create_audio_block(
+ base64=block["input_audio"]["data"],
+ mime_type=f"audio/{block['input_audio']['format']}",
+ **all_extras,
+ )
+
+ # id-style file block
+ if block.get("type") == "file" and "file_id" in block.get("file", {}):
+ known_keys = {"type", "file"}
+ extras = _extract_extras(block, known_keys)
+
+ file_known_keys = {"file_id"}
+ file_extras = _extract_extras(block["file"], file_known_keys)
+
+ all_extras = {**extras}
+ for key, value in file_extras.items():
+ all_extras[f"file_{key}"] = value
+
+ return types.create_file_block(
+ file_id=block["file"]["file_id"],
+ **all_extras,
+ )
+
+ # base64-style file block
+ if (block["type"] == "file") and (
+ parsed := _parse_data_uri(block["file"]["file_data"])
+ ):
+ known_keys = {"type", "file"}
+ extras = _extract_extras(block, known_keys)
+
+ file_known_keys = {"file_data", "filename"}
+ file_extras = _extract_extras(block["file"], file_known_keys)
+
+ all_extras = {**extras}
+ for key, value in file_extras.items():
+ all_extras[f"file_{key}"] = value
+
+ filename = block["file"].get("filename")
+ return types.create_file_block(
+ base64=parsed["data"],
+ mime_type="application/pdf",
+ filename=filename,
+ **all_extras,
+ )
+
+ # Escape hatch
+ return block
+
+
+# v1 / Responses
+def _convert_annotation_to_v1(annotation: dict[str, Any]) -> types.Annotation:
+ annotation_type = annotation.get("type")
+
+ if annotation_type == "url_citation":
+ known_fields = {
+ "type",
+ "url",
+ "title",
+ "cited_text",
+ "start_index",
+ "end_index",
+ }
+ url_citation = cast("types.Citation", {})
+ for field in ("end_index", "start_index", "title"):
+ if field in annotation:
+ url_citation[field] = annotation[field]
+ url_citation["type"] = "citation"
+ url_citation["url"] = annotation["url"]
+ for field, value in annotation.items():
+ if field not in known_fields:
+ if "extras" not in url_citation:
+ url_citation["extras"] = {}
+ url_citation["extras"][field] = value
+ return url_citation
+
+ if annotation_type == "file_citation":
+ known_fields = {
+ "type",
+ "title",
+ "cited_text",
+ "start_index",
+ "end_index",
+ "filename",
+ }
+ document_citation: types.Citation = {"type": "citation"}
+ if "filename" in annotation:
+ document_citation["title"] = annotation["filename"]
+ for field, value in annotation.items():
+ if field not in known_fields:
+ if "extras" not in document_citation:
+ document_citation["extras"] = {}
+ document_citation["extras"][field] = value
+
+ return document_citation
+
+ # TODO: standardise container_file_citation?
+ non_standard_annotation: types.NonStandardAnnotation = {
+ "type": "non_standard_annotation",
+ "value": annotation,
+ }
+ return non_standard_annotation
+
+
+def _explode_reasoning(block: dict[str, Any]) -> Iterator[types.ReasoningContentBlock]:
+ if "summary" not in block:
+ yield cast("types.ReasoningContentBlock", block)
+ return
+
+ known_fields = {"type", "reasoning", "id", "index"}
+ unknown_fields = [
+ field for field in block if field != "summary" and field not in known_fields
+ ]
+ if unknown_fields:
+ block["extras"] = {}
+ for field in unknown_fields:
+ block["extras"][field] = block.pop(field)
+
+ if not block["summary"]:
+ # [{'id': 'rs_...', 'summary': [], 'type': 'reasoning', 'index': 0}]
+ block = {k: v for k, v in block.items() if k != "summary"}
+ if "index" in block:
+ meaningful_idx = f"{block['index']}_0"
+ block["index"] = f"lc_rs_{meaningful_idx.encode().hex()}"
+ yield cast("types.ReasoningContentBlock", block)
+ return
+
+ # Common part for every exploded line, except 'summary'
+ common = {k: v for k, v in block.items() if k in known_fields}
+
+ # Optional keys that must appear only in the first exploded item
+ first_only = block.pop("extras", None)
+
+ for idx, part in enumerate(block["summary"]):
+ new_block = dict(common)
+ new_block["reasoning"] = part.get("text", "")
+ if idx == 0 and first_only:
+ new_block.update(first_only)
+ if "index" in new_block:
+ summary_index = part.get("index", 0)
+ meaningful_idx = f"{new_block['index']}_{summary_index}"
+ new_block["index"] = f"lc_rs_{meaningful_idx.encode().hex()}"
+
+ yield cast("types.ReasoningContentBlock", new_block)
+
+
+def _convert_to_v1_from_responses(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert a Responses message to v1 format."""
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for raw_block in message.content:
+ if not isinstance(raw_block, dict):
+ continue
+ block = raw_block.copy()
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if "text" not in block:
+ block["text"] = ""
+ if "annotations" in block:
+ block["annotations"] = [
+ _convert_annotation_to_v1(a) for a in block["annotations"]
+ ]
+ if "index" in block:
+ block["index"] = f"lc_txt_{block['index']}"
+ yield cast("types.TextContentBlock", block)
+
+ elif block_type == "reasoning":
+ yield from _explode_reasoning(block)
+
+ elif block_type == "image_generation_call" and (
+ result := block.get("result")
+ ):
+ new_block = {"type": "image", "base64": result}
+ if output_format := block.get("output_format"):
+ new_block["mime_type"] = f"image/{output_format}"
+ if "id" in block:
+ new_block["id"] = block["id"]
+ if "index" in block:
+ new_block["index"] = f"lc_img_{block['index']}"
+ for extra_key in (
+ "status",
+ "background",
+ "output_format",
+ "quality",
+ "revised_prompt",
+ "size",
+ ):
+ if extra_key in block:
+ if "extras" not in new_block:
+ new_block["extras"] = {}
+ new_block["extras"][extra_key] = block[extra_key]
+ yield cast("types.ImageContentBlock", new_block)
+
+ elif block_type == "function_call":
+ tool_call_block: (
+ types.ToolCall | types.InvalidToolCall | types.ToolCallChunk | None
+ ) = None
+ call_id = block.get("call_id", "")
+
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ tool_call_block = message.tool_call_chunks[0].copy() # type: ignore[assignment]
+ elif call_id:
+ for tool_call in message.tool_calls or []:
+ if tool_call.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ break
+ else:
+ for invalid_tool_call in message.invalid_tool_calls or []:
+ if invalid_tool_call.get("id") == call_id:
+ tool_call_block = invalid_tool_call.copy()
+ break
+ if tool_call_block:
+ if "id" in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"]["item_id"] = block["id"]
+ if "index" in block:
+ tool_call_block["index"] = f"lc_tc_{block['index']}"
+ for extra_key in ("status", "namespace"):
+ if extra_key in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"][extra_key] = block[extra_key]
+ yield tool_call_block
+
+ elif block_type == "web_search_call":
+ web_search_call = {
+ "type": "server_tool_call",
+ "name": "web_search",
+ "args": {},
+ "id": block["id"],
+ }
+ if "index" in block:
+ web_search_call["index"] = f"lc_wsc_{block['index']}"
+
+ sources: dict[str, Any] | None = None
+ if "action" in block and isinstance(block["action"], dict):
+ if "sources" in block["action"]:
+ sources = block["action"]["sources"]
+ web_search_call["args"] = {
+ k: v for k, v in block["action"].items() if k != "sources"
+ }
+ for key in block:
+ if key not in {"type", "id", "action", "status", "index"}:
+ web_search_call[key] = block[key]
+
+ yield cast("types.ServerToolCall", web_search_call)
+
+ # If .content already has web_search_result, don't add
+ if not any(
+ isinstance(other_block, dict)
+ and other_block.get("type") == "web_search_result"
+ and other_block.get("id") == block["id"]
+ for other_block in message.content
+ ):
+ web_search_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if sources:
+ web_search_result["output"] = {"sources": sources}
+
+ status = block.get("status")
+ if status == "failed":
+ web_search_result["status"] = "error"
+ elif status == "completed":
+ web_search_result["status"] = "success"
+ elif status:
+ web_search_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ web_search_result["index"] = f"lc_wsr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", web_search_result)
+
+ elif block_type == "file_search_call":
+ file_search_call = {
+ "type": "server_tool_call",
+ "name": "file_search",
+ "id": block["id"],
+ "args": {"queries": block.get("queries", [])},
+ }
+ if "index" in block:
+ file_search_call["index"] = f"lc_fsc_{block['index']}"
+
+ for key in block:
+ if key not in {
+ "type",
+ "id",
+ "queries",
+ "results",
+ "status",
+ "index",
+ }:
+ file_search_call[key] = block[key]
+
+ yield cast("types.ServerToolCall", file_search_call)
+
+ file_search_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if file_search_output := block.get("results"):
+ file_search_result["output"] = file_search_output
+
+ status = block.get("status")
+ if status == "failed":
+ file_search_result["status"] = "error"
+ elif status == "completed":
+ file_search_result["status"] = "success"
+ elif status:
+ file_search_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ file_search_result["index"] = f"lc_fsr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", file_search_result)
+
+ elif block_type == "code_interpreter_call":
+ code_interpreter_call = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "id": block["id"],
+ }
+ if "code" in block:
+ code_interpreter_call["args"] = {"code": block["code"]}
+ if "index" in block:
+ code_interpreter_call["index"] = f"lc_cic_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "outputs",
+ "status",
+ "code",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in code_interpreter_call:
+ code_interpreter_call["extras"] = {}
+ code_interpreter_call["extras"][key] = block[key]
+
+ code_interpreter_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if "outputs" in block:
+ code_interpreter_result["output"] = block["outputs"]
+
+ status = block.get("status")
+ if status == "failed":
+ code_interpreter_result["status"] = "error"
+ elif status == "completed":
+ code_interpreter_result["status"] = "success"
+ elif status:
+ code_interpreter_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ code_interpreter_result["index"] = f"lc_cir_{block['index'] + 1}"
+
+ yield cast("types.ServerToolCall", code_interpreter_call)
+ yield cast("types.ServerToolResult", code_interpreter_result)
+
+ elif block_type == "mcp_call":
+ mcp_call = {
+ "type": "server_tool_call",
+ "name": "remote_mcp",
+ "id": block["id"],
+ }
+ if (arguments := block.get("arguments")) and isinstance(arguments, str):
+ try:
+ mcp_call["args"] = json.loads(block["arguments"])
+ except json.JSONDecodeError:
+ mcp_call["extras"] = {"arguments": arguments}
+ if "name" in block:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"]["tool_name"] = block["name"]
+ if "server_label" in block:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"]["server_label"] = block["server_label"]
+ if "index" in block:
+ mcp_call["index"] = f"lc_mcp_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "arguments",
+ "name",
+ "server_label",
+ "output",
+ "error",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"][key] = block[key]
+
+ yield cast("types.ServerToolCall", mcp_call)
+
+ mcp_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if mcp_output := block.get("output"):
+ mcp_result["output"] = mcp_output
+
+ error = block.get("error")
+ if error:
+ if "extras" not in mcp_result:
+ mcp_result["extras"] = {}
+ mcp_result["extras"]["error"] = error
+ mcp_result["status"] = "error"
+ else:
+ mcp_result["status"] = "success"
+
+ if "index" in block and isinstance(block["index"], int):
+ mcp_result["index"] = f"lc_mcpr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", mcp_result)
+
+ elif block_type == "mcp_list_tools":
+ mcp_list_tools_call = {
+ "type": "server_tool_call",
+ "name": "mcp_list_tools",
+ "args": {},
+ "id": block["id"],
+ }
+ if "server_label" in block:
+ mcp_list_tools_call["extras"] = {}
+ mcp_list_tools_call["extras"]["server_label"] = block[
+ "server_label"
+ ]
+ if "index" in block:
+ mcp_list_tools_call["index"] = f"lc_mlt_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "name",
+ "server_label",
+ "tools",
+ "error",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in mcp_list_tools_call:
+ mcp_list_tools_call["extras"] = {}
+ mcp_list_tools_call["extras"][key] = block[key]
+
+ yield cast("types.ServerToolCall", mcp_list_tools_call)
+
+ mcp_list_tools_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if mcp_output := block.get("tools"):
+ mcp_list_tools_result["output"] = mcp_output
+
+ error = block.get("error")
+ if error:
+ if "extras" not in mcp_list_tools_result:
+ mcp_list_tools_result["extras"] = {}
+ mcp_list_tools_result["extras"]["error"] = error
+ mcp_list_tools_result["status"] = "error"
+ else:
+ mcp_list_tools_result["status"] = "success"
+
+ if "index" in block and isinstance(block["index"], int):
+ mcp_list_tools_result["index"] = f"lc_mltr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", mcp_list_tools_result)
+
+ elif (
+ block_type == "tool_search_call" and block.get("execution") == "server"
+ ):
+ tool_search_call: dict[str, Any] = {
+ "type": "server_tool_call",
+ "name": "tool_search",
+ "id": block["id"],
+ "args": block.get("arguments", {}),
+ }
+ if "index" in block:
+ tool_search_call["index"] = f"lc_tsc_{block['index']}"
+ extras: dict[str, Any] = {}
+ known = {"type", "id", "arguments", "index"}
+ for key in block:
+ if key not in known:
+ extras[key] = block[key]
+ if extras:
+ tool_search_call["extras"] = extras
+ yield cast("types.ServerToolCall", tool_search_call)
+
+ elif (
+ block_type == "tool_search_output"
+ and block.get("execution") == "server"
+ ):
+ tool_search_output: dict[str, Any] = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ "output": {"tools": block.get("tools", [])},
+ }
+ status = block.get("status")
+ if status == "failed":
+ tool_search_output["status"] = "error"
+ elif status == "completed":
+ tool_search_output["status"] = "success"
+ if "index" in block and isinstance(block["index"], int):
+ tool_search_output["index"] = f"lc_tso_{block['index']}"
+ extras_out: dict[str, Any] = {"name": "tool_search"}
+ known_out = {"type", "id", "status", "tools", "index"}
+ for key in block:
+ if key not in known_out:
+ extras_out[key] = block[key]
+ if extras_out:
+ tool_search_output["extras"] = extras_out
+ yield cast("types.ServerToolResult", tool_search_output)
+
+ elif block_type in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+ else:
+ new_block = {"type": "non_standard", "value": block}
+ if "index" in new_block["value"]:
+ new_block["index"] = f"lc_ns_{new_block['value'].pop('index')}"
+ yield cast("types.NonStandardContentBlock", new_block)
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with OpenAI content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if isinstance(message.content, str):
+ return _convert_to_v1_from_chat_completions(message)
+ message = _convert_from_v03_ai_message(message)
+ return _convert_to_v1_from_responses(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with OpenAI content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if isinstance(message.content, str):
+ return _convert_to_v1_from_chat_completions_chunk(message)
+ message = _convert_from_v03_ai_message(message) # type: ignore[assignment]
+ return _convert_to_v1_from_responses(message)
+
+
+def _register_openai_translator() -> None:
+ """Register the OpenAI translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("openai", translate_content, translate_content_chunk)
+
+
+_register_openai_translator()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/chat.py b/python/user_packages/Python313/site-packages/langchain_core/messages/chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..6786efcacf4f349225cd98766366361565e255d8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/chat.py
@@ -0,0 +1,64 @@
+"""Chat Message."""
+
+from typing import Any, Literal
+
+from typing_extensions import override
+
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+)
+from langchain_core.utils._merge import merge_dicts
+
+
+class ChatMessage(BaseMessage):
+ """Message that can be assigned an arbitrary speaker (i.e. role)."""
+
+ role: str
+ """The speaker / role of the Message."""
+
+ type: Literal["chat"] = "chat"
+ """The type of the message (used during serialization)."""
+
+
+class ChatMessageChunk(ChatMessage, BaseMessageChunk):
+ """Chat Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["ChatMessageChunk"] = "ChatMessageChunk" # type: ignore[assignment]
+ """The type of the message (used during serialization)."""
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, ChatMessageChunk):
+ if self.role != other.role:
+ msg = "Cannot concatenate ChatMessageChunks with different roles."
+ raise ValueError(msg)
+
+ return self.__class__(
+ role=self.role,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+ if isinstance(other, BaseMessageChunk):
+ return self.__class__(
+ role=self.role,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+ return super().__add__(other)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/content.py b/python/user_packages/Python313/site-packages/langchain_core/messages/content.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a02139d5bbae2056051a5ab1796187bd50d7136
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/content.py
@@ -0,0 +1,1488 @@
+"""Standard, multimodal content blocks for Large Language Model I/O.
+
+This module provides standardized data structures for representing inputs to and outputs
+from LLMs. The core abstraction is the **Content Block**, a `TypedDict`.
+
+**Rationale**
+
+Different LLM providers use distinct and incompatible API schemas. This module provides
+a unified, provider-agnostic format to facilitate these interactions. A message to or
+from a model is simply a list of content blocks, allowing for the natural interleaving
+of text, images, and other content in a single ordered sequence.
+
+An adapter for a specific provider is responsible for translating this standard list of
+blocks into the format required by its API.
+
+**Extensibility**
+
+Data **not yet mapped** to a standard block may be represented using the
+`NonStandardContentBlock`, which allows for provider-specific data to be included
+without losing the benefits of type checking and validation.
+
+Furthermore, provider-specific fields **within** a standard block are fully supported
+by default in the `extras` field of each block. This allows for additional metadata
+to be included without breaking the standard structure. For example, Google's thought
+signature:
+
+```python
+AIMessage(
+ content=[
+ {
+ "type": "text",
+ "text": "J'adore la programmation.",
+ "extras": {"signature": "EpoWCpc..."}, # Thought signature
+ }
+ ], ...
+)
+```
+
+
+!!! note
+
+ Following widespread adoption of [PEP 728](https://peps.python.org/pep-0728/), we
+ intend to add `extra_items=Any` as a param to Content Blocks. This will signify to
+ type checkers that additional provider-specific fields are allowed outside of the
+ `extras` field, and that will become the new standard approach to adding
+ provider-specific metadata.
+
+ ??? note
+
+ **Example with PEP 728 provider-specific fields:**
+
+ ```python
+ # Content block definition
+ # NOTE: `extra_items=Any`
+ class TextContentBlock(TypedDict, extra_items=Any):
+ type: Literal["text"]
+ id: NotRequired[str]
+ text: str
+ annotations: NotRequired[list[Annotation]]
+ index: NotRequired[int]
+ ```
+
+ ```python
+ from langchain_core.messages.content import TextContentBlock
+
+ # Create a text content block with provider-specific fields
+ my_block: TextContentBlock = {
+ # Add required fields
+ "type": "text",
+ "text": "Hello, world!",
+ # Additional fields not specified in the TypedDict
+ # These are valid with PEP 728 and are typed as Any
+ "openai_metadata": {"model": "gpt-4", "temperature": 0.7},
+ "anthropic_usage": {"input_tokens": 10, "output_tokens": 20},
+ "custom_field": "any value",
+ }
+
+ # Mutating an existing block to add provider-specific fields
+ openai_data = my_block["openai_metadata"] # Type: Any
+ ```
+
+**Example Usage**
+
+```python
+# Direct construction
+from langchain_core.messages.content import TextContentBlock, ImageContentBlock
+
+multimodal_message: AIMessage(
+ content_blocks=[
+ TextContentBlock(type="text", text="What is shown in this image?"),
+ ImageContentBlock(
+ type="image",
+ url="https://www.langchain.com/images/brand/langchain_logo_text_w_white.png",
+ mime_type="image/png",
+ ),
+ ]
+)
+
+# Using factories
+from langchain_core.messages.content import create_text_block, create_image_block
+
+multimodal_message: AIMessage(
+ content=[
+ create_text_block("What is shown in this image?"),
+ create_image_block(
+ url="https://www.langchain.com/images/brand/langchain_logo_text_w_white.png",
+ mime_type="image/png",
+ ),
+ ]
+)
+```
+
+Factory functions offer benefits such as:
+
+- Automatic ID generation (when not provided)
+- No need to manually specify the `type` field
+"""
+
+from typing import Any, Literal, get_args, get_type_hints
+
+from typing_extensions import NotRequired, TypedDict
+
+from langchain_core.utils.utils import ensure_id
+
+
+class Citation(TypedDict):
+ """Annotation for citing data from a document.
+
+ !!! note
+
+ `start`/`end` indices refer to the **response text**,
+ not the source text. This means that the indices are relative to the model's
+ response, not the original document (as specified in the `url`).
+
+ !!! note "Factory function"
+
+ `create_citation` may also be used as a factory to create a `Citation`.
+ Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["citation"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ url: NotRequired[str]
+ """URL of the document source."""
+
+ title: NotRequired[str]
+ """Source document title.
+
+ For example, the page title for a web page or the title of a paper.
+ """
+
+ start_index: NotRequired[int]
+ """Start index of the **response text** (`TextContentBlock.text`)."""
+
+ end_index: NotRequired[int]
+ """End index of the **response text** (`TextContentBlock.text`)"""
+
+ cited_text: NotRequired[str]
+ """Excerpt of source text being cited."""
+
+ # NOTE: not including spans for the raw document text (such as `text_start_index`
+ # and `text_end_index`) as this is not currently supported by any provider. The
+ # thinking is that the `cited_text` should be sufficient for most use cases, and it
+ # is difficult to reliably extract spans from the raw document text across file
+ # formats or encoding schemes.
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class NonStandardAnnotation(TypedDict):
+ """Provider-specific annotation format."""
+
+ type: Literal["non_standard_annotation"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ value: dict[str, Any]
+ """Provider-specific annotation data."""
+
+
+Annotation = Citation | NonStandardAnnotation
+"""A union of all defined `Annotation` types."""
+
+
+class TextContentBlock(TypedDict):
+ """Text output from a LLM.
+
+ This typically represents the main text content of a message, such as the response
+ from a language model or the text of a user message.
+
+ !!! note "Factory function"
+
+ `create_text_block` may also be used as a factory to create a
+ `TextContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["text"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ text: str
+ """Block text."""
+
+ annotations: NotRequired[list[Annotation]]
+ """`Citation`s and other annotations."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ToolCall(TypedDict):
+ """Represents an AI's request to call a tool.
+
+ Example:
+ ```python
+ {"name": "foo", "args": {"a": 1}, "id": "123"}
+ ```
+
+ This represents a request to call the tool named "foo" with arguments {"a": 1}
+ and an identifier of "123".
+
+ !!! note "Factory function"
+
+ `create_tool_call` may also be used as a factory to create a
+ `ToolCall`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["tool_call"]
+ """Used for discrimination."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ToolCallChunk(TypedDict):
+ """A chunk of a tool call (yielded when streaming).
+
+ When merging `ToolCallChunks` (e.g., via `AIMessageChunk.__add__`),
+ all string attributes are concatenated. Chunks are only merged if their
+ values of `index` are equal and not `None`.
+
+ Example:
+ ```python
+ left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
+ right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
+
+ (
+ AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ + AIMessageChunk(content="", tool_call_chunks=right_chunks)
+ ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
+ ```
+ """
+
+ # TODO: Consider making fields NotRequired[str] in the future.
+
+ type: Literal["tool_call_chunk"]
+ """Used for serialization."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """The index of the tool call in a sequence."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class InvalidToolCall(TypedDict):
+ """Allowance for errors made by LLM.
+
+ Here we add an `error` key to surface errors made during generation
+ (e.g., invalid JSON arguments.)
+ """
+
+ # TODO: Consider making fields NotRequired[str] in the future.
+
+ type: Literal["invalid_tool_call"]
+ """Used for discrimination."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call."""
+
+ error: str | None
+ """An error message associated with the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolCall(TypedDict):
+ """Tool call that is executed server-side.
+
+ For example: code execution, web search, etc.
+ """
+
+ type: Literal["server_tool_call"]
+ """Used for discrimination."""
+
+ id: str
+ """An identifier associated with the tool call."""
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolCallChunk(TypedDict):
+ """A chunk of a server-side tool call (yielded when streaming)."""
+
+ type: Literal["server_tool_call_chunk"]
+ """Used for discrimination."""
+
+ name: NotRequired[str]
+ """The name of the tool to be called."""
+
+ args: NotRequired[str]
+ """JSON substring of the arguments to the tool call."""
+
+ id: NotRequired[str]
+ """Unique identifier for this server tool call chunk.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolResult(TypedDict):
+ """Result of a server-side tool call."""
+
+ type: Literal["server_tool_result"]
+ """Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this server tool result.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ tool_call_id: str
+ """ID of the corresponding server tool call."""
+
+ status: Literal["success", "error"]
+ """Execution status of the server-side tool."""
+
+ output: NotRequired[Any]
+ """Output of the executed tool."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ReasoningContentBlock(TypedDict):
+ """Reasoning output from a LLM.
+
+ !!! note "Factory function"
+
+ `create_reasoning_block` may also be used as a factory to create a
+ `ReasoningContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["reasoning"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ reasoning: NotRequired[str]
+ """Reasoning text.
+
+ Either the thought summary or the raw reasoning text itself.
+
+ Often parsed from `` tags in the model's response.
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+# Note: `title` and `context` are fields that could be used to provide additional
+# information about the file, such as a description or summary of its content.
+# E.g. with Claude, you can provide a context for a file which is passed to the model.
+class ImageContentBlock(TypedDict):
+ """Image data.
+
+ !!! note "Factory function"
+
+ `create_image_block` may also be used as a factory to create an
+ `ImageContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["image"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the image in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the image.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#image)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the image."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the image data itself."""
+
+
+class VideoContentBlock(TypedDict):
+ """Video data.
+
+ !!! note "Factory function"
+
+ `create_video_block` may also be used as a factory to create a
+ `VideoContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["video"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the video in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the video.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#video)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the video."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the video data itself."""
+
+
+class AudioContentBlock(TypedDict):
+ """Audio data.
+
+ !!! note "Factory function"
+
+ `create_audio_block` may also be used as a factory to create an
+ `AudioContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["audio"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the audio file in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the audio.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#audio)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the audio."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the audio data itself."""
+
+
+class PlainTextContentBlock(TypedDict):
+ """Plaintext data (e.g., from a `.txt` or `.md` document).
+
+ !!! note
+
+ A `PlainTextContentBlock` existed in `langchain-core<1.0.0`. Although the
+ name has carried over, the structure has changed significantly. The only shared
+ keys between the old and new versions are `type` and `text`, though the
+ `type` value has changed from `'text'` to `'text-plain'`.
+
+ !!! note
+
+ Title and context are optional fields that may be passed to the model. See
+ Anthropic [example](https://platform.claude.com/docs/en/build-with-claude/citations#citable-vs-non-citable-content).
+
+ !!! note "Factory function"
+
+ `create_plaintext_block` may also be used as a factory to create a
+ `PlainTextContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["text-plain"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the plaintext file in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: Literal["text/plain"]
+ """MIME type of the file.
+
+ Required for base64 data.
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the plaintext."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ text: NotRequired[str]
+ """Plaintext content. This is optional if the data is provided as base64."""
+
+ title: NotRequired[str]
+ """Title of the text data, e.g., the title of a document."""
+
+ context: NotRequired[str]
+ """Context for the text, e.g., a description or summary of the text's content."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the data itself."""
+
+
+class FileContentBlock(TypedDict):
+ """File data that doesn't fit into other multimodal block types.
+
+ This block is intended for files that are not images, audio, or plaintext. For
+ example, it can be used for PDFs, Word documents, etc.
+
+ If the file is an image, audio, or plaintext, you should use the corresponding
+ content block type (e.g., `ImageContentBlock`, `AudioContentBlock`,
+ `PlainTextContentBlock`).
+
+ !!! note "Factory function"
+
+ `create_file_block` may also be used as a factory to create a
+ `FileContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["file"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Used for tracking and referencing specific blocks (e.g., during streaming).
+
+ Not to be confused with `file_id`, which references an external file in a
+ storage system.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the file in an external file storage system.
+
+ For example, a file ID from OpenAI's Files API or another cloud storage provider.
+ This is distinct from `id`, which identifies the content block itself.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the file.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the file."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the file data itself."""
+
+
+# Future modalities to consider:
+# - 3D models
+# - Tabular data
+
+
+class NonStandardContentBlock(TypedDict):
+ """Provider-specific content data.
+
+ This block contains data for which there is not yet a standard type.
+
+ The purpose of this block should be to simply hold a provider-specific payload.
+ If a provider's non-standard output includes reasoning and tool calls, it should be
+ the adapter's job to parse that payload and emit the corresponding standard
+ `ReasoningContentBlock` and `ToolCalls`.
+
+ Has no `extras` field, as provider-specific data should be included in the
+ `value` field.
+
+ !!! note "Factory function"
+
+ `create_non_standard_block` may also be used as a factory to create a
+ `NonStandardContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["non_standard"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ value: dict[str, Any]
+ """Provider-specific content data."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+
+# --- Aliases ---
+DataContentBlock = (
+ ImageContentBlock
+ | VideoContentBlock
+ | AudioContentBlock
+ | PlainTextContentBlock
+ | FileContentBlock
+)
+"""A union of all defined multimodal data `ContentBlock` types."""
+
+ToolContentBlock = (
+ ToolCall | ToolCallChunk | ServerToolCall | ServerToolCallChunk | ServerToolResult
+)
+
+ContentBlock = (
+ TextContentBlock
+ | InvalidToolCall
+ | ReasoningContentBlock
+ | NonStandardContentBlock
+ | DataContentBlock
+ | ToolContentBlock
+)
+"""A union of all defined `ContentBlock` types and aliases."""
+
+
+KNOWN_BLOCK_TYPES = {
+ # Text output
+ "text",
+ "reasoning",
+ # Tools
+ "tool_call",
+ "invalid_tool_call",
+ "tool_call_chunk",
+ # Multimodal data
+ "image",
+ "audio",
+ "file",
+ "text-plain",
+ "video",
+ # Server-side tool calls
+ "server_tool_call",
+ "server_tool_call_chunk",
+ "server_tool_result",
+ # Catch-all
+ "non_standard",
+ # citation and non_standard_annotation intentionally omitted
+}
+"""These are block types known to `langchain-core >= 1.0.0`.
+
+If a block has a type not in this set, it is considered to be provider-specific.
+"""
+
+
+def _get_data_content_block_types() -> tuple[str, ...]:
+ """Get type literals from DataContentBlock union members dynamically.
+
+ Example: ("image", "video", "audio", "text-plain", "file")
+
+ Note that old style multimodal blocks type literals with new style blocks.
+ Specifically, "image", "audio", and "file".
+
+ See the docstring of `_normalize_messages` in `language_models._utils` for details.
+ """
+ data_block_types = []
+
+ for block_type in get_args(DataContentBlock):
+ hints = get_type_hints(block_type)
+ if "type" in hints:
+ type_annotation = hints["type"]
+ if hasattr(type_annotation, "__args__"):
+ # This is a Literal type, get the literal value
+ literal_value = type_annotation.__args__[0]
+ data_block_types.append(literal_value)
+
+ return tuple(data_block_types)
+
+
+def is_data_content_block(block: dict) -> bool:
+ """Check if the provided content block is a data content block.
+
+ Returns True for both v0 (old-style) and v1 (new-style) multimodal data blocks.
+
+ Args:
+ block: The content block to check.
+
+ Returns:
+ `True` if the content block is a data content block, `False` otherwise.
+ """
+ if block.get("type") not in _get_data_content_block_types():
+ return False
+
+ if any(key in block for key in ("url", "base64", "file_id", "text")):
+ # Type is valid and at least one data field is present
+ # (Accepts old-style image and audio URLContentBlock)
+
+ # 'text' is checked to support v0 PlainTextContentBlock types
+ # We must guard against new style TextContentBlock which also has 'text' `type`
+ # by ensuring the presence of `source_type`
+ if block["type"] == "text" and "source_type" not in block: # noqa: SIM103 # This is more readable
+ return False
+
+ return True
+
+ if "source_type" in block:
+ # Old-style content blocks had possible types of 'image', 'audio', and 'file'
+ # which is not captured in the prior check
+ source_type = block["source_type"]
+ if (source_type == "url" and "url" in block) or (
+ source_type == "base64" and "data" in block
+ ):
+ return True
+ if (source_type == "id" and "id" in block) or (
+ source_type == "text" and "url" in block
+ ):
+ return True
+
+ return False
+
+
+def create_text_block(
+ text: str,
+ *,
+ id: str | None = None,
+ annotations: list[Annotation] | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> TextContentBlock:
+ """Create a `TextContentBlock`.
+
+ Args:
+ text: The text content of the block.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ annotations: `Citation`s and other annotations for the text.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `TextContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = TextContentBlock(
+ type="text",
+ text=text,
+ id=ensure_id(id),
+ )
+ if annotations is not None:
+ block["annotations"] = annotations
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_image_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ImageContentBlock:
+ """Create an `ImageContentBlock`.
+
+ Args:
+ url: URL of the image.
+ base64: Base64-encoded image data.
+ file_id: ID of the image file from a file storage system.
+ mime_type: MIME type of the image.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ImageContentBlock`.
+
+ Raises:
+ ValueError: If no image source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ block = ImageContentBlock(type="image", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_video_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> VideoContentBlock:
+ """Create a `VideoContentBlock`.
+
+ Args:
+ url: URL of the video.
+ base64: Base64-encoded video data.
+ file_id: ID of the video file from a file storage system.
+ mime_type: MIME type of the video.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `VideoContentBlock`.
+
+ Raises:
+ ValueError: If no video source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = VideoContentBlock(type="video", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_audio_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> AudioContentBlock:
+ """Create an `AudioContentBlock`.
+
+ Args:
+ url: URL of the audio.
+ base64: Base64-encoded audio data.
+ file_id: ID of the audio file from a file storage system.
+ mime_type: MIME type of the audio.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `AudioContentBlock`.
+
+ Raises:
+ ValueError: If no audio source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = AudioContentBlock(type="audio", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_file_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> FileContentBlock:
+ """Create a `FileContentBlock`.
+
+ Args:
+ url: URL of the file.
+ base64: Base64-encoded file data.
+ file_id: ID of the file from a file storage system.
+ mime_type: MIME type of the file.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `FileContentBlock`.
+
+ Raises:
+ ValueError: If no file source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = FileContentBlock(type="file", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_plaintext_block(
+ text: str | None = None,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ title: str | None = None,
+ context: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> PlainTextContentBlock:
+ """Create a `PlainTextContentBlock`.
+
+ Args:
+ text: The plaintext content.
+ url: URL of the plaintext file.
+ base64: Base64-encoded plaintext data.
+ file_id: ID of the plaintext file from a file storage system.
+ title: Title of the text data.
+ context: Context or description of the text content.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `PlainTextContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = PlainTextContentBlock(
+ type="text-plain",
+ mime_type="text/plain",
+ id=ensure_id(id),
+ )
+
+ if text is not None:
+ block["text"] = text
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if title is not None:
+ block["title"] = title
+ if context is not None:
+ block["context"] = context
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_tool_call(
+ name: str,
+ args: dict[str, Any],
+ *,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ToolCall:
+ """Create a `ToolCall`.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call.
+ id: An identifier for the tool call.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ToolCall`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = ToolCall(
+ type="tool_call",
+ name=name,
+ args=args,
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_reasoning_block(
+ reasoning: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ReasoningContentBlock:
+ """Create a `ReasoningContentBlock`.
+
+ Args:
+ reasoning: The reasoning text or thought summary.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ReasoningContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = ReasoningContentBlock(
+ type="reasoning",
+ reasoning=reasoning or "",
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_citation(
+ *,
+ url: str | None = None,
+ title: str | None = None,
+ start_index: int | None = None,
+ end_index: int | None = None,
+ cited_text: str | None = None,
+ id: str | None = None,
+ **kwargs: Any,
+) -> Citation:
+ """Create a `Citation`.
+
+ Args:
+ url: URL of the document source.
+ title: Source document title.
+ start_index: Start index in the response text where citation applies.
+ end_index: End index in the response text where citation applies.
+ cited_text: Excerpt of source text being cited.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+
+ Returns:
+ A properly formatted `Citation`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = Citation(type="citation", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if title is not None:
+ block["title"] = title
+ if start_index is not None:
+ block["start_index"] = start_index
+ if end_index is not None:
+ block["end_index"] = end_index
+ if cited_text is not None:
+ block["cited_text"] = cited_text
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_non_standard_block(
+ value: dict[str, Any],
+ *,
+ id: str | None = None,
+ index: int | str | None = None,
+) -> NonStandardContentBlock:
+ """Create a `NonStandardContentBlock`.
+
+ Args:
+ value: Provider-specific content data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `NonStandardContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = NonStandardContentBlock(
+ type="non_standard",
+ value=value,
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ return block
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/function.py b/python/user_packages/Python313/site-packages/langchain_core/messages/function.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee0dad3975fcd40d89151fc7f70d068db1cc4fe4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/function.py
@@ -0,0 +1,62 @@
+"""Function Message."""
+
+from typing import Any, Literal
+
+from typing_extensions import override
+
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+)
+from langchain_core.utils._merge import merge_dicts
+
+
+class FunctionMessage(BaseMessage):
+ """Message for passing the result of executing a tool back to a model.
+
+ `FunctionMessage` are an older version of the `ToolMessage` schema, and
+ do not contain the `tool_call_id` field.
+
+ The `tool_call_id` field is used to associate the tool call request with the
+ tool call response. Useful in situations where a chat model is able
+ to request multiple tool calls in parallel.
+
+ """
+
+ name: str
+ """The name of the function that was executed."""
+
+ type: Literal["function"] = "function"
+ """The type of the message (used for serialization)."""
+
+
+class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
+ """Function Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, FunctionMessageChunk):
+ if self.name != other.name:
+ msg = "Cannot concatenate FunctionMessageChunks with different names."
+ raise ValueError(msg)
+
+ return self.__class__(
+ name=self.name,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+
+ return super().__add__(other)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/human.py b/python/user_packages/Python313/site-packages/langchain_core/messages/human.py
new file mode 100644
index 0000000000000000000000000000000000000000..338e22137008273fc7efcf93c49d146b962de87d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/human.py
@@ -0,0 +1,70 @@
+"""Human message."""
+
+from typing import Any, Literal, cast, overload
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+
+
+class HumanMessage(BaseMessage):
+ """Message from the user.
+
+ A `HumanMessage` is a message that is passed in from a user to the model.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage, SystemMessage
+
+ messages = [
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
+ HumanMessage(content="What is your name?"),
+ ]
+
+ # Instantiate a chat model and invoke it with the messages
+ model = ...
+ print(model.invoke(messages))
+ ```
+ """
+
+ type: Literal["human"] = "human"
+ """The type of the message (used for serialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Specify `content` as positional arg or `content_blocks` for typing."""
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class HumanMessageChunk(HumanMessage, BaseMessageChunk):
+ """Human Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["HumanMessageChunk"] = "HumanMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/modifier.py b/python/user_packages/Python313/site-packages/langchain_core/messages/modifier.py
new file mode 100644
index 0000000000000000000000000000000000000000..2175be492e829ee6058c727fe2d04b4ea5fe9efe
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/modifier.py
@@ -0,0 +1,33 @@
+"""Message responsible for deleting other messages."""
+
+from typing import Any, Literal
+
+from langchain_core.messages.base import BaseMessage
+
+
+class RemoveMessage(BaseMessage):
+ """Message responsible for deleting other messages."""
+
+ type: Literal["remove"] = "remove"
+ """The type of the message (used for serialization)."""
+
+ def __init__(
+ self,
+ id: str,
+ **kwargs: Any,
+ ) -> None:
+ """Create a RemoveMessage.
+
+ Args:
+ id: The ID of the message to remove.
+ **kwargs: Additional fields to pass to the message.
+
+ Raises:
+ ValueError: If the 'content' field is passed in kwargs.
+
+ """
+ if kwargs.pop("content", None):
+ msg = "RemoveMessage does not support 'content' field."
+ raise ValueError(msg)
+
+ super().__init__("", id=id, **kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/system.py b/python/user_packages/Python313/site-packages/langchain_core/messages/system.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a60811dffcacc016f075a7c5986bc536927ee7e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/system.py
@@ -0,0 +1,70 @@
+"""System message."""
+
+from typing import Any, Literal, cast, overload
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+
+
+class SystemMessage(BaseMessage):
+ """Message for priming AI behavior.
+
+ The system message is usually passed in as the first of a sequence
+ of input messages.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage, SystemMessage
+
+ messages = [
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
+ HumanMessage(content="What is your name?"),
+ ]
+
+ # Define a chat model and invoke it with the messages
+ print(model.invoke(messages))
+ ```
+ """
+
+ type: Literal["system"] = "system"
+ """The type of the message (used for serialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Specify `content` as positional arg or `content_blocks` for typing."""
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class SystemMessageChunk(SystemMessage, BaseMessageChunk):
+ """System Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/tool.py b/python/user_packages/Python313/site-packages/langchain_core/messages/tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..a83d4e6eb9e5868e128c88d78c101dc75c45a242
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/tool.py
@@ -0,0 +1,416 @@
+"""Messages for tools."""
+
+import json
+from typing import Any, Literal, cast, overload
+from uuid import UUID
+
+from pydantic import Field, model_validator
+from typing_extensions import NotRequired, TypedDict, override
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk, merge_content
+from langchain_core.messages.content import InvalidToolCall
+from langchain_core.utils._merge import merge_dicts, merge_obj
+
+
+class ToolOutputMixin:
+ """Mixin for objects that tools can return directly.
+
+ If a custom BaseTool is invoked with a `ToolCall` and the output of custom code is
+ not an instance of `ToolOutputMixin`, the output will automatically be coerced to
+ a string and wrapped in a `ToolMessage`.
+
+ """
+
+
+class ToolMessage(BaseMessage, ToolOutputMixin):
+ """Message for passing the result of executing a tool back to a model.
+
+ `ToolMessage` objects contain the result of a tool invocation. Typically, the result
+ is encoded inside the `content` field.
+
+ `tool_call_id` is used to associate the tool call request with the tool call
+ response. Useful in situations where a chat model is able to request multiple tool
+ calls in parallel.
+
+ Example:
+ A `ToolMessage` representing a result of `42` from a tool call with id
+
+ ```python
+ from langchain_core.messages import ToolMessage
+
+ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
+ ```
+
+ Example:
+ A `ToolMessage` where only part of the tool output is sent to the model
+ and the full output is passed in to artifact.
+
+ ```python
+ from langchain_core.messages import ToolMessage
+
+ tool_output = {
+ "stdout": "From the graph we can see that the correlation between "
+ "x and y is ...",
+ "stderr": None,
+ "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
+ }
+
+ ToolMessage(
+ content=tool_output["stdout"],
+ artifact=tool_output,
+ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
+ )
+ ```
+ """
+
+ tool_call_id: str
+ """Tool call that this message is responding to."""
+
+ type: Literal["tool"] = "tool"
+ """The type of the message (used for serialization)."""
+
+ artifact: Any = None
+ """Artifact of the Tool execution which is not meant to be sent to the model.
+
+ Should only be specified if it is different from the message content, e.g. if only
+ a subset of the full tool output is being passed as message content but the full
+ output is needed in other parts of the code.
+
+ """
+
+ status: Literal["success", "error"] = "success"
+ """Status of the tool invocation."""
+
+ additional_kwargs: dict = Field(default_factory=dict, repr=False)
+ """Currently inherited from `BaseMessage`, but not used."""
+ response_metadata: dict = Field(default_factory=dict, repr=False)
+ """Currently inherited from `BaseMessage`, but not used."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def coerce_args(cls, values: dict) -> dict:
+ """Coerce the model arguments to the correct types.
+
+ Args:
+ values: The model arguments.
+
+ """
+ content = values["content"]
+ if isinstance(content, tuple):
+ content = list(content)
+
+ if not isinstance(content, (str, list)):
+ try:
+ values["content"] = str(content)
+ except ValueError as e:
+ msg = (
+ "ToolMessage content should be a string or a list of string/dicts. "
+ f"Received:\n\n{content=}\n\n which could not be coerced into a "
+ "string."
+ )
+ raise ValueError(msg) from e
+ elif isinstance(content, list):
+ values["content"] = []
+ for i, x in enumerate(content):
+ if not isinstance(x, (str, dict)):
+ try:
+ values["content"].append(str(x))
+ except ValueError as e:
+ msg = (
+ "ToolMessage content should be a string or a list of "
+ "string/dicts. Received a list but "
+ f"element ToolMessage.content[{i}] is not a dict and could "
+ f"not be coerced to a string.:\n\n{x}"
+ )
+ raise ValueError(msg) from e
+ else:
+ values["content"].append(x)
+
+ tool_call_id = values["tool_call_id"]
+ if isinstance(tool_call_id, (UUID, int, float)):
+ values["tool_call_id"] = str(tool_call_id)
+ return values
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize a `ToolMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The contents of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional fields.
+ """
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class ToolMessageChunk(ToolMessage, BaseMessageChunk):
+ """Tool Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["ToolMessageChunk"] = "ToolMessageChunk" # type: ignore[assignment]
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, ToolMessageChunk):
+ if self.tool_call_id != other.tool_call_id:
+ msg = "Cannot concatenate ToolMessageChunks with different names."
+ raise ValueError(msg)
+
+ return self.__class__(
+ tool_call_id=self.tool_call_id,
+ content=merge_content(self.content, other.content),
+ artifact=merge_obj(self.artifact, other.artifact),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ status=_merge_status(self.status, other.status),
+ )
+
+ return super().__add__(other)
+
+
+class ToolCall(TypedDict):
+ """Represents an AI's request to call a tool.
+
+ Example:
+ ```python
+ {"name": "foo", "args": {"a": 1}, "id": "123"}
+ ```
+
+ This represents a request to call the tool named `'foo'` with arguments
+ `{"a": 1}` and an identifier of `'123'`.
+
+ !!! note "Factory function"
+
+ `tool_call` may also be used as a factory to create a `ToolCall`. Benefits
+ include:
+
+ * Required arguments strictly validated at creation time
+ """
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call as a dictionary."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+
+ type: NotRequired[Literal["tool_call"]]
+ """Used for discrimination."""
+
+
+def tool_call(
+ *,
+ name: str,
+ args: dict[str, Any],
+ id: str | None,
+) -> ToolCall:
+ """Create a tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a dictionary.
+ id: An identifier associated with the tool call.
+
+ Returns:
+ The created tool call.
+ """
+ return ToolCall(name=name, args=args, id=id, type="tool_call")
+
+
+class ToolCallChunk(TypedDict):
+ """A chunk of a tool call (yielded when streaming).
+
+ When merging `ToolCallChunk` objects (e.g., via `AIMessageChunk.__add__`), all
+ string attributes are concatenated. Chunks are only merged if their values of
+ `index` are equal and not `None`.
+
+ Example:
+ ```python
+ left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
+ right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
+
+ (
+ AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ + AIMessageChunk(content="", tool_call_chunks=right_chunks)
+ ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
+ ```
+ """
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call as a JSON-parseable string."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+
+ index: int | None
+ """The index of the tool call in a sequence.
+
+ Used for merging chunks.
+ """
+
+ type: NotRequired[Literal["tool_call_chunk"]]
+ """Used for discrimination."""
+
+
+def tool_call_chunk(
+ *,
+ name: str | None = None,
+ args: str | None = None,
+ id: str | None = None,
+ index: int | None = None,
+) -> ToolCallChunk:
+ """Create a tool call chunk.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a JSON string.
+ id: An identifier associated with the tool call.
+ index: The index of the tool call in a sequence.
+
+ Returns:
+ The created tool call chunk.
+ """
+ return ToolCallChunk(
+ name=name, args=args, id=id, index=index, type="tool_call_chunk"
+ )
+
+
+def invalid_tool_call(
+ *,
+ name: str | None = None,
+ args: str | None = None,
+ id: str | None = None,
+ error: str | None = None,
+) -> InvalidToolCall:
+ """Create an invalid tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a JSON string.
+ id: An identifier associated with the tool call.
+ error: An error message associated with the tool call.
+
+ Returns:
+ The created invalid tool call.
+ """
+ return InvalidToolCall(
+ name=name, args=args, id=id, error=error, type="invalid_tool_call"
+ )
+
+
+def default_tool_parser(
+ raw_tool_calls: list[dict],
+) -> tuple[list[ToolCall], list[InvalidToolCall]]:
+ """Best-effort parsing of tools.
+
+ Args:
+ raw_tool_calls: List of raw tool call dicts to parse.
+
+ Returns:
+ A list of tool calls and invalid tool calls.
+ """
+ tool_calls = []
+ invalid_tool_calls = []
+ for raw_tool_call in raw_tool_calls:
+ if "function" not in raw_tool_call:
+ continue
+ function_name = raw_tool_call["function"]["name"]
+ try:
+ function_args = json.loads(raw_tool_call["function"]["arguments"])
+ parsed = tool_call(
+ name=function_name or "",
+ args=function_args or {},
+ id=raw_tool_call.get("id"),
+ )
+ tool_calls.append(parsed)
+ except json.JSONDecodeError:
+ invalid_tool_calls.append(
+ invalid_tool_call(
+ name=function_name,
+ args=raw_tool_call["function"]["arguments"],
+ id=raw_tool_call.get("id"),
+ error=None,
+ )
+ )
+ return tool_calls, invalid_tool_calls
+
+
+def default_tool_chunk_parser(raw_tool_calls: list[dict]) -> list[ToolCallChunk]:
+ """Best-effort parsing of tool chunks.
+
+ Args:
+ raw_tool_calls: List of raw tool call dicts to parse.
+
+ Returns:
+ List of parsed ToolCallChunk objects.
+ """
+ tool_call_chunks = []
+ for tool_call in raw_tool_calls:
+ if "function" not in tool_call:
+ function_args = None
+ function_name = None
+ else:
+ function_args = tool_call["function"]["arguments"]
+ function_name = tool_call["function"]["name"]
+ parsed = tool_call_chunk(
+ name=function_name,
+ args=function_args,
+ id=tool_call.get("id"),
+ index=tool_call.get("index"),
+ )
+ tool_call_chunks.append(parsed)
+ return tool_call_chunks
+
+
+def _merge_status(
+ left: Literal["success", "error"], right: Literal["success", "error"]
+) -> Literal["success", "error"]:
+ return "error" if "error" in {left, right} else "success"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/messages/utils.py b/python/user_packages/Python313/site-packages/langchain_core/messages/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37d100c8f9c8aedab405cba434d9b2cf354e599
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/messages/utils.py
@@ -0,0 +1,2353 @@
+"""Module contains utility functions for working with messages.
+
+Some examples of what you can do with these functions include:
+
+* Convert messages to strings (serialization)
+* Convert messages from dicts to Message objects (deserialization)
+* Filter messages from a list of messages based on name, type or id etc.
+"""
+
+from __future__ import annotations
+
+import base64
+import inspect
+import json
+import logging
+import math
+from collections.abc import Callable, Iterable, Sequence
+from functools import partial, wraps
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Concatenate,
+ Literal,
+ ParamSpec,
+ Protocol,
+ TypeVar,
+ cast,
+ overload,
+)
+from xml.sax.saxutils import escape, quoteattr
+
+from pydantic import Discriminator, Field, Tag
+
+from langchain_core.exceptions import ErrorCode, create_message
+from langchain_core.messages.ai import AIMessage, AIMessageChunk
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_data_block,
+)
+from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
+from langchain_core.messages.content import (
+ is_data_content_block,
+)
+from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
+from langchain_core.messages.human import HumanMessage, HumanMessageChunk
+from langchain_core.messages.modifier import RemoveMessage
+from langchain_core.messages.system import SystemMessage, SystemMessageChunk
+from langchain_core.messages.tool import ToolCall, ToolMessage, ToolMessageChunk
+from langchain_core.utils.function_calling import convert_to_openai_tool
+
+if TYPE_CHECKING:
+ from langchain_core.language_models import BaseLanguageModel
+ from langchain_core.prompt_values import PromptValue
+ from langchain_core.runnables.base import Runnable
+ from langchain_core.tools import BaseTool
+
+try:
+ from langchain_text_splitters import TextSplitter
+
+ _HAS_LANGCHAIN_TEXT_SPLITTERS = True
+except ImportError:
+ _HAS_LANGCHAIN_TEXT_SPLITTERS = False
+
+logger = logging.getLogger(__name__)
+
+
+def _get_type(v: Any) -> str:
+ """Get the type associated with the object for serialization purposes."""
+ if isinstance(v, dict) and "type" in v:
+ result = v["type"]
+ elif hasattr(v, "type"):
+ result = v.type
+ else:
+ msg = (
+ f"Expected either a dictionary with a 'type' key or an object "
+ f"with a 'type' attribute. Instead got type {type(v)}."
+ )
+ raise TypeError(msg)
+ if not isinstance(result, str):
+ msg = f"Expected 'type' to be a str, got {type(result).__name__}"
+ raise TypeError(msg)
+ return result
+
+
+AnyMessage = Annotated[
+ Annotated[AIMessage, Tag(tag="ai")]
+ | Annotated[HumanMessage, Tag(tag="human")]
+ | Annotated[ChatMessage, Tag(tag="chat")]
+ | Annotated[SystemMessage, Tag(tag="system")]
+ | Annotated[FunctionMessage, Tag(tag="function")]
+ | Annotated[ToolMessage, Tag(tag="tool")]
+ | Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
+ | Annotated[HumanMessageChunk, Tag(tag="HumanMessageChunk")]
+ | Annotated[ChatMessageChunk, Tag(tag="ChatMessageChunk")]
+ | Annotated[SystemMessageChunk, Tag(tag="SystemMessageChunk")]
+ | Annotated[FunctionMessageChunk, Tag(tag="FunctionMessageChunk")]
+ | Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")],
+ Field(discriminator=Discriminator(_get_type)),
+]
+"""A type representing any defined `Message` or `MessageChunk` type."""
+
+
+def _has_base64_data(block: dict) -> bool:
+ """Check if a content block contains base64 encoded data.
+
+ Args:
+ block: A content block dictionary.
+
+ Returns:
+ Whether the block contains base64 data.
+ """
+ # Check for explicit base64 field (standard content blocks)
+ if block.get("base64"):
+ return True
+
+ # Check for data: URL in url field
+ url = block.get("url", "")
+ if isinstance(url, str) and url.startswith("data:"):
+ return True
+
+ # Check for OpenAI-style image_url with data: URL
+ image_url = block.get("image_url", {})
+ if isinstance(image_url, dict):
+ url = image_url.get("url", "")
+ if isinstance(url, str) and url.startswith("data:"):
+ return True
+
+ return False
+
+
+_XML_CONTENT_BLOCK_MAX_LEN = 500
+
+
+def _truncate(text: str, max_len: int = _XML_CONTENT_BLOCK_MAX_LEN) -> str:
+ """Truncate text to `max_len` characters, adding ellipsis if truncated."""
+ if len(text) <= max_len:
+ return text
+ return text[:max_len] + "..."
+
+
+def _format_content_block_xml(block: dict) -> str | None:
+ """Format a content block as XML.
+
+ Args:
+ block: A LangChain content block.
+
+ Returns:
+ XML string representation of the block, or `None` if the block should be
+ skipped.
+
+ Note:
+ Plain text document content, server tool call arguments, and server tool
+ result outputs are truncated to 500 characters.
+ """
+ block_type = block.get("type", "")
+
+ # Skip blocks with base64 encoded data
+ if _has_base64_data(block):
+ return None
+
+ # Text blocks
+ if block_type == "text":
+ text = block.get("text", "")
+ return escape(text) if text else None
+
+ # Reasoning blocks
+ if block_type == "reasoning":
+ reasoning = block.get("reasoning", "")
+ if reasoning:
+ return f"{escape(reasoning)} "
+ return None
+
+ # Image blocks (URL only, base64 already filtered)
+ if block_type == "image":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f" "
+ if file_id:
+ return f" "
+ return None
+
+ # OpenAI-style image_url blocks
+ if block_type == "image_url":
+ image_url = block.get("image_url", {})
+ if isinstance(image_url, dict):
+ url = image_url.get("url", "")
+ if url and not url.startswith("data:"):
+ return f" "
+ return None
+
+ # Audio blocks (URL only)
+ if block_type == "audio":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f""
+ if file_id:
+ return f""
+ return None
+
+ # Video blocks (URL only)
+ if block_type == "video":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f""
+ if file_id:
+ return f""
+ return None
+
+ # Plain text document blocks
+ if block_type == "text-plain":
+ text = block.get("text", "")
+ return escape(_truncate(text)) if text else None
+
+ # Server tool call blocks (from AI messages)
+ if block_type == "server_tool_call":
+ tc_id = quoteattr(str(block.get("id") or ""))
+ tc_name = quoteattr(str(block.get("name") or ""))
+ tc_args_json = json.dumps(block.get("args", {}), ensure_ascii=False)
+ tc_args = escape(_truncate(tc_args_json))
+ return (
+ f"{tc_args} "
+ )
+
+ # Server tool result blocks
+ if block_type == "server_tool_result":
+ tool_call_id = quoteattr(str(block.get("tool_call_id") or ""))
+ status = quoteattr(str(block.get("status") or ""))
+ output = block.get("output")
+ if output:
+ output_json = json.dumps(output, ensure_ascii=False)
+ output_str = escape(_truncate(output_json))
+ else:
+ output_str = ""
+ return (
+ f""
+ f"{output_str} "
+ )
+
+ # Unknown block type - skip silently
+ return None
+
+
+def _get_message_type_str(
+ m: BaseMessage,
+ human_prefix: str,
+ ai_prefix: str,
+ system_prefix: str,
+ function_prefix: str,
+ tool_prefix: str,
+) -> str:
+ """Get the type string for XML message element.
+
+ Args:
+ m: The message to get the type string for.
+ human_prefix: The prefix to use for `HumanMessage`.
+ ai_prefix: The prefix to use for `AIMessage`.
+ system_prefix: The prefix to use for `SystemMessage`.
+ function_prefix: The prefix to use for `FunctionMessage`.
+ tool_prefix: The prefix to use for `ToolMessage`.
+
+ Returns:
+ The type string for the message element.
+
+ Raises:
+ ValueError: If an unsupported message type is encountered.
+ """
+ if isinstance(m, HumanMessage):
+ return human_prefix.lower()
+ if isinstance(m, AIMessage):
+ return ai_prefix.lower()
+ if isinstance(m, SystemMessage):
+ return system_prefix.lower()
+ if isinstance(m, FunctionMessage):
+ return function_prefix.lower()
+ if isinstance(m, ToolMessage):
+ return tool_prefix.lower()
+ if isinstance(m, ChatMessage):
+ return m.role
+ msg = f"Got unsupported message type: {m}"
+ raise ValueError(msg)
+
+
+def get_buffer_string(
+ messages: Sequence[BaseMessage],
+ human_prefix: str = "Human",
+ ai_prefix: str = "AI",
+ *,
+ system_prefix: str = "System",
+ function_prefix: str = "Function",
+ tool_prefix: str = "Tool",
+ message_separator: str = "\n",
+ format: Literal["prefix", "xml"] = "prefix", # noqa: A002
+) -> str:
+ r"""Convert a sequence of messages to strings and concatenate them into one string.
+
+ Args:
+ messages: Messages to be converted to strings.
+ human_prefix: The prefix to prepend to contents of `HumanMessage`s.
+ ai_prefix: The prefix to prepend to contents of `AIMessage`.
+ system_prefix: The prefix to prepend to contents of `SystemMessage`s.
+ function_prefix: The prefix to prepend to contents of `FunctionMessage`s.
+ tool_prefix: The prefix to prepend to contents of `ToolMessage`s.
+ message_separator: The separator to use between messages.
+ format: The output format. `'prefix'` uses `Role: content` format (default).
+
+ `'xml'` uses XML-style `` format with proper character
+ escaping, which is useful when message content may contain role-like
+ prefixes that could cause ambiguity.
+
+ Returns:
+ A single string concatenation of all input messages.
+
+ Raises:
+ ValueError: If an unsupported message type is encountered.
+
+ !!! warning
+
+ If a message is an `AIMessage` and contains both tool calls under `tool_calls`
+ and a function call under `additional_kwargs["function_call"]`, only the tool
+ calls will be appended to the string representation.
+
+ !!! note "XML format"
+
+ When using `format='xml'`:
+
+ - All messages use uniform `content ` format.
+ - The `type` attribute uses `human_prefix` (lowercased) for `HumanMessage`,
+ `ai_prefix` (lowercased) for `AIMessage`, `system_prefix` (lowercased)
+ for `SystemMessage`, `function_prefix` (lowercased) for `FunctionMessage`,
+ `tool_prefix` (lowercased) for `ToolMessage`, and the original role
+ (unchanged) for `ChatMessage`.
+ - Message content is escaped using `xml.sax.saxutils.escape()`.
+ - Attribute values are escaped using `xml.sax.saxutils.quoteattr()`.
+ - AI messages with tool calls use nested structure with `` and
+ `` elements.
+ - For multi-modal content (list of content blocks), supported block types
+ are: `text`, `reasoning`, `image` (URL/file_id only), `image_url`
+ (OpenAI-style, URL only), `audio` (URL/file_id only), `video` (URL/file_id
+ only), `text-plain`, `server_tool_call`, and `server_tool_result`.
+ - Content blocks with base64-encoded data are skipped (including blocks
+ with `base64` field or `data:` URLs).
+ - Unknown block types are skipped.
+ - Plain text document content (`text-plain`), server tool call arguments,
+ and server tool result outputs are truncated to 500 characters.
+
+ Example:
+ Default prefix format:
+
+ ```python
+ from langchain_core.messages import AIMessage, HumanMessage, get_buffer_string
+
+ messages = [
+ HumanMessage(content="Hi, how are you?"),
+ AIMessage(content="Good, how are you?"),
+ ]
+ get_buffer_string(messages)
+ # -> "Human: Hi, how are you?\nAI: Good, how are you?"
+ ```
+
+ XML format (useful when content contains role-like prefixes):
+
+ ```python
+ messages = [
+ HumanMessage(content="Example: Human: some text"),
+ AIMessage(content="I see the example."),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> 'Example: Human: some text \\n'
+ # -> 'I see the example. '
+ ```
+
+ XML format with special characters (automatically escaped):
+
+ ```python
+ messages = [
+ HumanMessage(content="Is 5 < 10 & 10 > 5?"),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> 'Is 5 < 10 & 10 > 5? '
+ ```
+
+ XML format with tool calls:
+
+ ```python
+ messages = [
+ AIMessage(
+ content="I'll search for that.",
+ tool_calls=[
+ {"id": "call_123", "name": "search", "args": {"query": "weather"}}
+ ],
+ ),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> '\\n'
+ # -> ' I\\'ll search for that. \\n'
+ # -> ' '
+ # -> '{"query": "weather"} \\n'
+ # -> ' '
+ ```
+ """
+ if format not in {"prefix", "xml"}:
+ msg = (
+ f"Unrecognized format={format!r}. Supported formats are 'prefix' and 'xml'."
+ )
+ raise ValueError(msg)
+
+ string_messages = []
+ for m in messages:
+ if isinstance(m, HumanMessage):
+ role = human_prefix
+ elif isinstance(m, AIMessage):
+ role = ai_prefix
+ elif isinstance(m, SystemMessage):
+ role = system_prefix
+ elif isinstance(m, FunctionMessage):
+ role = function_prefix
+ elif isinstance(m, ToolMessage):
+ role = tool_prefix
+ elif isinstance(m, ChatMessage):
+ role = m.role
+ else:
+ msg = f"Got unsupported message type: {m}"
+ raise ValueError(msg) # noqa: TRY004
+
+ if format == "xml":
+ msg_type = _get_message_type_str(
+ m, human_prefix, ai_prefix, system_prefix, function_prefix, tool_prefix
+ )
+
+ # Format content blocks
+ if isinstance(m.content, str):
+ content_parts = [escape(m.content)] if m.content else []
+ else:
+ # List of content blocks
+ content_parts = []
+ for block in m.content:
+ if isinstance(block, str):
+ if block:
+ content_parts.append(escape(block))
+ else:
+ formatted = _format_content_block_xml(block)
+ if formatted:
+ content_parts.append(formatted)
+
+ # Check if this is an AIMessage with tool calls
+ has_tool_calls = isinstance(m, AIMessage) and m.tool_calls
+ has_function_call = (
+ isinstance(m, AIMessage)
+ and not m.tool_calls
+ and "function_call" in m.additional_kwargs
+ )
+
+ if has_tool_calls or has_function_call:
+ # Use nested structure for AI messages with tool calls
+ # Type narrowing: at this point m is AIMessage (verified above)
+ ai_msg = cast("AIMessage", m)
+ parts = [f""]
+ if content_parts:
+ parts.append(f" {' '.join(content_parts)} ")
+
+ if has_tool_calls:
+ for tc in ai_msg.tool_calls:
+ tc_id = quoteattr(str(tc.get("id") or ""))
+ tc_name = quoteattr(str(tc.get("name") or ""))
+ tc_args = escape(
+ json.dumps(tc.get("args", {}), ensure_ascii=False)
+ )
+ parts.append(
+ f" "
+ f"{tc_args} "
+ )
+ elif has_function_call:
+ fc = ai_msg.additional_kwargs["function_call"]
+ fc_name = quoteattr(str(fc.get("name") or ""))
+ fc_args = escape(str(fc.get("arguments") or "{}"))
+ parts.append(
+ f" {fc_args} "
+ )
+
+ parts.append(" ")
+ message = "\n".join(parts)
+ else:
+ # Simple structure for messages without tool calls
+ joined_content = " ".join(content_parts)
+ message = (
+ f"{joined_content} "
+ )
+ else: # format == "prefix"
+ content = m.text
+ message = f"{role}: {content}"
+ tool_info = ""
+ if isinstance(m, AIMessage):
+ if m.tool_calls:
+ tool_info = str(m.tool_calls)
+ elif "function_call" in m.additional_kwargs:
+ # Legacy behavior assumes only one function call per message
+ tool_info = str(m.additional_kwargs["function_call"])
+ if tool_info:
+ message += tool_info # Preserve original behavior
+
+ string_messages.append(message)
+
+ return message_separator.join(string_messages)
+
+
+def _message_from_dict(message: dict) -> BaseMessage:
+ type_ = message["type"]
+ if type_ == "human":
+ return HumanMessage(**message["data"])
+ if type_ == "ai":
+ return AIMessage(**message["data"])
+ if type_ == "system":
+ return SystemMessage(**message["data"])
+ if type_ == "chat":
+ return ChatMessage(**message["data"])
+ if type_ == "function":
+ return FunctionMessage(**message["data"])
+ if type_ == "tool":
+ return ToolMessage(**message["data"])
+ if type_ == "remove":
+ return RemoveMessage(**message["data"])
+ if type_ == "AIMessageChunk":
+ return AIMessageChunk(**message["data"])
+ if type_ == "HumanMessageChunk":
+ return HumanMessageChunk(**message["data"])
+ if type_ == "FunctionMessageChunk":
+ return FunctionMessageChunk(**message["data"])
+ if type_ == "ToolMessageChunk":
+ return ToolMessageChunk(**message["data"])
+ if type_ == "SystemMessageChunk":
+ return SystemMessageChunk(**message["data"])
+ if type_ == "ChatMessageChunk":
+ return ChatMessageChunk(**message["data"])
+ msg = f"Got unexpected message type: {type_}"
+ raise ValueError(msg)
+
+
+def messages_from_dict(messages: Sequence[dict]) -> list[BaseMessage]:
+ """Convert a sequence of messages from dicts to `Message` objects.
+
+ Args:
+ messages: Sequence of messages (as dicts) to convert.
+
+ Returns:
+ list of messages (BaseMessages).
+
+ """
+ return [_message_from_dict(m) for m in messages]
+
+
+def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage:
+ """Convert a message chunk to a `Message`.
+
+ Args:
+ chunk: Message chunk to convert.
+
+ Returns:
+ Message.
+ """
+ if not isinstance(chunk, BaseMessageChunk):
+ return chunk
+ # chunk classes always have the equivalent non-chunk class as their first parent
+ ignore_keys = ["type"]
+ if isinstance(chunk, AIMessageChunk):
+ ignore_keys.extend(["tool_call_chunks", "chunk_position"])
+ return cast(
+ "BaseMessage",
+ chunk.__class__.__mro__[1](
+ **{k: v for k, v in chunk.__dict__.items() if k not in ignore_keys}
+ ),
+ )
+
+
+MessageLikeRepresentation = (
+ BaseMessage | list[str] | tuple[str, str] | str | dict[str, Any]
+)
+"""A type representing the various ways a message can be represented."""
+
+
+def _create_message_from_message_type(
+ message_type: str,
+ content: str,
+ name: str | None = None,
+ tool_call_id: str | None = None,
+ tool_calls: list[dict[str, Any]] | None = None,
+ id: str | None = None,
+ **additional_kwargs: Any,
+) -> BaseMessage:
+ """Create a message from a `Message` type and content string.
+
+ Args:
+ message_type: the type of the message (e.g., `'human'`, `'ai'`, etc.).
+ content: the content string.
+ name: the name of the message.
+ tool_call_id: the tool call id.
+ tool_calls: the tool calls.
+ id: the id of the message.
+ additional_kwargs: additional keyword arguments.
+
+ Returns:
+ a message of the appropriate type.
+
+ Raises:
+ ValueError: if the message type is not one of `'human'`, `'user'`, `'ai'`,
+ `'assistant'`, `'function'`, `'tool'`, `'system'`, or
+ `'developer'`.
+ """
+ kwargs: dict[str, Any] = {}
+ if name is not None:
+ kwargs["name"] = name
+ if tool_call_id is not None:
+ kwargs["tool_call_id"] = tool_call_id
+ if additional_kwargs:
+ if response_metadata := additional_kwargs.pop("response_metadata", None):
+ kwargs["response_metadata"] = response_metadata
+ kwargs["additional_kwargs"] = additional_kwargs
+ additional_kwargs.update(additional_kwargs.pop("additional_kwargs", {}))
+ if id is not None:
+ kwargs["id"] = id
+ if tool_calls is not None:
+ kwargs["tool_calls"] = []
+ for tool_call in tool_calls:
+ # Convert OpenAI-format tool call to LangChain format.
+ if "function" in tool_call:
+ args = tool_call["function"]["arguments"]
+ if isinstance(args, str):
+ args = json.loads(args, strict=False)
+ kwargs["tool_calls"].append(
+ {
+ "name": tool_call["function"]["name"],
+ "args": args,
+ "id": tool_call["id"],
+ "type": "tool_call",
+ }
+ )
+ else:
+ kwargs["tool_calls"].append(tool_call)
+ if message_type in {"human", "user"}:
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
+ kwargs["example"] = example
+ message: BaseMessage = HumanMessage(content=content, **kwargs)
+ elif message_type in {"ai", "assistant"}:
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
+ kwargs["example"] = example
+ message = AIMessage(content=content, **kwargs)
+ elif message_type in {"system", "developer"}:
+ if message_type == "developer":
+ kwargs["additional_kwargs"] = kwargs.get("additional_kwargs") or {}
+ kwargs["additional_kwargs"]["__openai_role__"] = "developer"
+ message = SystemMessage(content=content, **kwargs)
+ elif message_type == "function":
+ message = FunctionMessage(content=content, **kwargs)
+ elif message_type == "tool":
+ artifact = kwargs.get("additional_kwargs", {}).pop("artifact", None)
+ status = kwargs.get("additional_kwargs", {}).pop("status", None)
+ if status is not None:
+ kwargs["status"] = status
+ message = ToolMessage(content=content, artifact=artifact, **kwargs)
+ elif message_type == "remove":
+ message = RemoveMessage(**kwargs)
+ else:
+ msg = (
+ f"Unexpected message type: '{message_type}'. Use one of 'human',"
+ f" 'user', 'ai', 'assistant', 'function', 'tool', 'system', or 'developer'."
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+ return message
+
+
+def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
+ """Instantiate a `Message` from a variety of message formats.
+
+ The message format can be one of the following:
+
+ - `BaseMessagePromptTemplate`
+ - `BaseMessage`
+ - 2-tuple of (role string, template); e.g., (`'human'`, `'{user_input}'`)
+ - dict: a message dict with role and content keys
+ - string: shorthand for (`'human'`, template); e.g., `'{user_input}'`
+
+ Args:
+ message: a representation of a message in one of the supported formats.
+
+ Returns:
+ An instance of a message or a message template.
+
+ Raises:
+ NotImplementedError: if the message type is not supported.
+ ValueError: if the message dict does not contain the required keys.
+
+ """
+ if isinstance(message, BaseMessage):
+ message_ = message
+ elif isinstance(message, Sequence):
+ if isinstance(message, str):
+ message_ = _create_message_from_message_type("human", message)
+ else:
+ try:
+ message_type_str, template = message
+ except ValueError as e:
+ msg = "Message as a sequence must be (role string, template)"
+ raise NotImplementedError(msg) from e
+ message_ = _create_message_from_message_type(message_type_str, template)
+ elif isinstance(message, dict):
+ msg_kwargs = message.copy()
+ try:
+ try:
+ msg_type = msg_kwargs.pop("role")
+ except KeyError:
+ msg_type = msg_kwargs.pop("type")
+ # None msg content is not allowed
+ msg_content = msg_kwargs.pop("content") or ""
+ except KeyError as e:
+ msg = f"Message dict must contain 'role' and 'content' keys, got {message}"
+ msg = create_message(
+ message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE
+ )
+ raise ValueError(msg) from e
+ message_ = _create_message_from_message_type(
+ msg_type, msg_content, **msg_kwargs
+ )
+ else:
+ msg = f"Unsupported message type: {type(message)}"
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise NotImplementedError(msg)
+
+ return message_
+
+
+def convert_to_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+) -> list[BaseMessage]:
+ """Convert a sequence of messages to a list of messages.
+
+ Args:
+ messages: Sequence of messages to convert.
+
+ Returns:
+ list of messages (BaseMessages).
+
+ """
+ # Import here to avoid circular imports
+ from langchain_core.prompt_values import PromptValue # noqa: PLC0415
+
+ if isinstance(messages, PromptValue):
+ return messages.to_messages()
+ return [_convert_to_message(m) for m in messages]
+
+
+_P = ParamSpec("_P")
+_R_co = TypeVar("_R_co", covariant=True)
+
+
+class _RunnableSupportCallable(Protocol[_P, _R_co]):
+ @overload
+ def __call__(
+ self,
+ messages: None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
+
+ @overload
+ def __call__(
+ self,
+ messages: Sequence[MessageLikeRepresentation] | PromptValue,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co: ...
+
+ def __call__(
+ self,
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
+
+
+def _runnable_support(
+ func: Callable[
+ Concatenate[Sequence[MessageLikeRepresentation] | PromptValue, _P], _R_co
+ ],
+) -> _RunnableSupportCallable[_P, _R_co]:
+ @wraps(func)
+ def wrapped(
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]:
+ # Import locally to prevent circular import.
+ from langchain_core.runnables.base import RunnableLambda # noqa: PLC0415
+
+ if messages is not None:
+ return func(messages, *args, **kwargs)
+ return RunnableLambda(partial(func, **kwargs), name=func.__name__)
+
+ return cast("_RunnableSupportCallable[_P, _R_co]", wrapped)
+
+
+@_runnable_support
+def filter_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ include_names: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ include_types: Sequence[str | type[BaseMessage]] | None = None,
+ exclude_types: Sequence[str | type[BaseMessage]] | None = None,
+ include_ids: Sequence[str] | None = None,
+ exclude_ids: Sequence[str] | None = None,
+ exclude_tool_calls: Sequence[str] | bool | None = None,
+) -> list[BaseMessage]:
+ """Filter messages based on `name`, `type` or `id`.
+
+ Args:
+ messages: Sequence Message-like objects to filter.
+ include_names: Message names to include.
+ exclude_names: Messages names to exclude.
+ include_types: Message types to include. Can be specified as string names
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
+
+ exclude_types: Message types to exclude. Can be specified as string names
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
+
+ include_ids: Message IDs to include.
+ exclude_ids: Message IDs to exclude.
+ exclude_tool_calls: Tool call IDs to exclude.
+ Can be one of the following:
+ - `True`: All `AIMessage` objects with tool calls and all `ToolMessage`
+ objects will be excluded.
+ - a sequence of tool call IDs to exclude:
+ - `ToolMessage` objects with the corresponding tool call ID will be
+ excluded.
+ - The `tool_calls` in the AIMessage will be updated to exclude
+ matching tool calls. If all `tool_calls` are filtered from an
+ AIMessage, the whole message is excluded.
+
+ Returns:
+ A list of Messages that meets at least one of the `incl_*` conditions and none
+ of the `excl_*` conditions. If not `incl_*` conditions are specified then
+ anything that is not explicitly excluded will be included.
+
+ Raises:
+ ValueError: If two incompatible arguments are provided.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ filter_messages,
+ AIMessage,
+ HumanMessage,
+ SystemMessage,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant."),
+ HumanMessage("what's your name", id="foo", name="example_user"),
+ AIMessage("steve-o", id="bar", name="example_assistant"),
+ HumanMessage(
+ "what's your favorite color",
+ id="baz",
+ ),
+ AIMessage(
+ "silicon blue",
+ id="blah",
+ ),
+ ]
+
+ filter_messages(
+ messages,
+ include_names=("example_user", "example_assistant"),
+ include_types=("system",),
+ exclude_ids=("bar",),
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage("you're a good assistant."),
+ HumanMessage("what's your name", id="foo", name="example_user"),
+ ]
+ ```
+ """
+ messages = convert_to_messages(messages)
+ filtered: list[BaseMessage] = []
+ for msg in messages:
+ if (
+ (exclude_names and msg.name in exclude_names)
+ or (exclude_types and _is_message_type(msg, exclude_types))
+ or (exclude_ids and msg.id in exclude_ids)
+ ):
+ continue
+
+ if exclude_tool_calls is True and (
+ (isinstance(msg, AIMessage) and msg.tool_calls)
+ or isinstance(msg, ToolMessage)
+ ):
+ continue
+
+ new_msg = msg
+ if isinstance(exclude_tool_calls, (list, tuple, set)):
+ if isinstance(msg, AIMessage) and msg.tool_calls:
+ tool_calls = [
+ tool_call
+ for tool_call in msg.tool_calls
+ if tool_call["id"] not in exclude_tool_calls
+ ]
+ if not tool_calls:
+ continue
+
+ content = msg.content
+ # handle Anthropic content blocks
+ if isinstance(msg.content, list):
+ content = [
+ content_block
+ for content_block in msg.content
+ if (
+ not isinstance(content_block, dict)
+ or content_block.get("type") != "tool_use"
+ or content_block.get("id") not in exclude_tool_calls
+ )
+ ]
+
+ new_msg = msg.model_copy(
+ update={"tool_calls": tool_calls, "content": content}
+ )
+ elif (
+ isinstance(msg, ToolMessage) and msg.tool_call_id in exclude_tool_calls
+ ):
+ continue
+
+ # default to inclusion when no inclusion criteria given.
+ if (
+ not (include_types or include_ids or include_names)
+ or (include_names and new_msg.name in include_names)
+ or (include_types and _is_message_type(new_msg, include_types))
+ or (include_ids and new_msg.id in include_ids)
+ ):
+ filtered.append(new_msg)
+
+ return filtered
+
+
+@_runnable_support
+def merge_message_runs(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ chunk_separator: str = "\n",
+) -> list[BaseMessage]:
+ r"""Merge consecutive Messages of the same type.
+
+ !!! note
+ `ToolMessage` objects are not merged, as each has a distinct tool call id that
+ can't be merged.
+
+ Args:
+ messages: Sequence Message-like objects to merge.
+ chunk_separator: Specify the string to be inserted between message chunks.
+
+ Returns:
+ list of BaseMessages with consecutive runs of message types merged into single
+ messages. By default, if two messages being merged both have string contents,
+ the merged content is a concatenation of the two strings with a new-line
+ separator.
+ The separator inserted between message chunks can be controlled by specifying
+ any string with `chunk_separator`. If at least one of the messages has a list
+ of content blocks, the merged content is a list of content blocks.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ merge_message_runs,
+ AIMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolCall,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant."),
+ HumanMessage(
+ "what's your favorite color",
+ id="foo",
+ ),
+ HumanMessage(
+ "wait your favorite food",
+ id="bar",
+ ),
+ AIMessage(
+ "my favorite colo",
+ tool_calls=[
+ ToolCall(
+ name="blah_tool", args={"x": 2}, id="123", type="tool_call"
+ )
+ ],
+ id="baz",
+ ),
+ AIMessage(
+ [{"type": "text", "text": "my favorite dish is lasagna"}],
+ tool_calls=[
+ ToolCall(
+ name="blah_tool",
+ args={"x": -10},
+ id="456",
+ type="tool_call",
+ )
+ ],
+ id="blur",
+ ),
+ ]
+
+ merge_message_runs(messages)
+ ```
+
+ ```python
+ [
+ SystemMessage("you're a good assistant."),
+ HumanMessage(
+ "what's your favorite color\\n"
+ "wait your favorite food", id="foo",
+ ),
+ AIMessage(
+ [
+ "my favorite colo",
+ {"type": "text", "text": "my favorite dish is lasagna"}
+ ],
+ tool_calls=[
+ ToolCall({
+ "name": "blah_tool",
+ "args": {"x": 2},
+ "id": "123",
+ "type": "tool_call"
+ }),
+ ToolCall({
+ "name": "blah_tool",
+ "args": {"x": -10},
+ "id": "456",
+ "type": "tool_call"
+ })
+ ]
+ id="baz"
+ ),
+ ]
+
+ ```
+ """
+ if not messages:
+ return []
+ messages = convert_to_messages(messages)
+ merged: list[BaseMessage] = []
+ for msg in messages:
+ last = merged.pop() if merged else None
+ if not last:
+ merged.append(msg)
+ elif isinstance(msg, ToolMessage) or not isinstance(msg, last.__class__):
+ merged.extend([last, msg])
+ else:
+ last_chunk = _msg_to_chunk(last)
+ curr_chunk = _msg_to_chunk(msg)
+ if curr_chunk.response_metadata:
+ curr_chunk.response_metadata.clear()
+ if (
+ isinstance(last_chunk.content, str)
+ and isinstance(curr_chunk.content, str)
+ and last_chunk.content
+ and curr_chunk.content
+ ):
+ last_chunk.content += chunk_separator
+ merged.append(_chunk_to_msg(last_chunk + curr_chunk))
+ return merged
+
+
+# TODO: Update so validation errors (for token_counter, for example) are raised on
+# init not at runtime.
+@_runnable_support
+def trim_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int]
+ | Callable[[BaseMessage], int]
+ | BaseLanguageModel
+ | Literal["approximate"],
+ strategy: Literal["first", "last"] = "last",
+ allow_partial: bool = False,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ include_system: bool = False,
+ text_splitter: Callable[[str], list[str]] | TextSplitter | None = None,
+) -> list[BaseMessage]:
+ r"""Trim messages to be below a token count.
+
+ `trim_messages` can be used to reduce the size of a chat history to a specified
+ token or message count.
+
+ In either case, if passing the trimmed chat history back into a chat model
+ directly, the resulting chat history should usually satisfy the following
+ properties:
+
+ 1. The resulting chat history should be valid. Most chat models expect that chat
+ history starts with either (1) a `HumanMessage` or (2) a `SystemMessage`
+ followed by a `HumanMessage`. To achieve this, set `start_on='human'`.
+ In addition, generally a `ToolMessage` can only appear after an `AIMessage`
+ that involved a tool call.
+ 2. It includes recent messages and drops old messages in the chat history.
+ To achieve this set the `strategy='last'`.
+ 3. Usually, the new chat history should include the `SystemMessage` if it
+ was present in the original chat history since the `SystemMessage` includes
+ special instructions to the chat model. The `SystemMessage` is almost always
+ the first message in the history if present. To achieve this set the
+ `include_system=True`.
+
+ !!! note
+ The examples below show how to configure `trim_messages` to achieve a behavior
+ consistent with the above properties.
+
+ Args:
+ messages: Sequence of Message-like objects to trim.
+ max_tokens: Max token count of trimmed messages.
+ token_counter: Function or llm for counting tokens in a `BaseMessage` or a
+ list of `BaseMessage`.
+
+ If a `BaseLanguageModel` is passed in then
+ `BaseLanguageModel.get_num_tokens_from_messages()` will be used. Set to
+ `len` to count the number of **messages** in the chat history.
+
+ You can also use string shortcuts for convenience:
+
+ - `'approximate'`: Uses `count_tokens_approximately` for fast, approximate
+ token counts.
+
+ !!! note
+
+ `count_tokens_approximately` (or the shortcut `'approximate'`) is
+ recommended for using `trim_messages` on the hot path, where exact token
+ counting is not necessary.
+
+ strategy: Strategy for trimming.
+
+ - `'first'`: Keep the first `<= n_count` tokens of the messages.
+ - `'last'`: Keep the last `<= n_count` tokens of the messages.
+ allow_partial: Whether to split a message if only part of the message can be
+ included.
+
+ If `strategy='last'` then the last partial contents of a message are
+ included. If `strategy='first'` then the first partial contents of a
+ message are included.
+ end_on: The message type to end on.
+
+ If specified then every message after the last occurrence of this type is
+ ignored. If `strategy='last'` then this is done before we attempt to get the
+ last `max_tokens`. If `strategy='first'` then this is done after we get the
+ first `max_tokens`. Can be specified as string names (e.g. `'system'`,
+ `'human'`, `'ai'`, ...) or as `BaseMessage` classes (e.g. `SystemMessage`,
+ `HumanMessage`, `AIMessage`, ...). Can be a single type or a list of types.
+
+ start_on: The message type to start on.
+
+ Should only be specified if `strategy='last'`. If specified then every
+ message before the first occurrence of this type is ignored. This is done
+ after we trim the initial messages to the last `max_tokens`. Does not apply
+ to a `SystemMessage` at index 0 if `include_system=True`. Can be specified
+ as string names (e.g. `'system'`, `'human'`, `'ai'`, ...) or as
+ `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`,
+ ...). Can be a single type or a list of types.
+
+ include_system: Whether to keep the `SystemMessage` if there is one at index
+ `0`.
+
+ Should only be specified if `strategy="last"`.
+ text_splitter: Function or `langchain_text_splitters.TextSplitter` for
+ splitting the string contents of a message.
+
+ Only used if `allow_partial=True`. If `strategy='last'` then the last split
+ tokens from a partial message will be included. if `strategy='first'` then
+ the first split tokens from a partial message will be included. Token
+ splitter assumes that separators are kept, so that split contents can be
+ directly concatenated to recreate the original text. Defaults to splitting
+ on newlines.
+
+ Returns:
+ List of trimmed `BaseMessage`.
+
+ Raises:
+ ValueError: if two incompatible arguments are specified or an unrecognized
+ `strategy` is specified.
+
+ Example:
+ Trim chat history based on token count, keeping the `SystemMessage` if
+ present, and ensuring that the chat history starts with a `HumanMessage` (or a
+ `SystemMessage` followed by a `HumanMessage`).
+
+ ```python
+ from langchain_core.messages import (
+ AIMessage,
+ HumanMessage,
+ BaseMessage,
+ SystemMessage,
+ trim_messages,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant, you always respond with a joke."),
+ HumanMessage("i wonder why it's called langchain"),
+ AIMessage(
+ 'Well, I guess they thought "WordRope" and "SentenceString" just '
+ "didn't have the same ring to it!"
+ ),
+ HumanMessage("and who is harrison chasing anyways"),
+ AIMessage(
+ "Hmmm let me think.\n\nWhy, he's probably chasing after the last "
+ "cup of coffee in the office!"
+ ),
+ HumanMessage("what do you call a speechless parrot"),
+ ]
+
+
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ token_counter=ChatOpenAI(model="gpt-4o"),
+ # Most chat models expect that chat history starts with either:
+ # (1) a HumanMessage or
+ # (2) a SystemMessage followed by a HumanMessage
+ start_on="human",
+ # Usually, we want to keep the SystemMessage
+ # if it's present in the original history.
+ # The SystemMessage has special instructions for the model.
+ include_system=True,
+ allow_partial=False,
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage(
+ content="you're a good assistant, you always respond with a joke."
+ ),
+ HumanMessage(content="what do you call a speechless parrot"),
+ ]
+ ```
+
+ Trim chat history using approximate token counting with `'approximate'`:
+
+ ```python
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ # Using the "approximate" shortcut for fast token counting
+ token_counter="approximate",
+ start_on="human",
+ include_system=True,
+ )
+
+ # This is equivalent to using `count_tokens_approximately` directly
+ from langchain_core.messages.utils import count_tokens_approximately
+
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ token_counter=count_tokens_approximately,
+ start_on="human",
+ include_system=True,
+ )
+ ```
+
+ Trim chat history based on the message count, keeping the `SystemMessage` if
+ present, and ensuring that the chat history starts with a HumanMessage (
+ or a `SystemMessage` followed by a `HumanMessage`).
+
+ trim_messages(
+ messages,
+ # When `len` is passed in as the token counter function,
+ # max_tokens will count the number of messages in the chat history.
+ max_tokens=4,
+ strategy="last",
+ # Passing in `len` as a token counter function will
+ # count the number of messages in the chat history.
+ token_counter=len,
+ # Most chat models expect that chat history starts with either:
+ # (1) a HumanMessage or
+ # (2) a SystemMessage followed by a HumanMessage
+ start_on="human",
+ # Usually, we want to keep the SystemMessage
+ # if it's present in the original history.
+ # The SystemMessage has special instructions for the model.
+ include_system=True,
+ allow_partial=False,
+ )
+
+ ```python
+ [
+ SystemMessage(
+ content="you're a good assistant, you always respond with a joke."
+ ),
+ HumanMessage(content="and who is harrison chasing anyways"),
+ AIMessage(
+ content="Hmmm let me think.\n\nWhy, he's probably chasing after "
+ "the last cup of coffee in the office!"
+ ),
+ HumanMessage(content="what do you call a speechless parrot"),
+ ]
+ ```
+ Trim chat history using a custom token counter function that counts the
+ number of tokens in each message.
+
+ ```python
+ messages = [
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.", id="first"
+ ),
+ AIMessage(
+ [
+ {"type": "text", "text": "This is the FIRST 4 token block."},
+ {"type": "text", "text": "This is the SECOND 4 token block."},
+ ],
+ id="second",
+ ),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.", id="third"
+ ),
+ AIMessage(
+ "This is a 4 token text. The full message is 10 tokens.",
+ id="fourth",
+ ),
+ ]
+
+
+ def dummy_token_counter(messages: list[BaseMessage]) -> int:
+ # treat each message like it adds 3 default tokens at the beginning
+ # of the message and at the end of the message. 3 + 4 + 3 = 10 tokens
+ # per message.
+
+ default_content_len = 4
+ default_msg_prefix_len = 3
+ default_msg_suffix_len = 3
+
+ count = 0
+ for msg in messages:
+ if isinstance(msg.content, str):
+ count += (
+ default_msg_prefix_len
+ + default_content_len
+ + default_msg_suffix_len
+ )
+ if isinstance(msg.content, list):
+ count += (
+ default_msg_prefix_len
+ + len(msg.content) * default_content_len
+ + default_msg_suffix_len
+ )
+ return count
+ ```
+
+ First 30 tokens, allowing partial messages:
+ ```python
+ trim_messages(
+ messages,
+ max_tokens=30,
+ token_counter=dummy_token_counter,
+ strategy="first",
+ allow_partial=True,
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.",
+ id="first",
+ ),
+ AIMessage(
+ [{"type": "text", "text": "This is the FIRST 4 token block."}],
+ id="second",
+ ),
+ ]
+ ```
+ """
+ # Validate arguments
+ if start_on and strategy == "first":
+ msg = "start_on parameter is only valid with strategy='last'"
+ raise ValueError(msg)
+ if include_system and strategy == "first":
+ msg = "include_system parameter is only valid with strategy='last'"
+ raise ValueError(msg)
+
+ messages = convert_to_messages(messages)
+
+ # Handle string shortcuts for token counter
+ if isinstance(token_counter, str):
+ if token_counter in _TOKEN_COUNTER_SHORTCUTS:
+ actual_token_counter = _TOKEN_COUNTER_SHORTCUTS[token_counter]
+ else:
+ available_shortcuts = ", ".join(
+ f"'{key}'" for key in _TOKEN_COUNTER_SHORTCUTS
+ )
+ msg = (
+ f"Invalid token_counter shortcut '{token_counter}'. "
+ f"Available shortcuts: {available_shortcuts}."
+ )
+ raise ValueError(msg)
+ else:
+ # Type narrowing: at this point token_counter is not a str
+ actual_token_counter = token_counter # type: ignore[assignment]
+
+ if hasattr(actual_token_counter, "get_num_tokens_from_messages"):
+ list_token_counter = actual_token_counter.get_num_tokens_from_messages
+ elif callable(actual_token_counter):
+ if (
+ next(
+ iter(inspect.signature(actual_token_counter).parameters.values())
+ ).annotation
+ is BaseMessage
+ ):
+
+ def list_token_counter(messages: Sequence[BaseMessage]) -> int:
+ return sum(actual_token_counter(msg) for msg in messages) # type: ignore[arg-type, misc]
+
+ else:
+ list_token_counter = actual_token_counter
+ else:
+ msg = (
+ f"'token_counter' expected to be a model that implements "
+ f"'get_num_tokens_from_messages()' or a function. Received object of type "
+ f"{type(actual_token_counter)}."
+ )
+ raise ValueError(msg)
+
+ if _HAS_LANGCHAIN_TEXT_SPLITTERS and isinstance(text_splitter, TextSplitter):
+ text_splitter_fn = text_splitter.split_text
+ elif text_splitter:
+ text_splitter_fn = cast("Callable", text_splitter)
+ else:
+ text_splitter_fn = _default_text_splitter
+
+ if strategy == "first":
+ return _first_max_tokens(
+ messages,
+ max_tokens=max_tokens,
+ token_counter=list_token_counter,
+ text_splitter=text_splitter_fn,
+ partial_strategy="first" if allow_partial else None,
+ end_on=end_on,
+ )
+ if strategy == "last":
+ return _last_max_tokens(
+ messages,
+ max_tokens=max_tokens,
+ token_counter=list_token_counter,
+ allow_partial=allow_partial,
+ include_system=include_system,
+ start_on=start_on,
+ end_on=end_on,
+ text_splitter=text_splitter_fn,
+ )
+ msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'."
+ raise ValueError(msg)
+
+
+_SingleMessage = BaseMessage | str | dict[str, Any]
+_T = TypeVar("_T", bound=_SingleMessage)
+# A sequence of _SingleMessage that is NOT a bare str
+_MultipleMessages = Sequence[_T]
+
+
+@overload
+def convert_to_openai_messages(
+ messages: _SingleMessage,
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> dict: ...
+
+
+@overload
+def convert_to_openai_messages(
+ messages: _MultipleMessages,
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> list[dict]: ...
+
+
+def convert_to_openai_messages(
+ messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> dict | list[dict]:
+ """Convert LangChain messages into OpenAI message dicts.
+
+ Args:
+ messages: Message-like object or iterable of objects whose contents are
+ in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats.
+ text_format: How to format string or text block contents:
+ - `'string'`:
+ If a message has a string content, this is left as a string. If
+ a message has content blocks that are all of type `'text'`, these
+ are joined with a newline to make a single string. If a message has
+ content blocks and at least one isn't of type `'text'`, then
+ all blocks are left as dicts.
+ - `'block'`:
+ If a message has a string content, this is turned into a list
+ with a single content block of type `'text'`. If a message has
+ content blocks these are left as is.
+ include_id: Whether to include message IDs in the openai messages, if they
+ are present in the source messages.
+ pass_through_unknown_blocks: Whether to include content blocks with unknown
+ formats in the output. If `False`, an error is raised if an unknown
+ content block is encountered.
+
+ Raises:
+ ValueError: if an unrecognized `text_format` is specified, or if a message
+ content block is missing expected keys.
+
+ Returns:
+ The return type depends on the input type:
+
+ - dict:
+ If a single message-like object is passed in, a single OpenAI message
+ dict is returned.
+ - list[dict]:
+ If a sequence of message-like objects are passed in, a list of OpenAI
+ message dicts is returned.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ convert_to_openai_messages,
+ AIMessage,
+ SystemMessage,
+ ToolMessage,
+ )
+
+ messages = [
+ SystemMessage([{"type": "text", "text": "foo"}]),
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what's in this"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,'/9j/4AAQSk'"},
+ },
+ ],
+ },
+ AIMessage(
+ "",
+ tool_calls=[
+ {
+ "name": "analyze",
+ "args": {"baz": "buz"},
+ "id": "1",
+ "type": "tool_call",
+ }
+ ],
+ ),
+ ToolMessage("foobar", tool_call_id="1", name="bar"),
+ {"role": "assistant", "content": "that's nice"},
+ ]
+ oai_messages = convert_to_openai_messages(messages)
+ # -> [
+ # {'role': 'system', 'content': 'foo'},
+ # {'role': 'user', 'content': [{'type': 'text', 'text': 'what's in this'}, {'type': 'image_url', 'image_url': {'url': "data:image/png;base64,'/9j/4AAQSk'"}}]},
+ # {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '1','function': {'name': 'analyze', 'arguments': '{"baz": "buz"}'}}], 'content': ''},
+ # {'role': 'tool', 'name': 'bar', 'content': 'foobar'},
+ # {'role': 'assistant', 'content': 'that's nice'}
+ # ]
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.11"
+
+ """ # noqa: E501
+ if text_format not in {"string", "block"}:
+ err = f"Unrecognized {text_format=}, expected one of 'string' or 'block'."
+ raise ValueError(err)
+
+ oai_messages: list[dict] = []
+
+ if is_single := isinstance(messages, (BaseMessage, dict, str)):
+ messages = [messages]
+
+ messages = convert_to_messages(messages)
+
+ for i, message in enumerate(messages):
+ oai_msg: dict = {"role": _get_message_openai_role(message)}
+ tool_messages: list = []
+ content: str | list[dict]
+
+ if message.name:
+ oai_msg["name"] = message.name
+ if isinstance(message, AIMessage) and message.tool_calls:
+ oai_msg["tool_calls"] = _convert_to_openai_tool_calls(message.tool_calls)
+ if message.additional_kwargs.get("refusal"):
+ oai_msg["refusal"] = message.additional_kwargs["refusal"]
+ if isinstance(message, ToolMessage):
+ oai_msg["tool_call_id"] = message.tool_call_id
+ if include_id and message.id:
+ oai_msg["id"] = message.id
+
+ if not message.content:
+ content = "" if text_format == "string" else []
+ elif isinstance(message.content, str):
+ if text_format == "string":
+ content = message.content
+ else:
+ content = [{"type": "text", "text": message.content}]
+ elif text_format == "string" and all(
+ isinstance(block, str) or block.get("type") == "text"
+ for block in message.content
+ ):
+ content = "\n".join(
+ block if isinstance(block, str) else block["text"]
+ for block in message.content
+ )
+ else:
+ content = []
+ for j, block in enumerate(message.content):
+ # OpenAI format
+ if isinstance(block, str):
+ content.append({"type": "text", "text": block})
+ elif block.get("type") == "text":
+ if missing := [k for k in ("text",) if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'text' "
+ f"but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append({"type": block["type"], "text": block["text"]})
+ elif block.get("type") == "image_url":
+ if missing := [k for k in ("image_url",) if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image_url' "
+ f"but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": block["image_url"],
+ }
+ )
+ # Standard multi-modal content block
+ elif is_data_content_block(block):
+ formatted_block = convert_to_openai_data_block(block)
+ if (
+ formatted_block.get("type") == "file"
+ and "file" in formatted_block
+ and "filename" not in formatted_block["file"]
+ ):
+ logger.info("Generating a fallback filename.")
+ formatted_block["file"]["filename"] = "LC_AUTOGENERATED"
+ content.append(formatted_block)
+ # Anthropic and Bedrock converse format
+ elif (block.get("type") == "image") or "image" in block:
+ # Anthropic
+ if source := block.get("source"):
+ if missing := [
+ k for k in ("media_type", "type", "data") if k not in source
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image' "
+ f"but 'source' is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (
+ f"data:{source['media_type']};"
+ f"{source['type']},{source['data']}"
+ )
+ },
+ }
+ )
+ # Bedrock converse
+ elif image := block.get("image"):
+ if missing := [
+ k for k in ("source", "format") if k not in image
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has key 'image', "
+ f"but 'image' is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ b64_image = _bytes_to_b64_str(image["source"]["bytes"])
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (
+ f"data:image/{image['format']};base64,{b64_image}"
+ )
+ },
+ }
+ )
+ else:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image' "
+ f"but does not have a 'source' or 'image' key. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ # OpenAI file format
+ elif (
+ block.get("type") == "file"
+ and isinstance(block.get("file"), dict)
+ and isinstance(block.get("file", {}).get("file_data"), str)
+ ):
+ if block.get("file", {}).get("filename") is None:
+ logger.info("Generating a fallback filename.")
+ block["file"]["filename"] = "LC_AUTOGENERATED"
+ content.append(block)
+ # OpenAI audio format
+ elif (
+ block.get("type") == "input_audio"
+ and isinstance(block.get("input_audio"), dict)
+ and isinstance(block.get("input_audio", {}).get("data"), str)
+ and isinstance(block.get("input_audio", {}).get("format"), str)
+ ):
+ content.append(block)
+ elif block.get("type") == "tool_use":
+ if missing := [
+ k for k in ("id", "name", "input") if k not in block
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_use', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if not any(
+ tool_call["id"] == block["id"]
+ for tool_call in cast("AIMessage", message).tool_calls
+ ):
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
+ oai_msg["tool_calls"].append(
+ {
+ "type": "function",
+ "id": block["id"],
+ "function": {
+ "name": block["name"],
+ "arguments": json.dumps(
+ block["input"], ensure_ascii=False
+ ),
+ },
+ }
+ )
+ elif block.get("type") == "function_call": # OpenAI Responses
+ if not any(
+ tool_call["id"] == block.get("call_id")
+ for tool_call in cast("AIMessage", message).tool_calls
+ ):
+ if missing := [
+ k
+ for k in ("call_id", "name", "arguments")
+ if k not in block
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_use', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
+ oai_msg["tool_calls"].append(
+ {
+ "type": "function",
+ "id": block.get("call_id"),
+ "function": {
+ "name": block.get("name"),
+ "arguments": block.get("arguments"),
+ },
+ }
+ )
+ if pass_through_unknown_blocks:
+ content.append(block)
+ elif block.get("type") == "tool_result":
+ if missing := [
+ k for k in ("content", "tool_use_id") if k not in block
+ ]:
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_result', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ tool_message = ToolMessage(
+ block["content"],
+ tool_call_id=block["tool_use_id"],
+ status="error" if block.get("is_error") else "success",
+ )
+ # Recurse to make sure tool message contents are OpenAI format.
+ tool_messages.extend(
+ convert_to_openai_messages(
+ [tool_message], text_format=text_format
+ )
+ )
+ elif (block.get("type") == "json") or "json" in block:
+ if "json" not in block:
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'json' "
+ f"but does not have a 'json' key. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ content.append(
+ {
+ "type": "text",
+ "text": json.dumps(block["json"]),
+ }
+ )
+ elif (block.get("type") == "guard_content") or "guard_content" in block:
+ if (
+ "guard_content" not in block
+ or "text" not in block["guard_content"]
+ ):
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'guard_content' but does not have a "
+ f"messages[{i}].content[{j}]['guard_content']['text'] "
+ f"key. Full content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ text = block["guard_content"]["text"]
+ if isinstance(text, dict):
+ text = text["text"]
+ content.append({"type": "text", "text": text})
+ # VertexAI format
+ elif block.get("type") == "media":
+ if missing := [k for k in ("mime_type", "data") if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'media' but does not have key(s) {missing}. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if "image" not in block["mime_type"]:
+ err = (
+ f"OpenAI messages can only support text and image data."
+ f" Received content block with media of type:"
+ f" {block['mime_type']}"
+ )
+ raise ValueError(err)
+ b64_image = _bytes_to_b64_str(block["data"])
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (f"data:{block['mime_type']};base64,{b64_image}")
+ },
+ }
+ )
+ elif (
+ block.get("type") in {"thinking", "reasoning"}
+ or pass_through_unknown_blocks
+ ):
+ content.append(block)
+ else:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] does not match OpenAI, "
+ f"Anthropic, Bedrock Converse, or VertexAI format. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if text_format == "string" and not any(
+ block["type"] != "text" for block in content
+ ):
+ content = "\n".join(block["text"] for block in content)
+ oai_msg["content"] = content
+ if message.content and not oai_msg["content"] and tool_messages:
+ oai_messages.extend(tool_messages)
+ else:
+ oai_messages.extend([oai_msg, *tool_messages])
+
+ if is_single:
+ return oai_messages[0]
+ return oai_messages
+
+
+def _first_max_tokens(
+ messages: Sequence[BaseMessage],
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int],
+ text_splitter: Callable[[str], list[str]],
+ partial_strategy: Literal["first", "last"] | None = None,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+) -> list[BaseMessage]:
+ messages = list(messages)
+ if not messages:
+ return messages
+
+ # Check if all messages already fit within token limit
+ if token_counter(messages) <= max_tokens:
+ # When all messages fit, only apply end_on filtering if needed
+ if end_on:
+ for _ in range(len(messages)):
+ if not _is_message_type(messages[-1], end_on):
+ messages.pop()
+ else:
+ break
+ return messages
+
+ # Use binary search to find the maximum number of messages within token limit
+ left, right = 0, len(messages)
+ max_iterations = len(messages).bit_length()
+ for _ in range(max_iterations):
+ if left >= right:
+ break
+ mid = (left + right + 1) // 2
+ if token_counter(messages[:mid]) <= max_tokens:
+ left = mid
+ idx = mid
+ else:
+ right = mid - 1
+
+ # idx now contains the maximum number of complete messages we can include
+ idx = left
+
+ if partial_strategy and idx < len(messages):
+ included_partial = False
+ copied = False
+ if isinstance(messages[idx].content, list):
+ excluded = messages[idx].model_copy(deep=True)
+ copied = True
+ num_block = len(excluded.content)
+ if partial_strategy == "last":
+ excluded.content = list(reversed(excluded.content))
+ for _ in range(1, num_block):
+ excluded.content = excluded.content[:-1]
+ if token_counter([*messages[:idx], excluded]) <= max_tokens:
+ messages = [*messages[:idx], excluded]
+ idx += 1
+ included_partial = True
+ break
+ if included_partial and partial_strategy == "last":
+ excluded.content = list(reversed(excluded.content))
+ if not included_partial:
+ if not copied:
+ excluded = messages[idx].model_copy(deep=True)
+ copied = True
+
+ # Extract text content efficiently
+ text = None
+ if isinstance(excluded.content, str):
+ text = excluded.content
+ elif isinstance(excluded.content, list) and excluded.content:
+ for block in excluded.content:
+ if isinstance(block, str):
+ text = block
+ break
+ if isinstance(block, dict) and block.get("type") == "text":
+ text = block.get("text")
+ break
+
+ if text:
+ if not copied:
+ excluded = excluded.model_copy(deep=True)
+
+ split_texts = text_splitter(text)
+ base_message_count = token_counter(messages[:idx])
+ if partial_strategy == "last":
+ split_texts = list(reversed(split_texts))
+
+ # Binary search for the maximum number of splits we can include
+ left, right = 0, len(split_texts)
+ max_iterations = len(split_texts).bit_length()
+ for _ in range(max_iterations):
+ if left >= right:
+ break
+ mid = (left + right + 1) // 2
+ excluded.content = "".join(split_texts[:mid])
+ if base_message_count + token_counter([excluded]) <= max_tokens:
+ left = mid
+ else:
+ right = mid - 1
+
+ if left > 0:
+ content_splits = split_texts[:left]
+ if partial_strategy == "last":
+ content_splits = list(reversed(content_splits))
+ excluded.content = "".join(content_splits)
+ messages = [*messages[:idx], excluded]
+ idx += 1
+
+ if end_on:
+ for _ in range(idx):
+ if idx > 0 and not _is_message_type(messages[idx - 1], end_on):
+ idx -= 1
+ else:
+ break
+
+ return messages[:idx]
+
+
+def _last_max_tokens(
+ messages: Sequence[BaseMessage],
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int],
+ text_splitter: Callable[[str], list[str]],
+ allow_partial: bool = False,
+ include_system: bool = False,
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+) -> list[BaseMessage]:
+ messages = list(messages)
+ if len(messages) == 0:
+ return []
+
+ # Filter out messages after end_on type
+ if end_on:
+ for _ in range(len(messages)):
+ if not _is_message_type(messages[-1], end_on):
+ messages.pop()
+ else:
+ break
+
+ # Handle system message preservation
+ system_message = None
+ if include_system and len(messages) > 0 and isinstance(messages[0], SystemMessage):
+ system_message = messages[0]
+ messages = messages[1:]
+
+ # Reverse messages to use _first_max_tokens with reversed logic
+ reversed_messages = messages[::-1]
+
+ # Calculate remaining tokens after accounting for system message if present
+ remaining_tokens = max_tokens
+ if system_message:
+ system_tokens = token_counter([system_message])
+ remaining_tokens = max(0, max_tokens - system_tokens)
+
+ reversed_result = _first_max_tokens(
+ reversed_messages,
+ max_tokens=remaining_tokens,
+ token_counter=token_counter,
+ text_splitter=text_splitter,
+ partial_strategy="last" if allow_partial else None,
+ end_on=start_on,
+ )
+
+ # Re-reverse the messages and add back the system message if needed
+ result = reversed_result[::-1]
+ if system_message:
+ result = [system_message, *result]
+
+ return result
+
+
+_MSG_CHUNK_MAP: dict[type[BaseMessage], type[BaseMessageChunk]] = {
+ HumanMessage: HumanMessageChunk,
+ AIMessage: AIMessageChunk,
+ SystemMessage: SystemMessageChunk,
+ ToolMessage: ToolMessageChunk,
+ FunctionMessage: FunctionMessageChunk,
+ ChatMessage: ChatMessageChunk,
+}
+_CHUNK_MSG_MAP = {v: k for k, v in _MSG_CHUNK_MAP.items()}
+
+
+def _msg_to_chunk(message: BaseMessage) -> BaseMessageChunk:
+ if message.__class__ in _MSG_CHUNK_MAP:
+ return _MSG_CHUNK_MAP[message.__class__](**message.model_dump(exclude={"type"}))
+
+ for msg_cls, chunk_cls in _MSG_CHUNK_MAP.items():
+ if isinstance(message, msg_cls):
+ return chunk_cls(**message.model_dump(exclude={"type"}))
+
+ msg = (
+ f"Unrecognized message class {message.__class__}. Supported classes are "
+ f"{list(_MSG_CHUNK_MAP.keys())}"
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+
+
+def _chunk_to_msg(chunk: BaseMessageChunk) -> BaseMessage:
+ if chunk.__class__ in _CHUNK_MSG_MAP:
+ return _CHUNK_MSG_MAP[chunk.__class__](
+ **chunk.model_dump(exclude={"type", "tool_call_chunks", "chunk_position"})
+ )
+ for chunk_cls, msg_cls in _CHUNK_MSG_MAP.items():
+ if isinstance(chunk, chunk_cls):
+ return msg_cls(
+ **chunk.model_dump(
+ exclude={"type", "tool_call_chunks", "chunk_position"}
+ )
+ )
+
+ msg = (
+ f"Unrecognized message chunk class {chunk.__class__}. Supported classes are "
+ f"{list(_CHUNK_MSG_MAP.keys())}"
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+
+
+def _default_text_splitter(text: str) -> list[str]:
+ splits = text.split("\n")
+ return [s + "\n" for s in splits[:-1]] + splits[-1:]
+
+
+def _is_message_type(
+ message: BaseMessage,
+ type_: str | type[BaseMessage] | Sequence[str | type[BaseMessage]],
+) -> bool:
+ types = [type_] if isinstance(type_, (str, type)) else type_
+ types_str = [t for t in types if isinstance(t, str)]
+ types_types = tuple(t for t in types if isinstance(t, type))
+
+ return message.type in types_str or isinstance(message, types_types)
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def _get_message_openai_role(message: BaseMessage) -> str:
+ if isinstance(message, AIMessage):
+ return "assistant"
+ if isinstance(message, HumanMessage):
+ return "user"
+ if isinstance(message, ToolMessage):
+ return "tool"
+ if isinstance(message, SystemMessage):
+ role = message.additional_kwargs.get("__openai_role__", "system")
+ if not isinstance(role, str):
+ msg = f"Expected '__openai_role__' to be a str, got {type(role).__name__}"
+ raise TypeError(msg)
+ return role
+ if isinstance(message, FunctionMessage):
+ return "function"
+ if isinstance(message, ChatMessage):
+ return message.role
+ msg = f"Unknown BaseMessage type {message.__class__}."
+ raise ValueError(msg)
+
+
+def _convert_to_openai_tool_calls(tool_calls: list[ToolCall]) -> list[dict]:
+ return [
+ {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ },
+ }
+ for tool_call in tool_calls
+ ]
+
+
+def count_tokens_approximately(
+ messages: Iterable[MessageLikeRepresentation],
+ *,
+ chars_per_token: float = 4.0,
+ extra_tokens_per_message: float = 3.0,
+ count_name: bool = True,
+ tokens_per_image: int = 85,
+ use_usage_metadata_scaling: bool = False,
+ tools: list[BaseTool | dict[str, Any]] | None = None,
+) -> int:
+ """Approximate the total number of tokens in messages.
+
+ The token count includes stringified message content, role, and (optionally) name.
+
+ - For AI messages, the token count also includes stringified tool calls.
+ - For tool messages, the token count also includes the tool call ID.
+ - For multimodal messages with images, applies a fixed token penalty per image
+ instead of counting base64-encoded characters.
+ - If tools are provided, the token count also includes stringified tool schemas.
+
+ Args:
+ messages: List of messages to count tokens for.
+ chars_per_token: Number of characters per token to use for the approximation.
+ One token corresponds to ~4 chars for common English text.
+ You can also specify `float` values for more fine-grained control.
+ [See more here](https://platform.openai.com/tokenizer).
+ extra_tokens_per_message: Number of extra tokens to add per message, e.g.
+ special tokens, including beginning/end of message.
+ You can also specify `float` values for more fine-grained control.
+ [See more here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb).
+ count_name: Whether to include message names in the count.
+ tokens_per_image: Fixed token cost per image (default: 85, aligned with
+ OpenAI's low-resolution image token cost).
+ use_usage_metadata_scaling: If True, and all AI messages have consistent
+ `response_metadata['model_provider']`, scale the approximate token count
+ using the **most recent** AI message that has
+ `usage_metadata['total_tokens']`. The scaling factor is:
+ `AI_total_tokens / approx_tokens_up_to_that_AI_message`
+ tools: List of tools to include in the token count. Each tool can be either
+ a `BaseTool` instance or a dict representing a tool schema. `BaseTool`
+ instances are converted to OpenAI tool format before counting.
+
+ Returns:
+ Approximate number of tokens in the messages (and tools, if provided).
+
+ Note:
+ This is a simple approximation that may not match the exact token count used by
+ specific models. For accurate counts, use model-specific tokenizers.
+
+ For multimodal messages containing images, a fixed token penalty is applied
+ per image instead of counting base64-encoded characters, which provides a
+ more realistic approximation.
+
+ !!! version-added "Added in `langchain-core` 0.3.46"
+ """
+ converted_messages = convert_to_messages(messages)
+
+ token_count = 0.0
+
+ ai_model_provider: str | None = None
+ invalid_model_provider = False
+ last_ai_total_tokens: int | None = None
+ approx_at_last_ai: float | None = None
+
+ # Count tokens for tools if provided
+ if tools:
+ tools_chars = 0
+ for tool in tools:
+ tool_dict = tool if isinstance(tool, dict) else convert_to_openai_tool(tool)
+ tools_chars += len(json.dumps(tool_dict))
+ token_count += math.ceil(tools_chars / chars_per_token)
+
+ for message in converted_messages:
+ message_chars = 0
+
+ if isinstance(message.content, str):
+ message_chars += len(message.content)
+ # Handle multimodal content (list of content blocks)
+ elif isinstance(message.content, list):
+ for block in message.content:
+ if isinstance(block, str):
+ # String block
+ message_chars += len(block)
+ elif isinstance(block, dict):
+ block_type = block.get("type", "")
+
+ # Apply fixed penalty for image blocks
+ if block_type in {"image", "image_url"}:
+ token_count += tokens_per_image
+ # Count text blocks normally
+ elif block_type == "text":
+ text = block.get("text", "")
+ message_chars += len(text)
+ # Conservative estimate for unknown block types
+ else:
+ message_chars += len(repr(block))
+ else:
+ # Fallback for unexpected block types
+ message_chars += len(repr(block))
+ else:
+ # Fallback for other content types
+ content = repr(message.content)
+ message_chars += len(content)
+
+ if (
+ isinstance(message, AIMessage)
+ # exclude Anthropic format as tool calls are already included in the content
+ and not isinstance(message.content, list)
+ and message.tool_calls
+ ):
+ tool_calls_content = repr(message.tool_calls)
+ message_chars += len(tool_calls_content)
+
+ if isinstance(message, ToolMessage):
+ message_chars += len(message.tool_call_id)
+
+ role = _get_message_openai_role(message)
+ message_chars += len(role)
+
+ if message.name and count_name:
+ message_chars += len(message.name)
+
+ # NOTE: we're rounding up per message to ensure that
+ # individual message token counts add up to the total count
+ # for a list of messages
+ token_count += math.ceil(message_chars / chars_per_token)
+
+ # add extra tokens per message
+ token_count += extra_tokens_per_message
+
+ if use_usage_metadata_scaling and isinstance(message, AIMessage):
+ model_provider = message.response_metadata.get("model_provider")
+ if ai_model_provider is None:
+ ai_model_provider = model_provider
+ elif model_provider != ai_model_provider:
+ invalid_model_provider = True
+
+ if message.usage_metadata and isinstance(
+ (total_tokens := message.usage_metadata.get("total_tokens")), int
+ ):
+ last_ai_total_tokens = total_tokens
+ approx_at_last_ai = token_count
+
+ if (
+ use_usage_metadata_scaling
+ and len(converted_messages) > 1
+ and not invalid_model_provider
+ and ai_model_provider is not None
+ and last_ai_total_tokens is not None
+ and approx_at_last_ai
+ and approx_at_last_ai > 0
+ ):
+ scale_factor = last_ai_total_tokens / approx_at_last_ai
+ token_count *= min(1.25, max(1.0, scale_factor))
+
+ # round up once more time in case extra_tokens_per_message is a float
+ return math.ceil(token_count)
+
+
+# Mapping from string shortcuts to token counter functions
+def _approximate_token_counter(messages: Sequence[BaseMessage]) -> int:
+ """Wrapper for `count_tokens_approximately` that matches expected signature."""
+ return count_tokens_approximately(messages)
+
+
+_TOKEN_COUNTER_SHORTCUTS = {
+ "approximate": _approximate_token_counter,
+}
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bd9c0ca893bcb0985b0d880d31d0df394f9f3f2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__init__.py
@@ -0,0 +1,101 @@
+"""`OutputParser` classes parse the output of an LLM call into structured data.
+
+!!! tip "Structured output"
+
+ Output parsers emerged as an early solution to the challenge of obtaining structured
+ output from LLMs.
+
+ Today, most LLMs support [structured output](https://docs.langchain.com/oss/python/langchain/models#structured-outputs)
+ natively. In such cases, using output parsers may be unnecessary, and you should
+ leverage the model's built-in capabilities for structured output. Refer to the
+ [documentation of your chosen model](https://docs.langchain.com/oss/python/integrations/providers/overview)
+ for guidance on how to achieve structured output directly.
+
+ Output parsers remain valuable when working with models that do not support
+ structured output natively, or when you require additional processing or validation
+ of the model's output beyond its inherent capabilities.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.output_parsers.base import (
+ BaseGenerationOutputParser,
+ BaseLLMOutputParser,
+ BaseOutputParser,
+ )
+ from langchain_core.output_parsers.json import (
+ JsonOutputParser,
+ SimpleJsonOutputParser,
+ )
+ from langchain_core.output_parsers.list import (
+ CommaSeparatedListOutputParser,
+ ListOutputParser,
+ MarkdownListOutputParser,
+ NumberedListOutputParser,
+ )
+ from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ JsonOutputToolsParser,
+ PydanticToolsParser,
+ )
+ from langchain_core.output_parsers.pydantic import PydanticOutputParser
+ from langchain_core.output_parsers.string import StrOutputParser
+ from langchain_core.output_parsers.transform import (
+ BaseCumulativeTransformOutputParser,
+ BaseTransformOutputParser,
+ )
+ from langchain_core.output_parsers.xml import XMLOutputParser
+
+__all__ = [
+ "BaseCumulativeTransformOutputParser",
+ "BaseGenerationOutputParser",
+ "BaseLLMOutputParser",
+ "BaseOutputParser",
+ "BaseTransformOutputParser",
+ "CommaSeparatedListOutputParser",
+ "JsonOutputKeyToolsParser",
+ "JsonOutputParser",
+ "JsonOutputToolsParser",
+ "ListOutputParser",
+ "MarkdownListOutputParser",
+ "NumberedListOutputParser",
+ "PydanticOutputParser",
+ "PydanticToolsParser",
+ "SimpleJsonOutputParser",
+ "StrOutputParser",
+ "XMLOutputParser",
+]
+
+_dynamic_imports = {
+ "BaseLLMOutputParser": "base",
+ "BaseGenerationOutputParser": "base",
+ "BaseOutputParser": "base",
+ "JsonOutputParser": "json",
+ "SimpleJsonOutputParser": "json",
+ "ListOutputParser": "list",
+ "CommaSeparatedListOutputParser": "list",
+ "MarkdownListOutputParser": "list",
+ "NumberedListOutputParser": "list",
+ "JsonOutputKeyToolsParser": "openai_tools",
+ "JsonOutputToolsParser": "openai_tools",
+ "PydanticToolsParser": "openai_tools",
+ "PydanticOutputParser": "pydantic",
+ "StrOutputParser": "string",
+ "BaseTransformOutputParser": "transform",
+ "BaseCumulativeTransformOutputParser": "transform",
+ "XMLOutputParser": "xml",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return __all__
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..398235608022a3fbd829186f00a0898ee42ced54
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba3c7f721dd063554506934bf9f83b6911c79f97
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..429a9470783e5aceb928f0bce2c9e3510580ce6e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b7e39e7259ecbc386ec9c56d4460dfc9dd79b02
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24bcb0c2e0f4e515a1eb6b78e1ac2dd3e6cba65e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af13fd02b0d3cf0356dc63dbe1261740b429f0b9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45d32bdf4dcb1cf268c5f6995ea0fff9dbd78956
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92f277a2a854946634c240a7636b125ad98db2a1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a0c901dc3e000dfa2889da8f5bf3f9ffe2d3cf3
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab5f1c0de4ff7ab46da942469b199f6cb6783544
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..717107af7ea91e407881994a042971dad2cef539
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/base.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..861e8ba77774433b0cbd1265b7d75069e30bdf76
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/base.py
@@ -0,0 +1,348 @@
+"""Base parser for language model outputs."""
+
+from __future__ import annotations
+
+import contextlib
+from abc import ABC, abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import override
+
+from langchain_core.language_models import LanguageModelOutput
+from langchain_core.messages import AnyMessage, BaseMessage
+from langchain_core.outputs import ChatGeneration, Generation
+from langchain_core.runnables import Runnable, RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from langchain_core.prompt_values import PromptValue
+
+T = TypeVar("T")
+OutputParserLike = Runnable[LanguageModelOutput, T]
+
+
+class BaseLLMOutputParser(ABC, Generic[T]):
+ """Abstract base class for parsing the outputs of a model."""
+
+ @abstractmethod
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+
+ async def aparse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The Generations are assumed to be different candidate outputs for a
+ single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse_result, result, partial=partial)
+
+
+class BaseGenerationOutputParser(
+ BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
+):
+ """Base class to parse the output of an LLM call."""
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """Return the input type for the parser."""
+ return str | AnyMessage
+
+ @property
+ @override
+ def OutputType(self) -> type[T]:
+ """Return the output type for the parser."""
+ # even though mypy complains this isn't valid,
+ # it is good enough for pydantic to build the schema from
+ return cast("type[T]", T) # type: ignore[misc]
+
+ @override
+ def invoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return self._call_with_config(
+ lambda inner_input: self.parse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return self._call_with_config(
+ lambda inner_input: self.parse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+
+class BaseOutputParser(
+ BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
+):
+ """Base class to parse the output of an LLM call.
+
+ Output parsers help structure language model responses.
+
+ Example:
+ ```python
+ # Implement a simple boolean output parser
+
+
+ class BooleanOutputParser(BaseOutputParser[bool]):
+ true_val: str = "YES"
+ false_val: str = "NO"
+
+ def parse(self, text: str) -> bool:
+ cleaned_text = text.strip().upper()
+ if cleaned_text not in (
+ self.true_val.upper(),
+ self.false_val.upper(),
+ ):
+ raise OutputParserException(
+ f"BooleanOutputParser expected output value to either be "
+ f"{self.true_val} or {self.false_val} (case-insensitive). "
+ f"Received {cleaned_text}."
+ )
+ return cleaned_text == self.true_val.upper()
+
+ @property
+ def _type(self) -> str:
+ return "boolean_output_parser"
+ ```
+ """
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """Return the input type for the parser."""
+ return str | AnyMessage
+
+ @property
+ @override
+ def OutputType(self) -> type[T]:
+ """Return the output type for the parser.
+
+ This property is inferred from the first type argument of the class.
+
+ Raises:
+ TypeError: If the class doesn't have an inferable `OutputType`.
+ """
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if "args" in metadata and len(metadata["args"]) > 0:
+ return cast("type[T]", metadata["args"][0])
+
+ msg = (
+ f"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. "
+ "Override the OutputType property to specify the output type."
+ )
+ raise TypeError(msg)
+
+ @override
+ def invoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return self._call_with_config(
+ lambda inner_input: self.parse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return self._call_with_config(
+ lambda inner_input: self.parse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ The return value is parsed from only the first `Generation` in the result, which
+ is assumed to be the highest-likelihood `Generation`.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return self.parse(result[0].text)
+
+ @abstractmethod
+ def parse(self, text: str) -> T:
+ """Parse a single string model output into some structure.
+
+ Args:
+ text: String output of a language model.
+
+ Returns:
+ Structured output.
+ """
+
+ async def aparse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ The return value is parsed from only the first `Generation` in the result, which
+ is assumed to be the highest-likelihood `Generation`.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse_result, result, partial=partial)
+
+ async def aparse(self, text: str) -> T:
+ """Async parse a single string model output into some structure.
+
+ Args:
+ text: String output of a language model.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse, text)
+
+ # TODO: rename 'completion' -> 'text'.
+ def parse_with_prompt(
+ self,
+ completion: str,
+ prompt: PromptValue, # noqa: ARG002
+ ) -> Any:
+ """Parse the output of an LLM call with the input prompt for context.
+
+ The prompt is largely provided in the event the `OutputParser` wants to retry or
+ fix the output in some way, and needs information from the prompt to do so.
+
+ Args:
+ completion: String output of a language model.
+ prompt: Input `PromptValue`.
+
+ Returns:
+ Structured output.
+ """
+ return self.parse(completion)
+
+ def get_format_instructions(self) -> str:
+ """Instructions on how the LLM output should be formatted."""
+ raise NotImplementedError
+
+ @property
+ def _type(self) -> str:
+ """Return the output parser type for serialization."""
+ msg = (
+ f"_type property is not implemented in class {self.__class__.__name__}."
+ " This is required for serialization."
+ )
+ raise NotImplementedError(msg)
+
+ def dict(self, **kwargs: Any) -> dict:
+ """Return dictionary representation of output parser."""
+ output_parser_dict = super().model_dump(**kwargs)
+ with contextlib.suppress(NotImplementedError):
+ output_parser_dict["_type"] = self._type
+ return output_parser_dict
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/format_instructions.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/format_instructions.py
new file mode 100644
index 0000000000000000000000000000000000000000..49898917f45c7e779ac005717acd0327822db447
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/format_instructions.py
@@ -0,0 +1,16 @@
+"""Format instructions."""
+
+JSON_FORMAT_INSTRUCTIONS = """STRICT OUTPUT FORMAT:
+- Return only the JSON value that conforms to the schema. Do not include any additional text, explanations, headings, or separators.
+- Do not wrap the JSON in Markdown or code fences (no ``` or ```json).
+- Do not prepend or append any text (e.g., do not write "Here is the JSON:").
+- The response must be a single top-level JSON value exactly as required by the schema (object/array/etc.), with no trailing commas or comments.
+
+The output should be formatted as a JSON instance that conforms to the JSON schema below.
+
+As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
+
+Here is the output schema (shown in a code block for readability only — do not include any backticks or Markdown in your output):
+```
+{schema}
+```""" # noqa: E501
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/json.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..829e042c7c9fefed89dac102eb66c3bd9094aef3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/json.py
@@ -0,0 +1,139 @@
+"""Parser for JSON output."""
+
+from __future__ import annotations
+
+import json
+from json import JSONDecodeError
+from typing import Annotated, Any, TypeVar
+
+import jsonpatch # type: ignore[import-untyped]
+import pydantic
+from pydantic import SkipValidation
+from pydantic.v1 import BaseModel
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers.format_instructions import JSON_FORMAT_INSTRUCTIONS
+from langchain_core.output_parsers.transform import BaseCumulativeTransformOutputParser
+from langchain_core.outputs import Generation
+from langchain_core.utils.json import (
+ parse_and_check_json_markdown,
+ parse_json_markdown,
+ parse_partial_json,
+)
+
+# Union type needs to be last assignment to PydanticBaseModel to make mypy happy.
+PydanticBaseModel = BaseModel | pydantic.BaseModel
+
+TBaseModel = TypeVar("TBaseModel", bound=PydanticBaseModel)
+
+
+class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse the output of an LLM call to a JSON object.
+
+ Probably the most reliable output parser for getting structured data that does *not*
+ use function calling.
+
+ When used in streaming mode, it will yield partial JSON objects containing all the
+ keys that have been returned so far.
+
+ In streaming, if `diff` is set to `True`, yields `JSONPatch` operations describing
+ the difference between the previous and the current object.
+ """
+
+ pydantic_object: Annotated[type[TBaseModel] | None, SkipValidation()] = None # type: ignore[valid-type]
+ """The Pydantic object to use for validation.
+
+ If `None`, no validation is performed.
+ """
+
+ @override
+ def _diff(self, prev: Any | None, next: Any) -> Any:
+ return jsonpatch.make_patch(prev, next).patch
+
+ @staticmethod
+ def _get_schema(pydantic_object: type[TBaseModel]) -> dict[str, Any]:
+ if issubclass(pydantic_object, pydantic.BaseModel):
+ return pydantic_object.model_json_schema()
+ return pydantic_object.schema()
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ text = result[0].text
+ text = text.strip()
+ if partial:
+ try:
+ return parse_json_markdown(text)
+ except JSONDecodeError:
+ return None
+ else:
+ try:
+ return parse_json_markdown(text)
+ except JSONDecodeError as e:
+ msg = f"Invalid json output: {text}"
+ raise OutputParserException(msg, llm_output=text) from e
+
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a JSON object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed JSON object.
+ """
+ return self.parse_result([Generation(text=text)])
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the JSON output.
+
+ Returns:
+ The format instructions for the JSON output.
+ """
+ if self.pydantic_object is None:
+ return "Return a JSON object."
+ # Copy schema to avoid altering original Pydantic schema.
+ schema = dict(self._get_schema(self.pydantic_object).items())
+
+ # Remove extraneous fields.
+ reduced_schema = schema
+ if "title" in reduced_schema:
+ del reduced_schema["title"]
+ if "type" in reduced_schema:
+ del reduced_schema["type"]
+ # Ensure json in context is well-formed with double quotes.
+ schema_str = json.dumps(reduced_schema, ensure_ascii=False)
+ return JSON_FORMAT_INSTRUCTIONS.format(schema=schema_str)
+
+ @property
+ def _type(self) -> str:
+ return "simple_json_output_parser"
+
+
+# For backwards compatibility
+SimpleJsonOutputParser = JsonOutputParser
+
+
+__all__ = [
+ "JsonOutputParser",
+ "SimpleJsonOutputParser", # For backwards compatibility
+ "parse_and_check_json_markdown", # For backwards compatibility
+ "parse_partial_json", # For backwards compatibility
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/list.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/list.py
new file mode 100644
index 0000000000000000000000000000000000000000..834c9ec153a0ddb8b742256e21eca25eaae45748
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/list.py
@@ -0,0 +1,249 @@
+"""Parsers for list output."""
+
+from __future__ import annotations
+
+import csv
+import re
+from abc import abstractmethod
+from collections import deque
+from io import StringIO
+from typing import TYPE_CHECKING, TypeVar
+
+from typing_extensions import override
+
+from langchain_core.messages import BaseMessage
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+T = TypeVar("T")
+
+
+def droplastn(
+ iter: Iterator[T], # noqa: A002
+ n: int,
+) -> Iterator[T]:
+ """Drop the last `n` elements of an iterator.
+
+ Args:
+ iter: The iterator to drop elements from.
+ n: The number of elements to drop.
+
+ Yields:
+ The elements of the iterator, except the last n elements.
+ """
+ buffer: deque[T] = deque()
+ for item in iter:
+ buffer.append(item)
+ if len(buffer) > n:
+ yield buffer.popleft()
+
+
+class ListOutputParser(BaseTransformOutputParser[list[str]]):
+ """Parse the output of a model to a list."""
+
+ @property
+ def _type(self) -> str:
+ return "list"
+
+ @abstractmethod
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Yields:
+ A match object for each part of the output.
+ """
+ raise NotImplementedError
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[list[str]]:
+ buffer = ""
+ for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ # Extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ continue
+ buffer += chunk_content
+ else:
+ # Add current chunk to buffer
+ buffer += chunk
+ # Parse buffer into a list of parts
+ try:
+ done_idx = 0
+ # Yield only complete parts
+ for m in droplastn(self.parse_iter(buffer), 1):
+ done_idx = m.end()
+ yield [m.group(1)]
+ buffer = buffer[done_idx:]
+ except NotImplementedError:
+ parts = self.parse(buffer)
+ # Yield only complete parts
+ if len(parts) > 1:
+ for part in parts[:-1]:
+ yield [part]
+ buffer = parts[-1]
+ # Yield the last part
+ for part in self.parse(buffer):
+ yield [part]
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[list[str]]:
+ buffer = ""
+ async for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ # Extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ continue
+ buffer += chunk_content
+ else:
+ # Add current chunk to buffer
+ buffer += chunk
+ # Parse buffer into a list of parts
+ try:
+ done_idx = 0
+ # Yield only complete parts
+ for m in droplastn(self.parse_iter(buffer), 1):
+ done_idx = m.end()
+ yield [m.group(1)]
+ buffer = buffer[done_idx:]
+ except NotImplementedError:
+ parts = self.parse(buffer)
+ # Yield only complete parts
+ if len(parts) > 1:
+ for part in parts[:-1]:
+ yield [part]
+ buffer = parts[-1]
+ # Yield the last part
+ for part in self.parse(buffer):
+ yield [part]
+
+
+class CommaSeparatedListOutputParser(ListOutputParser):
+ """Parse the output of a model to a comma-separated list."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "output_parsers", "list"]`
+ """
+ return ["langchain", "output_parsers", "list"]
+
+ @override
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the comma-separated list output."""
+ return (
+ "Your response should be a list of comma separated values, "
+ "eg: `foo, bar, baz` or `foo,bar,baz`"
+ )
+
+ @override
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ try:
+ reader = csv.reader(
+ StringIO(text), quotechar='"', delimiter=",", skipinitialspace=True
+ )
+ return [item for sublist in reader for item in sublist]
+ except csv.Error:
+ # Keep old logic for backup
+ return [part.strip() for part in text.split(",")]
+
+ @property
+ def _type(self) -> str:
+ return "comma-separated-list"
+
+
+class NumberedListOutputParser(ListOutputParser):
+ """Parse a numbered list."""
+
+ pattern: str = r"\d+\.\s([^\n]+)"
+ """The pattern to match a numbered list item."""
+
+ @override
+ def get_format_instructions(self) -> str:
+ return (
+ "Your response should be a numbered list with each item on a new line. "
+ "For example: \n\n1. foo\n\n2. bar\n\n3. baz"
+ )
+
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ return re.findall(self.pattern, text)
+
+ @override
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ return re.finditer(self.pattern, text)
+
+ @property
+ def _type(self) -> str:
+ return "numbered-list"
+
+
+class MarkdownListOutputParser(ListOutputParser):
+ """Parse a Markdown list."""
+
+ pattern: str = r"^\s*[-*]\s([^\n]+)$"
+ """The pattern to match a Markdown list item."""
+
+ @override
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the Markdown list output."""
+ return "Your response should be a markdown list, eg: `- foo\n- bar\n- baz`"
+
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ return re.findall(self.pattern, text, re.MULTILINE)
+
+ @override
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ return re.finditer(self.pattern, text, re.MULTILINE)
+
+ @property
+ def _type(self) -> str:
+ return "markdown-list"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_functions.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..812af64292a72c275d17f596e084f3c678f51ea9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_functions.py
@@ -0,0 +1,313 @@
+"""Parsers for OpenAI functions output."""
+
+import copy
+import json
+from types import GenericAlias
+from typing import Any
+
+import jsonpatch # type: ignore[import-untyped]
+from pydantic import BaseModel, model_validator
+from pydantic.v1 import BaseModel as BaseModelV1
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers import (
+ BaseCumulativeTransformOutputParser,
+ BaseGenerationOutputParser,
+)
+from langchain_core.output_parsers.json import parse_partial_json
+from langchain_core.outputs import ChatGeneration, Generation
+
+
+class OutputFunctionsParser(BaseGenerationOutputParser[Any]):
+ """Parse an output that is one of sets of values."""
+
+ args_only: bool = True
+ """Whether to only return the arguments to the function call."""
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ try:
+ func_call = copy.deepcopy(message.additional_kwargs["function_call"])
+ except KeyError as exc:
+ msg = f"Could not parse function call: {exc}"
+ raise OutputParserException(msg) from exc
+
+ if self.args_only:
+ return func_call["arguments"]
+ return func_call
+
+
+class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse an output as the JSON object."""
+
+ strict: bool = False
+ """Whether to allow non-JSON-compliant strings.
+
+ See: https://docs.python.org/3/library/json.html#encoders-and-decoders
+
+ Useful when the parsed output may include unicode characters or new lines.
+ """
+
+ args_only: bool = True
+ """Whether to only return the arguments to the function call."""
+
+ @property
+ def _type(self) -> str:
+ return "json_functions"
+
+ @override
+ def _diff(self, prev: Any | None, next: Any) -> Any:
+ return jsonpatch.make_patch(prev, next).patch
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ if len(result) != 1:
+ msg = f"Expected exactly one result, but got {len(result)}"
+ raise OutputParserException(msg)
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ try:
+ function_call = message.additional_kwargs["function_call"]
+ except KeyError as exc:
+ if partial:
+ return None
+ msg = f"Could not parse function call: {exc}"
+ raise OutputParserException(msg) from exc
+ try:
+ if partial:
+ try:
+ if self.args_only:
+ return parse_partial_json(
+ function_call["arguments"], strict=self.strict
+ )
+ return {
+ **function_call,
+ "arguments": parse_partial_json(
+ function_call["arguments"], strict=self.strict
+ ),
+ }
+ except json.JSONDecodeError:
+ return None
+ elif self.args_only:
+ try:
+ return json.loads(function_call["arguments"], strict=self.strict)
+ except (json.JSONDecodeError, TypeError) as exc:
+ msg = f"Could not parse function call data: {exc}"
+ raise OutputParserException(msg) from exc
+ else:
+ try:
+ return {
+ **function_call,
+ "arguments": json.loads(
+ function_call["arguments"], strict=self.strict
+ ),
+ }
+ except (json.JSONDecodeError, TypeError) as exc:
+ msg = f"Could not parse function call data: {exc}"
+ raise OutputParserException(msg) from exc
+ except KeyError:
+ return None
+
+ # This method would be called by the default implementation of `parse_result`
+ # but we're overriding that method so it's not needed.
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a JSON object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed JSON object.
+ """
+ raise NotImplementedError
+
+
+class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
+ """Parse an output as the element of the JSON object."""
+
+ key_name: str
+ """The name of the key to return."""
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+ """
+ res = super().parse_result(result, partial=partial)
+ if partial and res is None:
+ return None
+ return res.get(self.key_name) if partial else res[self.key_name]
+
+
+class PydanticOutputFunctionsParser(OutputFunctionsParser):
+ """Parse an output as a Pydantic object.
+
+ This parser is used to parse the output of a chat model that uses OpenAI function
+ format to invoke functions.
+
+ The parser extracts the function call invocation and matches them to the Pydantic
+ schema provided.
+
+ An exception will be raised if the function call does not match the provided schema.
+
+ Example:
+ ```python
+ message = AIMessage(
+ content="This is a test message",
+ additional_kwargs={
+ "function_call": {
+ "name": "cookie",
+ "arguments": json.dumps({"name": "value", "age": 10}),
+ }
+ },
+ )
+ chat_generation = ChatGeneration(message=message)
+
+
+ class Cookie(BaseModel):
+ name: str
+ age: int
+
+
+ class Dog(BaseModel):
+ species: str
+
+
+ # Full output
+ parser = PydanticOutputFunctionsParser(
+ pydantic_schema={"cookie": Cookie, "dog": Dog}
+ )
+ result = parser.parse_result([chat_generation])
+ ```
+
+ """
+
+ pydantic_schema: type[BaseModel] | dict[str, type[BaseModel]]
+ """The Pydantic schema to parse the output with.
+
+ If multiple schemas are provided, then the function name will be used to
+ determine which schema to use.
+ """
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_schema(cls, values: dict[str, Any]) -> Any:
+ """Validate the Pydantic schema.
+
+ Args:
+ values: The values to validate.
+
+ Returns:
+ The validated values.
+
+ Raises:
+ ValueError: If the schema is not a Pydantic schema.
+ """
+ schema = values["pydantic_schema"]
+ if "args_only" not in values:
+ values["args_only"] = (
+ isinstance(schema, type)
+ and not isinstance(schema, GenericAlias)
+ and issubclass(schema, BaseModel)
+ )
+ elif values["args_only"] and isinstance(schema, dict):
+ msg = (
+ "If multiple pydantic schemas are provided then args_only should be"
+ " False."
+ )
+ raise ValueError(msg)
+ return values
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Raises:
+ ValueError: If the Pydantic schema is not valid.
+
+ Returns:
+ The parsed JSON object.
+ """
+ result_ = super().parse_result(result)
+ if self.args_only:
+ if hasattr(self.pydantic_schema, "model_validate_json"):
+ pydantic_args = self.pydantic_schema.model_validate_json(result_)
+ else:
+ pydantic_args = self.pydantic_schema.parse_raw(result_) # type: ignore[attr-defined]
+ else:
+ fn_name = result_["name"]
+ args = result_["arguments"]
+ if isinstance(self.pydantic_schema, dict):
+ pydantic_schema = self.pydantic_schema[fn_name]
+ else:
+ pydantic_schema = self.pydantic_schema
+ if issubclass(pydantic_schema, BaseModel):
+ pydantic_args = pydantic_schema.model_validate_json(args)
+ elif issubclass(pydantic_schema, BaseModelV1):
+ pydantic_args = pydantic_schema.parse_raw(args)
+ else:
+ msg = f"Unsupported Pydantic schema: {pydantic_schema}"
+ raise ValueError(msg)
+ return pydantic_args
+
+
+class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):
+ """Parse an output as an attribute of a Pydantic object."""
+
+ attr_name: str
+ """The name of the attribute to return."""
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+ """
+ result = super().parse_result(result)
+ return getattr(result, self.attr_name)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_tools.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..c42e09466533a895097ae214f96940cc3a3bc13c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/openai_tools.py
@@ -0,0 +1,384 @@
+"""Parse tools for OpenAI tools output."""
+
+import copy
+import json
+import logging
+from json import JSONDecodeError
+from typing import Annotated, Any
+
+from pydantic import SkipValidation, ValidationError
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.messages import AIMessage, InvalidToolCall
+from langchain_core.messages.tool import invalid_tool_call
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.output_parsers.transform import BaseCumulativeTransformOutputParser
+from langchain_core.outputs import ChatGeneration, Generation
+from langchain_core.utils.json import parse_partial_json
+from langchain_core.utils.pydantic import (
+ TypeBaseModel,
+ is_pydantic_v1_subclass,
+ is_pydantic_v2_subclass,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def parse_tool_call(
+ raw_tool_call: dict[str, Any],
+ *,
+ partial: bool = False,
+ strict: bool = False,
+ return_id: bool = True,
+) -> dict[str, Any] | None:
+ """Parse a single tool call.
+
+ Args:
+ raw_tool_call: The raw tool call to parse.
+ partial: Whether to parse partial JSON.
+ strict: Whether to allow non-JSON-compliant strings.
+ return_id: Whether to return the tool call id.
+
+ Returns:
+ The parsed tool call.
+
+ Raises:
+ OutputParserException: If the tool call is not valid JSON.
+ """
+ if "function" not in raw_tool_call:
+ return None
+
+ arguments = raw_tool_call["function"]["arguments"]
+
+ if partial:
+ try:
+ function_args = parse_partial_json(arguments, strict=strict)
+ except (JSONDecodeError, TypeError): # None args raise TypeError
+ return None
+ # Handle None or empty string arguments for parameter-less tools
+ elif not arguments:
+ function_args = {}
+ else:
+ try:
+ function_args = json.loads(arguments, strict=strict)
+ except JSONDecodeError as e:
+ msg = (
+ f"Function {raw_tool_call['function']['name']} arguments:\n\n"
+ f"{arguments}\n\nare not valid JSON. "
+ f"Received JSONDecodeError {e}"
+ )
+ raise OutputParserException(msg) from e
+ parsed = {
+ "name": raw_tool_call["function"]["name"] or "",
+ "args": function_args or {},
+ }
+ if return_id:
+ parsed["id"] = raw_tool_call.get("id")
+ parsed = create_tool_call(**parsed) # type: ignore[assignment,arg-type]
+ return parsed
+
+
+def make_invalid_tool_call(
+ raw_tool_call: dict[str, Any],
+ error_msg: str | None,
+) -> InvalidToolCall:
+ """Create an `InvalidToolCall` from a raw tool call.
+
+ Args:
+ raw_tool_call: The raw tool call.
+ error_msg: The error message.
+
+ Returns:
+ An `InvalidToolCall` instance with the error message.
+ """
+ return invalid_tool_call(
+ name=raw_tool_call["function"]["name"],
+ args=raw_tool_call["function"]["arguments"],
+ id=raw_tool_call.get("id"),
+ error=error_msg,
+ )
+
+
+def parse_tool_calls(
+ raw_tool_calls: list[dict],
+ *,
+ partial: bool = False,
+ strict: bool = False,
+ return_id: bool = True,
+) -> list[dict[str, Any]]:
+ """Parse a list of tool calls.
+
+ Args:
+ raw_tool_calls: The raw tool calls to parse.
+ partial: Whether to parse partial JSON.
+ strict: Whether to allow non-JSON-compliant strings.
+ return_id: Whether to return the tool call id.
+
+ Returns:
+ The parsed tool calls.
+
+ Raises:
+ OutputParserException: If any of the tool calls are not valid JSON.
+ """
+ final_tools: list[dict[str, Any]] = []
+ exceptions = []
+ for tool_call in raw_tool_calls:
+ try:
+ parsed = parse_tool_call(
+ tool_call, partial=partial, strict=strict, return_id=return_id
+ )
+ if parsed:
+ final_tools.append(parsed)
+ except OutputParserException as e:
+ exceptions.append(str(e))
+ continue
+ if exceptions:
+ raise OutputParserException("\n\n".join(exceptions))
+ return final_tools
+
+
+class JsonOutputToolsParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse tools from OpenAI response."""
+
+ strict: bool = False
+ """Whether to allow non-JSON-compliant strings.
+
+ See: https://docs.python.org/3/library/json.html#encoders-and-decoders
+
+ Useful when the parsed output may include unicode characters or new lines.
+ """
+
+ return_id: bool = False
+ """Whether to return the tool call id."""
+
+ first_tool_only: bool = False
+ """Whether to return only the first tool call.
+
+ If `False`, the result will be a list of tool calls, or an empty list if no tool
+ calls are found.
+
+ If `True`, and multiple tool calls are found, only the first one will be returned,
+ and the other tool calls will be ignored.
+
+ If no tool calls are found, `None` will be returned.
+ """
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of tool calls.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+
+ If `True`, the output will be a JSON object containing
+ all the keys that have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed tool calls.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ if isinstance(message, AIMessage) and message.tool_calls:
+ tool_calls = [dict(tc) for tc in message.tool_calls]
+ for tool_call in tool_calls:
+ if not self.return_id:
+ _ = tool_call.pop("id")
+ else:
+ try:
+ raw_tool_calls = copy.deepcopy(message.additional_kwargs["tool_calls"])
+ except KeyError:
+ return []
+ tool_calls = parse_tool_calls(
+ raw_tool_calls,
+ partial=partial,
+ strict=self.strict,
+ return_id=self.return_id,
+ )
+ # for backwards compatibility
+ for tc in tool_calls:
+ tc["type"] = tc.pop("name")
+
+ if self.first_tool_only:
+ return tool_calls[0] if tool_calls else None
+ return tool_calls
+
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a list of tool calls.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed tool calls.
+ """
+ raise NotImplementedError
+
+
+class JsonOutputKeyToolsParser(JsonOutputToolsParser):
+ """Parse tools from OpenAI response."""
+
+ key_name: str
+ """The type of tools to return."""
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of tool calls.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+ If `True`, the output will be a JSON object containing
+ all the keys that have been returned so far.
+ If `False`, the output will be the full JSON object.
+
+ Raises:
+ OutputParserException: If the generation is not a chat generation.
+
+ Returns:
+ The parsed tool calls.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ if isinstance(message, AIMessage) and message.tool_calls:
+ parsed_tool_calls = [dict(tc) for tc in message.tool_calls]
+ for tool_call in parsed_tool_calls:
+ if not self.return_id:
+ _ = tool_call.pop("id")
+ else:
+ try:
+ # This exists purely for backward compatibility / cached messages
+ # All new messages should use `message.tool_calls`
+ raw_tool_calls = copy.deepcopy(message.additional_kwargs["tool_calls"])
+ except KeyError:
+ if self.first_tool_only:
+ return None
+ return []
+ parsed_tool_calls = parse_tool_calls(
+ raw_tool_calls,
+ partial=partial,
+ strict=self.strict,
+ return_id=self.return_id,
+ )
+ # For backwards compatibility
+ for tc in parsed_tool_calls:
+ tc["type"] = tc.pop("name")
+ if self.first_tool_only:
+ parsed_result = list(
+ filter(lambda x: x["type"] == self.key_name, parsed_tool_calls)
+ )
+ single_result = (
+ parsed_result[0]
+ if parsed_result and parsed_result[0]["type"] == self.key_name
+ else None
+ )
+ if self.return_id:
+ return single_result
+ if single_result:
+ return single_result["args"]
+ return None
+ return (
+ [res for res in parsed_tool_calls if res["type"] == self.key_name]
+ if self.return_id
+ else [
+ res["args"] for res in parsed_tool_calls if res["type"] == self.key_name
+ ]
+ )
+
+
+# Common cause of ValidationError is truncated output due to max_tokens.
+_MAX_TOKENS_ERROR = (
+ "Output parser received a `max_tokens` stop reason. "
+ "The output is likely incomplete—please increase `max_tokens` "
+ "or shorten your prompt."
+)
+
+
+class PydanticToolsParser(JsonOutputToolsParser):
+ """Parse tools from OpenAI response."""
+
+ tools: Annotated[list[TypeBaseModel], SkipValidation()]
+ """The tools to parse."""
+
+ # TODO: Support more granular streaming of objects.
+ # Currently only streams once all Pydantic object fields are present.
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of Pydantic objects.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed Pydantic objects.
+
+ Raises:
+ ValueError: If the tool call arguments are not a dict.
+ ValidationError: If the tool call arguments do not conform to the Pydantic
+ model.
+ """
+ json_results = super().parse_result(result, partial=partial)
+ if not json_results:
+ return None if self.first_tool_only else []
+
+ json_results = [json_results] if self.first_tool_only else json_results
+ name_dict_v2: dict[str, TypeBaseModel] = {
+ tool.model_config.get("title") or tool.__name__: tool
+ for tool in self.tools
+ if is_pydantic_v2_subclass(tool)
+ }
+ name_dict_v1: dict[str, TypeBaseModel] = {
+ tool.__name__: tool for tool in self.tools if is_pydantic_v1_subclass(tool)
+ }
+ name_dict: dict[str, TypeBaseModel] = {**name_dict_v2, **name_dict_v1}
+ pydantic_objects = []
+ for res in json_results:
+ if not isinstance(res["args"], dict):
+ if partial:
+ continue
+ msg = (
+ f"Tool arguments must be specified as a dict, received: "
+ f"{res['args']}"
+ )
+ raise ValueError(msg)
+
+ try:
+ tool = name_dict[res["type"]]
+ except KeyError as e:
+ available = ", ".join(name_dict.keys()) or ""
+ msg = (
+ f"Unknown tool type: {res['type']!r}. Available tools: {available}"
+ )
+ raise OutputParserException(msg) from e
+
+ try:
+ pydantic_objects.append(tool(**res["args"]))
+ except (ValidationError, ValueError):
+ if partial:
+ continue
+ has_max_tokens_stop_reason = any(
+ generation.message.response_metadata.get("stop_reason")
+ == "max_tokens"
+ for generation in result
+ if isinstance(generation, ChatGeneration)
+ )
+ if has_max_tokens_stop_reason:
+ logger.exception(_MAX_TOKENS_ERROR)
+ raise
+ if self.first_tool_only:
+ return pydantic_objects[0] if pydantic_objects else None
+ return pydantic_objects
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/pydantic.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/pydantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a7eee972dfc4e7472b792fa3ef1b820c8dacee1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/pydantic.py
@@ -0,0 +1,139 @@
+"""Output parsers using Pydantic."""
+
+import json
+from typing import Annotated, Generic, Literal, overload
+
+import pydantic
+from pydantic import SkipValidation
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers import JsonOutputParser
+from langchain_core.outputs import Generation
+from langchain_core.utils.pydantic import (
+ PydanticBaseModel,
+ TBaseModel,
+)
+
+
+class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
+ """Parse an output using a Pydantic model."""
+
+ pydantic_object: Annotated[type[TBaseModel], SkipValidation()]
+ """The Pydantic model to parse."""
+
+ def _parse_obj(self, obj: dict) -> TBaseModel:
+ try:
+ if issubclass(self.pydantic_object, pydantic.BaseModel):
+ return self.pydantic_object.model_validate(obj)
+ if issubclass(self.pydantic_object, pydantic.v1.BaseModel):
+ return self.pydantic_object.parse_obj(obj)
+ msg = f"Unsupported model version for PydanticOutputParser: \
+ {self.pydantic_object.__class__}"
+ raise OutputParserException(msg)
+ except (pydantic.ValidationError, pydantic.v1.ValidationError) as e:
+ raise self._parser_exception(e, obj) from e
+
+ def _parser_exception(
+ self, e: Exception, json_object: dict
+ ) -> OutputParserException:
+ json_string = json.dumps(json_object, ensure_ascii=False)
+ name = self.pydantic_object.__name__
+ msg = f"Failed to parse {name} from completion {json_string}. Got: {e}"
+ return OutputParserException(msg, llm_output=json_string)
+
+ @overload
+ def parse_result(
+ self, result: list[Generation], *, partial: Literal[False] = False
+ ) -> TBaseModel: ...
+
+ @overload
+ def parse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> TBaseModel | None: ...
+
+ def parse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> TBaseModel | None:
+ """Parse the result of an LLM call to a Pydantic object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ Raises:
+ OutputParserException: If the result is not valid JSON or does not conform
+ to the Pydantic model.
+
+ Returns:
+ The parsed Pydantic object.
+ """
+ try:
+ json_object = super().parse_result(result)
+ return self._parse_obj(json_object)
+ except OutputParserException:
+ if partial:
+ return None
+ raise
+
+ def parse(self, text: str) -> TBaseModel:
+ """Parse the output of an LLM call to a Pydantic object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed Pydantic object.
+ """
+ return self.parse_result([Generation(text=text)])
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the JSON output.
+
+ Returns:
+ The format instructions for the JSON output.
+ """
+ # Copy schema to avoid altering original Pydantic schema.
+ schema = dict(self._get_schema(self.pydantic_object).items())
+
+ # Remove extraneous fields.
+ reduced_schema = schema
+ if "title" in reduced_schema:
+ del reduced_schema["title"]
+ if "type" in reduced_schema:
+ del reduced_schema["type"]
+ # Ensure json in context is well-formed with double quotes.
+ schema_str = json.dumps(reduced_schema, ensure_ascii=False)
+
+ return _PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str)
+
+ @property
+ def _type(self) -> str:
+ return "pydantic"
+
+ @property
+ @override
+ def OutputType(self) -> type[TBaseModel]:
+ """Return the Pydantic model."""
+ return self.pydantic_object
+
+
+_PYDANTIC_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance that conforms to the JSON schema below.
+
+As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
+the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
+
+Here is the output schema:
+```
+{schema}
+```""" # noqa: E501
+
+# Re-exporting types for backwards compatibility
+__all__ = [
+ "PydanticBaseModel",
+ "PydanticOutputParser",
+ "TBaseModel",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/string.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/string.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d8f3bb6eddc1253fbd57347859586d208db69a6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/string.py
@@ -0,0 +1,63 @@
+"""String output parser."""
+
+from typing_extensions import override
+
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+
+
+class StrOutputParser(BaseTransformOutputParser[str]):
+ """Extract text content from model outputs as a string.
+
+ Converts model outputs (such as `AIMessage` or `AIMessageChunk` objects) into plain
+ text strings. It's the simplest output parser and is useful when you need string
+ responses for downstream processing, display, or storage.
+
+ Supports streaming, yielding text chunks as they're generated by the model.
+
+ Example:
+ ```python
+ from langchain_core.output_parsers import StrOutputParser
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(model="gpt-4o")
+ parser = StrOutputParser()
+
+ # Get string output from a model
+ message = model.invoke("Tell me a joke")
+ result = parser.invoke(message)
+ print(result) # plain string
+
+ # With streaming - use transform() to process a stream
+ stream = model.stream("Tell me a story")
+ for chunk in parser.transform(stream):
+ print(chunk, end="", flush=True)
+ ```
+ """
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """`StrOutputParser` is serializable.
+
+ Returns:
+ `True`
+ """
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "output_parser"]`
+ """
+ return ["langchain", "schema", "output_parser"]
+
+ @property
+ def _type(self) -> str:
+ """Return the output parser type for serialization."""
+ return "default"
+
+ @override
+ def parse(self, text: str) -> str:
+ """Returns the input text with no changes."""
+ return text
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/transform.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..f04d66b68511decb6ba5dafa183c47516c49842d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/transform.py
@@ -0,0 +1,175 @@
+"""Base classes for output parsers that can handle streaming input."""
+
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.messages import BaseMessage, BaseMessageChunk
+from langchain_core.output_parsers.base import BaseOutputParser, T
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ Generation,
+ GenerationChunk,
+)
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_core.runnables import RunnableConfig
+
+
+class BaseTransformOutputParser(BaseOutputParser[T]):
+ """Base class for an output parser that can handle streaming input."""
+
+ def _transform(
+ self,
+ input: Iterator[str | BaseMessage],
+ ) -> Iterator[T]:
+ for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ yield self.parse_result([ChatGeneration(message=chunk)])
+ else:
+ yield self.parse_result([Generation(text=chunk)])
+
+ async def _atransform(
+ self,
+ input: AsyncIterator[str | BaseMessage],
+ ) -> AsyncIterator[T]:
+ async for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ yield await run_in_executor(
+ None, self.parse_result, [ChatGeneration(message=chunk)]
+ )
+ else:
+ yield await run_in_executor(
+ None, self.parse_result, [Generation(text=chunk)]
+ )
+
+ @override
+ def transform(
+ self,
+ input: Iterator[str | BaseMessage],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[T]:
+ """Transform the input into the output format.
+
+ Args:
+ input: The input to transform.
+ config: The configuration to use for the transformation.
+ **kwargs: Additional keyword arguments.
+
+ Yields:
+ The transformed output.
+ """
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, run_type="parser"
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[str | BaseMessage],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[T]:
+ """Async transform the input into the output format.
+
+ Args:
+ input: The input to transform.
+ config: The configuration to use for the transformation.
+ **kwargs: Additional keyword arguments.
+
+ Yields:
+ The transformed output.
+ """
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, run_type="parser"
+ ):
+ yield chunk
+
+
+class BaseCumulativeTransformOutputParser(BaseTransformOutputParser[T]):
+ """Base class for an output parser that can handle streaming input."""
+
+ diff: bool = False
+ """In streaming mode, whether to yield diffs between the previous and current parsed
+ output, or just the current parsed output.
+ """
+
+ def _diff(
+ self,
+ prev: T | None,
+ next: T, # noqa: A002
+ ) -> T:
+ """Convert parsed outputs into a diff format.
+
+ The semantics of this are up to the output parser.
+
+ Args:
+ prev: The previous parsed output.
+ next: The current parsed output.
+
+ Returns:
+ The diff between the previous and current parsed output.
+ """
+ raise NotImplementedError
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[Any]:
+ prev_parsed = None
+ acc_gen: GenerationChunk | ChatGenerationChunk | None = None
+ for chunk in input:
+ chunk_gen: GenerationChunk | ChatGenerationChunk
+ if isinstance(chunk, BaseMessageChunk):
+ chunk_gen = ChatGenerationChunk(message=chunk)
+ elif isinstance(chunk, BaseMessage):
+ chunk_gen = ChatGenerationChunk(
+ message=BaseMessageChunk(**chunk.model_dump())
+ )
+ else:
+ chunk_gen = GenerationChunk(text=chunk)
+
+ acc_gen = chunk_gen if acc_gen is None else acc_gen + chunk_gen # type: ignore[operator]
+
+ parsed = self.parse_result([acc_gen], partial=True)
+ if parsed is not None and parsed != prev_parsed:
+ if self.diff:
+ yield self._diff(prev_parsed, parsed)
+ else:
+ yield parsed
+ prev_parsed = parsed
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[T]:
+ prev_parsed = None
+ acc_gen: GenerationChunk | ChatGenerationChunk | None = None
+ async for chunk in input:
+ chunk_gen: GenerationChunk | ChatGenerationChunk
+ if isinstance(chunk, BaseMessageChunk):
+ chunk_gen = ChatGenerationChunk(message=chunk)
+ elif isinstance(chunk, BaseMessage):
+ chunk_gen = ChatGenerationChunk(
+ message=BaseMessageChunk(**chunk.model_dump())
+ )
+ else:
+ chunk_gen = GenerationChunk(text=chunk)
+
+ acc_gen = chunk_gen if acc_gen is None else acc_gen + chunk_gen # type: ignore[operator]
+
+ parsed = await self.aparse_result([acc_gen], partial=True)
+ if parsed is not None and parsed != prev_parsed:
+ if self.diff:
+ yield await run_in_executor(None, self._diff, prev_parsed, parsed)
+ else:
+ yield parsed
+ prev_parsed = parsed
diff --git a/python/user_packages/Python313/site-packages/langchain_core/output_parsers/xml.py b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/xml.py
new file mode 100644
index 0000000000000000000000000000000000000000..c65a1db3299a6694bef71cd1e5015dfb6782e542
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/output_parsers/xml.py
@@ -0,0 +1,300 @@
+"""Output parser for XML format."""
+
+import contextlib
+import re
+import xml
+import xml.etree.ElementTree as ET
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, Literal
+from xml.etree.ElementTree import TreeBuilder
+
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.messages import BaseMessage
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+from langchain_core.runnables.utils import AddableDict
+
+try:
+ from defusedxml import ElementTree # type: ignore[import-untyped]
+ from defusedxml.ElementTree import XMLParser # type: ignore[import-untyped]
+
+ _HAS_DEFUSEDXML = True
+except ImportError:
+ _HAS_DEFUSEDXML = False
+
+XML_FORMAT_INSTRUCTIONS = """The output should be formatted as a XML file.
+1. Output should conform to the tags below.
+2. If tags are not given, make them on your own.
+3. Remember to always open and close all the tags.
+
+As an example, for the tags ["foo", "bar", "baz"]:
+1. String "\n \n \n \n " is a well-formatted instance of the schema.
+2. String "\n \n " is a badly-formatted instance.
+3. String "\n \n \n " is a badly-formatted instance.
+
+Here are the output tags:
+```
+{tags}
+```""" # noqa: E501
+
+
+class _StreamingParser:
+ """Streaming parser for XML.
+
+ This implementation is pulled into a class to avoid implementation drift between
+ `transform` and `atransform` of the `XMLOutputParser`.
+ """
+
+ def __init__(self, parser: Literal["defusedxml", "xml"]) -> None:
+ """Initialize the streaming parser.
+
+ Args:
+ parser: Parser to use for XML parsing.
+
+ Can be either `'defusedxml'` or `'xml'`. See documentation in
+ `XMLOutputParser` for more information.
+
+ Raises:
+ ImportError: If `defusedxml` is not installed and the `defusedxml` parser is
+ requested.
+ """
+ if parser == "defusedxml":
+ if not _HAS_DEFUSEDXML:
+ msg = (
+ "defusedxml is not installed. "
+ "Please install it to use the defusedxml parser."
+ "You can install it with `pip install defusedxml` "
+ )
+ raise ImportError(msg)
+ parser_ = XMLParser(target=TreeBuilder())
+ else:
+ parser_ = None
+ self.pull_parser = ET.XMLPullParser(["start", "end"], _parser=parser_)
+ self.xml_start_re = re.compile(r"<[a-zA-Z:_]")
+ self.current_path: list[str] = []
+ self.current_path_has_children = False
+ self.buffer = ""
+ self.xml_started = False
+
+ def parse(self, chunk: str | BaseMessage) -> Iterator[AddableDict]:
+ """Parse a chunk of text.
+
+ Args:
+ chunk: A chunk of text to parse. This can be a `str` or a `BaseMessage`.
+
+ Yields:
+ A `dict` representing the parsed XML element.
+
+ Raises:
+ xml.etree.ElementTree.ParseError: If the XML is not well-formed.
+ """
+ if isinstance(chunk, BaseMessage):
+ # extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ # ignore non-string messages (e.g., function calls)
+ return
+ chunk = chunk_content
+ # add chunk to buffer of unprocessed text
+ self.buffer += chunk
+ # if xml string hasn't started yet, continue to next chunk
+ if not self.xml_started:
+ if match := self.xml_start_re.search(self.buffer):
+ # if xml string has started, remove all text before it
+ self.buffer = self.buffer[match.start() :]
+ self.xml_started = True
+ else:
+ return
+ # feed buffer to parser
+ self.pull_parser.feed(self.buffer)
+ self.buffer = ""
+ # yield all events
+ try:
+ events = self.pull_parser.read_events()
+ for event, elem in events: # type: ignore[misc]
+ if event == "start":
+ # update current path
+ self.current_path.append(elem.tag) # type: ignore[union-attr]
+ self.current_path_has_children = False
+ elif event == "end":
+ # remove last element from current path
+ #
+ self.current_path.pop()
+ # yield element
+ if not self.current_path_has_children:
+ yield nested_element(self.current_path, elem) # type: ignore[arg-type]
+ # prevent yielding of parent element
+ if self.current_path:
+ self.current_path_has_children = True
+ else:
+ self.xml_started = False
+ except xml.etree.ElementTree.ParseError:
+ # This might be junk at the end of the XML input.
+ # Let's check whether the current path is empty.
+ if not self.current_path:
+ # If it is empty, we can ignore this error.
+ return
+ else:
+ raise
+
+ def close(self) -> None:
+ """Close the parser.
+
+ This should be called after all chunks have been parsed.
+ """
+ # Ignore ParseError. This will ignore any incomplete XML at the end of the input
+ with contextlib.suppress(xml.etree.ElementTree.ParseError):
+ self.pull_parser.close()
+
+
+class XMLOutputParser(BaseTransformOutputParser):
+ """Parse an output using xml format.
+
+ Returns a dictionary of tags.
+ """
+
+ tags: list[str] | None = None
+ """Tags to tell the LLM to expect in the XML output.
+
+ Note this may not be perfect depending on the LLM implementation.
+
+ For example, with `tags=["foo", "bar", "baz"]`:
+
+ 1. A well-formatted XML instance:
+ `'\n \n \n \n '`
+
+ 2. A badly-formatted XML instance (missing closing tag for 'bar'):
+ `'\n \n '`
+
+ 3. A badly-formatted XML instance (unexpected 'tag' element):
+ `'\n \n \n '`
+ """
+ encoding_matcher: re.Pattern = re.compile(
+ r"<([^>]*encoding[^>]*)>\n(.*)", re.MULTILINE | re.DOTALL
+ )
+
+ parser: Literal["defusedxml", "xml"] = "defusedxml"
+ """Parser to use for XML parsing.
+
+ Can be either `'defusedxml'` or `'xml'`.
+
+ - `'defusedxml'` is the default parser and is used to prevent XML vulnerabilities
+ present in some distributions of Python's standard library xml. `defusedxml` is
+ a wrapper around the standard library parser that sets up the parser with secure
+ defaults.
+ - `'xml'` is the standard library parser.
+
+ !!! warning
+
+ Use `xml` only if you are sure that your distribution of the standard library is
+ not vulnerable to XML vulnerabilities.
+
+ Review the following resources for more information:
+
+ * https://docs.python.org/3/library/xml.html#xml-vulnerabilities
+ * https://github.com/tiran/defusedxml
+
+ The standard library relies on [`libexpat`](https://github.com/libexpat/libexpat)
+ for parsing XML.
+ """
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the XML output."""
+ return XML_FORMAT_INSTRUCTIONS.format(tags=self.tags)
+
+ def parse(self, text: str) -> dict[str, str | list[Any]]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A `dict` representing the parsed XML.
+
+ Raises:
+ OutputParserException: If the XML is not well-formed.
+ ImportError: If defus`edxml is not installed and the `defusedxml` parser is
+ requested.
+ """
+ # Try to find XML string within triple backticks
+ # Imports are temporarily placed here to avoid issue with caching on CI
+ # likely if you're reading this you can move them to the top of the file
+ if self.parser == "defusedxml":
+ if not _HAS_DEFUSEDXML:
+ msg = (
+ "defusedxml is not installed. "
+ "Please install it to use the defusedxml parser."
+ "You can install it with `pip install defusedxml`"
+ "See https://github.com/tiran/defusedxml for more details"
+ )
+ raise ImportError(msg)
+ et = ElementTree # Use the defusedxml parser
+ else:
+ et = ET # Use the standard library parser
+
+ match = re.search(r"```(xml)?(.*)```", text, re.DOTALL)
+ if match is not None:
+ # If match found, use the content within the backticks
+ text = match.group(2)
+ encoding_match = self.encoding_matcher.search(text)
+ if encoding_match:
+ text = encoding_match.group(2)
+
+ text = text.strip()
+ try:
+ root = et.fromstring(text)
+ return self._root_to_dict(root)
+ except et.ParseError as e:
+ msg = f"Failed to parse XML format from completion {text}. Got: {e}"
+ raise OutputParserException(msg, llm_output=text) from e
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[AddableDict]:
+ streaming_parser = _StreamingParser(self.parser)
+ for chunk in input:
+ yield from streaming_parser.parse(chunk)
+ streaming_parser.close()
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[AddableDict]:
+ streaming_parser = _StreamingParser(self.parser)
+ async for chunk in input:
+ for output in streaming_parser.parse(chunk):
+ yield output
+ streaming_parser.close()
+
+ def _root_to_dict(self, root: ET.Element) -> dict[str, str | list[Any]]:
+ """Converts xml tree to python dictionary."""
+ if root.text and bool(re.search(r"\S", root.text)):
+ # If root text contains any non-whitespace character it
+ # returns {root.tag: root.text}
+ return {root.tag: root.text}
+ result: dict = {root.tag: []}
+ for child in root:
+ if len(child) == 0:
+ result[root.tag].append({child.tag: child.text})
+ else:
+ result[root.tag].append(self._root_to_dict(child))
+ return result
+
+ @property
+ def _type(self) -> str:
+ return "xml"
+
+
+def nested_element(path: list[str], elem: ET.Element) -> Any:
+ """Get nested element from path.
+
+ Args:
+ path: The path to the element.
+ elem: The element to extract.
+
+ Returns:
+ The nested element.
+ """
+ if len(path) == 0:
+ return AddableDict({elem.tag: elem.text})
+ return AddableDict({path[0]: [nested_element(path[1:], elem)]})
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d579010ee76187168ad8164555884aed4bd1a267
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/__init__.py
@@ -0,0 +1,66 @@
+"""Output classes.
+
+Used to represent the output of a language model call and the output of a chat.
+
+The top container for information is the `LLMResult` object. `LLMResult` is used by both
+chat models and LLMs. This object contains the output of the language model and any
+additional information that the model provider wants to return.
+
+When invoking models via the standard runnable methods (e.g. invoke, batch, etc.):
+
+- Chat models will return `AIMessage` objects.
+- LLMs will return regular text strings.
+
+In addition, users can access the raw output of either LLMs or chat models via
+callbacks. The `on_chat_model_end` and `on_llm_end` callbacks will return an `LLMResult`
+object containing the generated outputs and any additional information returned by the
+model provider.
+
+In general, if information is already available in the AIMessage object, it is
+recommended to access it from there rather than from the `LLMResult` object.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.outputs.chat_generation import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ )
+ from langchain_core.outputs.chat_result import ChatResult
+ from langchain_core.outputs.generation import Generation, GenerationChunk
+ from langchain_core.outputs.llm_result import LLMResult
+ from langchain_core.outputs.run_info import RunInfo
+
+__all__ = (
+ "ChatGeneration",
+ "ChatGenerationChunk",
+ "ChatResult",
+ "Generation",
+ "GenerationChunk",
+ "LLMResult",
+ "RunInfo",
+)
+
+_dynamic_imports = {
+ "ChatGeneration": "chat_generation",
+ "ChatGenerationChunk": "chat_generation",
+ "ChatResult": "chat_result",
+ "Generation": "generation",
+ "GenerationChunk": "generation",
+ "LLMResult": "llm_result",
+ "RunInfo": "run_info",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29c317fbc1bf05e010ce6b4f3952516719f5ba0e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..deedd15be8d4fa4a0910e9fb3a41d592eab640ba
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..739d1c13dc656abae0549dfb098a8fe145dfefb4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/generation.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/generation.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71937ea0d8f5b72532b28dcabc09360e14453285
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/generation.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8149d9a45ba3aece021eee3921552ad600370f15
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..139e9621e4149af7776497647517f439be5f7c40
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_generation.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..b104d9b613350a38b6b4a5ae5addb4d3dd477454
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_generation.py
@@ -0,0 +1,157 @@
+"""Chat generation output classes."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from pydantic import model_validator
+
+from langchain_core.messages import BaseMessage, BaseMessageChunk
+from langchain_core.outputs.generation import Generation
+from langchain_core.utils._merge import merge_dicts
+
+if TYPE_CHECKING:
+ from typing_extensions import Self
+
+
+class ChatGeneration(Generation):
+ """A single chat generation output.
+
+ A subclass of `Generation` that represents the response from a chat model that
+ generates chat messages.
+
+ The `message` attribute is a structured representation of the chat message. Most of
+ the time, the message will be of type `AIMessage`.
+
+ Users working with chat models will usually access information via either
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks).
+ """
+
+ text: str = ""
+ """The text contents of the output message.
+
+ !!! warning "SHOULD NOT BE SET DIRECTLY!"
+
+ """
+ message: BaseMessage
+ """The message output by the chat model."""
+
+ # Override type to be ChatGeneration, ignore mypy error as this is intentional
+ type: Literal["ChatGeneration"] = "ChatGeneration" # type: ignore[assignment]
+ """Type is used exclusively for serialization purposes."""
+
+ @model_validator(mode="after")
+ def set_text(self) -> Self:
+ """Set the text attribute to be the contents of the message.
+
+ Args:
+ values: The values of the object.
+
+ Returns:
+ The values of the object with the text attribute set.
+
+ Raises:
+ ValueError: If the message is not a string or a list.
+ """
+ # Check for legacy blocks with "text" key but no "type" field.
+ # Otherwise, delegate to `message.text`.
+ if isinstance(self.message.content, list):
+ has_legacy_blocks = any(
+ isinstance(block, dict)
+ and "text" in block
+ and block.get("type") is None
+ for block in self.message.content
+ )
+
+ if has_legacy_blocks:
+ blocks = []
+ for block in self.message.content:
+ if isinstance(block, str):
+ blocks.append(block)
+ elif isinstance(block, dict):
+ block_type = block.get("type")
+ if block_type == "text" or (
+ block_type is None and "text" in block
+ ):
+ blocks.append(block.get("text", ""))
+ self.text = "".join(blocks)
+ else:
+ self.text = self.message.text
+ else:
+ self.text = self.message.text
+
+ return self
+
+
+class ChatGenerationChunk(ChatGeneration):
+ """`ChatGeneration` chunk.
+
+ `ChatGeneration` chunks can be concatenated with other `ChatGeneration` chunks.
+ """
+
+ message: BaseMessageChunk
+ """The message chunk output by the chat model."""
+ # Override type to be ChatGeneration, ignore mypy error as this is intentional
+
+ type: Literal["ChatGenerationChunk"] = "ChatGenerationChunk" # type: ignore[assignment]
+ """Type is used exclusively for serialization purposes."""
+
+ def __add__(
+ self, other: ChatGenerationChunk | list[ChatGenerationChunk]
+ ) -> ChatGenerationChunk:
+ """Concatenate two `ChatGenerationChunk`s.
+
+ Args:
+ other: The other `ChatGenerationChunk` or list of `ChatGenerationChunk` to
+ concatenate.
+
+ Raises:
+ TypeError: If other is not a `ChatGenerationChunk` or list of
+ `ChatGenerationChunk`.
+
+ Returns:
+ A new `ChatGenerationChunk` concatenated from self and other.
+ """
+ if isinstance(other, ChatGenerationChunk):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ other.generation_info or {},
+ )
+ return ChatGenerationChunk(
+ message=self.message + other.message,
+ generation_info=generation_info or None,
+ )
+ if isinstance(other, list) and all(
+ isinstance(x, ChatGenerationChunk) for x in other
+ ):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ *[chunk.generation_info for chunk in other if chunk.generation_info],
+ )
+ return ChatGenerationChunk(
+ message=self.message + [chunk.message for chunk in other],
+ generation_info=generation_info or None,
+ )
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+
+def merge_chat_generation_chunks(
+ chunks: list[ChatGenerationChunk],
+) -> ChatGenerationChunk | None:
+ """Merge a list of `ChatGenerationChunk`s into a single `ChatGenerationChunk`.
+
+ Args:
+ chunks: A list of `ChatGenerationChunk` to merge.
+
+ Returns:
+ A merged `ChatGenerationChunk`, or `None` if the input list is empty.
+ """
+ if not chunks:
+ return None
+
+ if len(chunks) == 1:
+ return chunks[0]
+
+ return chunks[0] + chunks[1:]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_result.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cc814310e44ffce6bc0b84475d81f5dae735a43
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/chat_result.py
@@ -0,0 +1,37 @@
+"""Chat result schema."""
+
+from pydantic import BaseModel
+
+from langchain_core.outputs.chat_generation import ChatGeneration
+
+
+class ChatResult(BaseModel):
+ """Use to represent the result of a chat model call with a single prompt.
+
+ This container is used internally by some implementations of chat model, it will
+ eventually be mapped to a more general `LLMResult` object, and then projected into
+ an `AIMessage` object.
+
+ LangChain users working with chat models will usually access information via
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks). Please refer the `AIMessage` and `LLMResult` schema documentation for
+ more information.
+ """
+
+ generations: list[ChatGeneration]
+ """List of the chat generations.
+
+ Generations is a list to allow for multiple candidate generations for a single
+ input prompt.
+ """
+
+ llm_output: dict | None = None
+ """For arbitrary model provider-specific output.
+
+ This dictionary is a free-form dictionary that can contain any information that the
+ provider wants to return. It is not standardized and keys may vary by provider and
+ over time.
+
+ Users should generally avoid relying on this field and instead rely on accessing
+ relevant information from standardized fields present in `AIMessage`.
+ """
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/generation.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..246b68c1fc2b77debcaa7267304856be7ef916b4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/generation.py
@@ -0,0 +1,80 @@
+"""Generation output schema."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from langchain_core.load import Serializable
+from langchain_core.utils._merge import merge_dicts
+
+
+class Generation(Serializable):
+ """A single text generation output.
+
+ Generation represents the response from an "old-fashioned" LLM (string-in,
+ string-out) that generates regular text (not chat messages).
+
+ This model is used internally by chat model and will eventually be mapped to a more
+ general `LLMResult` object, and then projected into an `AIMessage` object.
+
+ LangChain users working with chat models will usually access information via
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks). Please refer to `AIMessage` and `LLMResult` for more information.
+ """
+
+ text: str
+ """Generated text output."""
+
+ generation_info: dict[str, Any] | None = None
+ """Raw response from the provider.
+
+ May include things like the reason for finishing or token log probabilities.
+ """
+
+ type: Literal["Generation"] = "Generation"
+ """Type is used exclusively for serialization purposes.
+
+ Set to `'Generation'` for this class.
+ """
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "output"]`
+ """
+ return ["langchain", "schema", "output"]
+
+
+class GenerationChunk(Generation):
+ """`GenerationChunk`, which can be concatenated with other `Generation` chunks."""
+
+ def __add__(self, other: GenerationChunk) -> GenerationChunk:
+ """Concatenate two `GenerationChunk` objects.
+
+ Args:
+ other: Another `GenerationChunk` to concatenate with.
+
+ Raises:
+ TypeError: If other is not a `GenerationChunk`.
+
+ Returns:
+ A new `GenerationChunk` concatenated from self and other.
+ """
+ if isinstance(other, GenerationChunk):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ other.generation_info or {},
+ )
+ return GenerationChunk(
+ text=self.text + other.text,
+ generation_info=generation_info or None,
+ )
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/llm_result.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/llm_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..df40c41975089b293463988ba2558fd31a8bd8fb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/llm_result.py
@@ -0,0 +1,112 @@
+"""`LLMResult` class."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Literal
+
+from pydantic import BaseModel
+
+from langchain_core.outputs.chat_generation import ChatGeneration, ChatGenerationChunk
+from langchain_core.outputs.generation import Generation, GenerationChunk
+from langchain_core.outputs.run_info import RunInfo
+
+
+class LLMResult(BaseModel):
+ """A container for results of an LLM call.
+
+ Both chat models and LLMs generate an `LLMResult` object. This object contains the
+ generated outputs and any additional information that the model provider wants to
+ return.
+ """
+
+ generations: list[
+ list[Generation | ChatGeneration | GenerationChunk | ChatGenerationChunk]
+ ]
+ """Generated outputs.
+
+ The first dimension of the list represents completions for different input prompts.
+
+ The second dimension of the list represents different candidate generations for a
+ given prompt.
+
+ - When returned from **an LLM**, the type is `list[list[Generation]]`.
+ - When returned from a **chat model**, the type is `list[list[ChatGeneration]]`.
+
+ `ChatGeneration` is a subclass of `Generation` that has a field for a structured
+ chat message.
+ """
+
+ llm_output: dict | None = None
+ """For arbitrary model provider-specific output.
+
+ This dictionary is a free-form dictionary that can contain any information that the
+ provider wants to return. It is not standardized and keys may vary by provider and
+ over time.
+
+ Users should generally avoid relying on this field and instead rely on accessing
+ relevant information from standardized fields present in AIMessage.
+ """
+
+ run: list[RunInfo] | None = None
+ """List of metadata info for model call for each input.
+
+ See `langchain_core.outputs.run_info.RunInfo` for details.
+ """
+
+ type: Literal["LLMResult"] = "LLMResult"
+ """Type is used exclusively for serialization purposes."""
+
+ def flatten(self) -> list[LLMResult]:
+ """Flatten generations into a single list.
+
+ Unpack `list[list[Generation]] -> list[LLMResult]` where each returned
+ `LLMResult` contains only a single `Generation`. If token usage information is
+ available, it is kept only for the `LLMResult` corresponding to the top-choice
+ `Generation`, to avoid over-counting of token usage downstream.
+
+ Returns:
+ List of `LLMResult` objects where each returned `LLMResult` contains a
+ single `Generation`.
+ """
+ llm_results = []
+ for i, gen_list in enumerate(self.generations):
+ # Avoid double counting tokens in OpenAICallback
+ if i == 0:
+ llm_results.append(
+ LLMResult(
+ generations=[gen_list],
+ llm_output=self.llm_output,
+ )
+ )
+ else:
+ if self.llm_output is not None:
+ llm_output = deepcopy(self.llm_output)
+ llm_output["token_usage"] = {}
+ else:
+ llm_output = None
+ llm_results.append(
+ LLMResult(
+ generations=[gen_list],
+ llm_output=llm_output,
+ )
+ )
+ return llm_results
+
+ def __eq__(self, other: object) -> bool:
+ """Check for `LLMResult` equality by ignoring any metadata related to runs.
+
+ Args:
+ other: Another `LLMResult` object to compare against.
+
+ Returns:
+ `True` if the generations and `llm_output` are equal, `False` otherwise.
+ """
+ if not isinstance(other, LLMResult):
+ return NotImplemented
+ return (
+ self.generations == other.generations
+ and self.llm_output == other.llm_output
+ )
+
+ __hash__ = None # type: ignore[assignment]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/outputs/run_info.py b/python/user_packages/Python313/site-packages/langchain_core/outputs/run_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8bbca14555562447d6ccbe28520cfbd74671273
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/outputs/run_info.py
@@ -0,0 +1,22 @@
+"""`RunInfo` class."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from pydantic import BaseModel
+
+
+class RunInfo(BaseModel):
+ """Class that contains metadata for a single execution of a chain or model.
+
+ Defined for backwards compatibility with older versions of `langchain_core`.
+
+ !!! warning "This model will likely be deprecated in the future."
+
+ Users can acquire the `run_id` information from callbacks or via `run_id`
+ information present in the `astream_event` API (depending on the use case).
+ """
+
+ run_id: UUID
+ """A unique identifier for the model or chain run."""
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..772ed40d19d6b3a2569a31d71214771a1ba18112
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/__init__.py
@@ -0,0 +1,101 @@
+"""A prompt is the input to the model.
+
+Prompt is often constructed from multiple components and prompt values. Prompt classes
+and functions make constructing and working with prompts easy.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.prompts.base import (
+ BasePromptTemplate,
+ aformat_document,
+ format_document,
+ )
+ from langchain_core.prompts.chat import (
+ AIMessagePromptTemplate,
+ BaseChatPromptTemplate,
+ ChatMessagePromptTemplate,
+ ChatPromptTemplate,
+ HumanMessagePromptTemplate,
+ MessagesPlaceholder,
+ SystemMessagePromptTemplate,
+ )
+ from langchain_core.prompts.dict import DictPromptTemplate
+ from langchain_core.prompts.few_shot import (
+ FewShotChatMessagePromptTemplate,
+ FewShotPromptTemplate,
+ )
+ from langchain_core.prompts.few_shot_with_templates import (
+ FewShotPromptWithTemplates,
+ )
+ from langchain_core.prompts.loading import load_prompt
+ from langchain_core.prompts.prompt import PromptTemplate
+ from langchain_core.prompts.string import (
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+ jinja2_formatter,
+ validate_jinja2,
+ )
+
+__all__ = (
+ "AIMessagePromptTemplate",
+ "BaseChatPromptTemplate",
+ "BasePromptTemplate",
+ "ChatMessagePromptTemplate",
+ "ChatPromptTemplate",
+ "DictPromptTemplate",
+ "FewShotChatMessagePromptTemplate",
+ "FewShotPromptTemplate",
+ "FewShotPromptWithTemplates",
+ "HumanMessagePromptTemplate",
+ "MessagesPlaceholder",
+ "PromptTemplate",
+ "StringPromptTemplate",
+ "SystemMessagePromptTemplate",
+ "aformat_document",
+ "check_valid_template",
+ "format_document",
+ "get_template_variables",
+ "jinja2_formatter",
+ "load_prompt",
+ "validate_jinja2",
+)
+
+_dynamic_imports = {
+ "BasePromptTemplate": "base",
+ "format_document": "base",
+ "aformat_document": "base",
+ "AIMessagePromptTemplate": "chat",
+ "BaseChatPromptTemplate": "chat",
+ "ChatMessagePromptTemplate": "chat",
+ "ChatPromptTemplate": "chat",
+ "DictPromptTemplate": "dict",
+ "HumanMessagePromptTemplate": "chat",
+ "MessagesPlaceholder": "chat",
+ "SystemMessagePromptTemplate": "chat",
+ "FewShotChatMessagePromptTemplate": "few_shot",
+ "FewShotPromptTemplate": "few_shot",
+ "FewShotPromptWithTemplates": "few_shot_with_templates",
+ "load_prompt": "loading",
+ "PromptTemplate": "prompt",
+ "StringPromptTemplate": "string",
+ "check_valid_template": "string",
+ "get_template_variables": "string",
+ "jinja2_formatter": "string",
+ "validate_jinja2": "string",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af412a590394a2383b19ad95889d8e2bba277534
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82c1bd0fc721d9d97f863d8d7a09fc8796528bce
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/chat.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/chat.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7126b4a9c05fe7a99491e7122d441878f1695ee4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/chat.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/dict.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/dict.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63d53437c8171dbe0d5c33fbd9e7514e86c58cf8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/dict.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a77775a5ae8d537e4c30d5a050ac11b82fffd78
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..505d8764070b9d119cc87de4fafa5b62722d8c4d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/image.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/image.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..199734773a3171a6e1473294d31ad1cda0299b35
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/image.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/loading.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/loading.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8714ffb7fd2d674ca8b3434f7dbc4656059cf107
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/loading.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/message.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/message.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2125f6c81e2f6dc667e0828902fc35fc71ad3c6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/message.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4b802ea48748515f22b7d8ca73925d82b6d4e0a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/string.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/string.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2dfb692e39fec6956f02fcbcbb478937d5724af
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/string.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/structured.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/structured.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1d313ea316f2a990ec83e35ddddce089de29108
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/prompts/__pycache__/structured.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/base.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..c96c936d80f167685df6f80b418fd604b51f0957
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/base.py
@@ -0,0 +1,478 @@
+"""Base class for prompt templates."""
+
+from __future__ import annotations
+
+import builtins # noqa: TC003
+import contextlib
+import json
+from abc import ABC, abstractmethod
+from collections.abc import Mapping # noqa: TC003
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
+
+import yaml
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core._api import deprecated
+from langchain_core.exceptions import ErrorCode, create_message
+from langchain_core.load import dumpd
+from langchain_core.output_parsers.base import BaseOutputParser # noqa: TC001
+from langchain_core.prompt_values import (
+ ChatPromptValueConcrete,
+ PromptValue,
+ StringPromptValue,
+)
+from langchain_core.runnables import RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import ensure_config
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from langchain_core.documents import Document
+
+
+FormatOutputType = TypeVar("FormatOutputType")
+
+
+class BasePromptTemplate(
+ RunnableSerializable[dict, PromptValue], ABC, Generic[FormatOutputType]
+):
+ """Base class for all prompt templates, returning a prompt."""
+
+ input_variables: list[str]
+ """A list of the names of the variables whose values are required as inputs to the
+ prompt.
+ """
+
+ optional_variables: list[str] = Field(default=[])
+ """A list of the names of the variables for placeholder or `MessagePlaceholder` that
+ are optional.
+
+ These variables are auto inferred from the prompt and user need not provide them.
+ """
+
+ input_types: builtins.dict[str, Any] = Field(default_factory=dict, exclude=True)
+ """A dictionary of the types of the variables the prompt template expects.
+
+ If not provided, all variables are assumed to be strings.
+ """
+
+ output_parser: BaseOutputParser | None = None
+ """How to parse the output of calling an LLM on this formatted prompt."""
+
+ partial_variables: Mapping[str, Any] = Field(default_factory=dict)
+ """A dictionary of the partial variables the prompt template carries.
+
+ Partial variables populate the template so that you don't need to pass them in every
+ time you call the prompt.
+ """
+
+ metadata: builtins.dict[str, Any] | None = None
+ """Metadata to be used for tracing."""
+
+ tags: list[str] | None = None
+ """Tags to be used for tracing."""
+
+ @model_validator(mode="after")
+ def validate_variable_names(self) -> Self:
+ """Validate variable names do not include restricted names."""
+ if "stop" in self.input_variables:
+ msg = (
+ "Cannot have an input variable named 'stop', as it is used internally,"
+ " please rename."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ if "stop" in self.partial_variables:
+ msg = (
+ "Cannot have an partial variable named 'stop', as it is used "
+ "internally, please rename."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+
+ overall = set(self.input_variables).intersection(self.partial_variables)
+ if overall:
+ msg = f"Found overlapping input and partial variables: {overall}"
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return self
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "prompt_template"]`
+ """
+ return ["langchain", "schema", "prompt_template"]
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumpd uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """Return the output type of the prompt."""
+ return StringPromptValue | ChatPromptValueConcrete
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema for the prompt.
+
+ Args:
+ config: Configuration for the prompt.
+
+ Returns:
+ The input schema for the prompt.
+ """
+ # This is correct, but pydantic typings/mypy don't think so.
+ required_input_variables = {
+ k: (self.input_types.get(k, str), ...) for k in self.input_variables
+ }
+ optional_input_variables = {
+ k: (self.input_types.get(k, str), None) for k in self.optional_variables
+ }
+ return create_model_v2(
+ "PromptInput",
+ field_definitions={**required_input_variables, **optional_input_variables},
+ )
+
+ def _validate_input(self, inner_input: Any) -> dict:
+ if not isinstance(inner_input, dict):
+ if len(self.input_variables) == 1:
+ var_name = self.input_variables[0]
+ inner_input_ = {var_name: inner_input}
+
+ else:
+ msg = (
+ f"Expected mapping type as input to {self.__class__.__name__}. "
+ f"Received {type(inner_input)}."
+ )
+ raise TypeError(
+ create_message(
+ message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT
+ )
+ )
+ else:
+ inner_input_ = inner_input
+ missing = set(self.input_variables).difference(inner_input_)
+ if missing:
+ msg = (
+ f"Input to {self.__class__.__name__} is missing variables {missing}. "
+ f" Expected: {self.input_variables}"
+ f" Received: {list(inner_input_.keys())}"
+ )
+ example_key = missing.pop()
+ msg += (
+ f"\nNote: if you intended {{{example_key}}} to be part of the string"
+ " and not a variable, please escape it with double curly braces like: "
+ f"'{{{{{example_key}}}}}'."
+ )
+ raise KeyError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return inner_input_
+
+ def _format_prompt_with_error_handling(self, inner_input: dict) -> PromptValue:
+ inner_input_ = self._validate_input(inner_input)
+ return self.format_prompt(**inner_input_)
+
+ async def _aformat_prompt_with_error_handling(
+ self, inner_input: dict
+ ) -> PromptValue:
+ inner_input_ = self._validate_input(inner_input)
+ return await self.aformat_prompt(**inner_input_)
+
+ @override
+ def invoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> PromptValue:
+ """Invoke the prompt.
+
+ Args:
+ input: Input to the prompt.
+ config: Configuration for the prompt.
+
+ Returns:
+ The output of the prompt.
+ """
+ config = ensure_config(config)
+ if self.metadata:
+ config["metadata"] = {**config["metadata"], **self.metadata}
+ if self.tags:
+ config["tags"] += self.tags
+ return self._call_with_config(
+ self._format_prompt_with_error_handling,
+ input,
+ config,
+ run_type="prompt",
+ serialized=self._serialized,
+ )
+
+ @override
+ async def ainvoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> PromptValue:
+ """Async invoke the prompt.
+
+ Args:
+ input: Input to the prompt.
+ config: Configuration for the prompt.
+
+ Returns:
+ The output of the prompt.
+ """
+ config = ensure_config(config)
+ if self.metadata:
+ config["metadata"].update(self.metadata)
+ if self.tags:
+ config["tags"].extend(self.tags)
+ return await self._acall_with_config(
+ self._aformat_prompt_with_error_handling,
+ input,
+ config,
+ run_type="prompt",
+ serialized=self._serialized,
+ )
+
+ @abstractmethod
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Create `PromptValue`.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ The output of the prompt.
+ """
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async create `PromptValue`.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ The output of the prompt.
+ """
+ return self.format_prompt(**kwargs)
+
+ def partial(self, **kwargs: str | Callable[[], str]) -> BasePromptTemplate:
+ """Return a partial of the prompt template.
+
+ Args:
+ **kwargs: Partial variables to set.
+
+ Returns:
+ A partial of the prompt template.
+ """
+ prompt_dict = self.__dict__.copy()
+ prompt_dict["input_variables"] = list(
+ set(self.input_variables).difference(kwargs)
+ )
+ prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
+ return type(self)(**prompt_dict)
+
+ def _merge_partial_and_user_variables(self, **kwargs: Any) -> dict[str, Any]:
+ # Get partial params:
+ partial_kwargs = {
+ k: v if not callable(v) else v() for k, v in self.partial_variables.items()
+ }
+ return {**partial_kwargs, **kwargs}
+
+ @abstractmethod
+ def format(self, **kwargs: Any) -> FormatOutputType:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+
+ async def aformat(self, **kwargs: Any) -> FormatOutputType:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ await prompt.aformat(variable1="foo")
+ ```
+ """
+ return self.format(**kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ raise NotImplementedError
+
+ def dict(self, **kwargs: Any) -> dict:
+ """Return dictionary representation of prompt.
+
+ Args:
+ **kwargs: Any additional arguments to pass to the dictionary.
+
+ Returns:
+ Dictionary representation of the prompt.
+ """
+ prompt_dict = super().model_dump(**kwargs)
+ with contextlib.suppress(NotImplementedError):
+ prompt_dict["_type"] = self._prompt_type
+ return prompt_dict
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt.
+
+ Args:
+ file_path: Path to directory to save prompt to.
+
+ Raises:
+ ValueError: If the prompt has partial variables.
+ ValueError: If the file path is not json or yaml.
+ NotImplementedError: If the prompt type is not implemented.
+
+ Example:
+ ```python
+ prompt.save(file_path="path/prompt.yaml")
+ ```
+ """
+ if self.partial_variables:
+ msg = "Cannot save prompt with partial variables."
+ raise ValueError(msg)
+
+ # Fetch dictionary to save
+ prompt_dict = self.dict()
+ if "_type" not in prompt_dict:
+ msg = f"Prompt {self} does not support saving."
+ raise NotImplementedError(msg)
+
+ # Convert file to Path object.
+ save_path = Path(file_path)
+
+ directory_path = save_path.parent
+ directory_path.mkdir(parents=True, exist_ok=True)
+
+ resolved_path = save_path.resolve()
+ if resolved_path.suffix == ".json":
+ with resolved_path.open("w", encoding="utf-8") as f:
+ json.dump(prompt_dict, f, indent=4)
+ elif resolved_path.suffix.endswith((".yaml", ".yml")):
+ with resolved_path.open("w", encoding="utf-8") as f:
+ yaml.dump(prompt_dict, f, default_flow_style=False)
+ else:
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
+
+
+def _get_document_info(doc: Document, prompt: BasePromptTemplate[str]) -> dict:
+ base_info = {"page_content": doc.page_content, **doc.metadata}
+ missing_metadata = set(prompt.input_variables).difference(base_info)
+ if len(missing_metadata) > 0:
+ required_metadata = [
+ iv for iv in prompt.input_variables if iv != "page_content"
+ ]
+ msg = (
+ f"Document prompt requires documents to have metadata variables: "
+ f"{required_metadata}. Received document with missing metadata: "
+ f"{list(missing_metadata)}."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return {k: base_info[k] for k in prompt.input_variables}
+
+
+def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
+ """Format a document into a string based on a prompt template.
+
+ First, this pulls information from the document from two sources:
+
+ 1. `page_content`: This takes the information from the `document.page_content` and
+ assigns it to a variable named `page_content`.
+ 2. `metadata`: This takes information from `document.metadata` and assigns it to
+ variables of the same name.
+
+ Those variables are then passed into the `prompt` to produce a formatted string.
+
+ Args:
+ doc: `Document`, the `page_content` and `metadata` will be used to create the
+ final string.
+ prompt: `BasePromptTemplate`, will be used to format the `page_content` and
+ `metadata` into the final string.
+
+ Returns:
+ String of the document formatted.
+
+ Example:
+ ```python
+ from langchain_core.documents import Document
+ from langchain_core.prompts import PromptTemplate
+
+ doc = Document(page_content="This is a joke", metadata={"page": "1"})
+ prompt = PromptTemplate.from_template("Page {page}: {page_content}")
+ format_document(doc, prompt)
+ # -> "Page 1: This is a joke"
+ ```
+ """
+ return prompt.format(**_get_document_info(doc, prompt))
+
+
+async def aformat_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
+ """Async format a document into a string based on a prompt template.
+
+ First, this pulls information from the document from two sources:
+
+ 1. `page_content`: This takes the information from the `document.page_content` and
+ assigns it to a variable named `page_content`.
+ 2. `metadata`: This takes information from `document.metadata` and assigns it to
+ variables of the same name.
+
+ Those variables are then passed into the `prompt` to produce a formatted string.
+
+ Args:
+ doc: `Document`, the `page_content` and `metadata` will be used to create the
+ final string.
+ prompt: `BasePromptTemplate`, will be used to format the `page_content` and
+ `metadata` into the final string.
+
+ Returns:
+ String of the document formatted.
+ """
+ return await prompt.aformat(**_get_document_info(doc, prompt))
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/chat.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebd58c80319e50c91cd3a2632db7cd8d0b374fe5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/chat.py
@@ -0,0 +1,1491 @@
+"""Chat prompt template."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Sequence
+from pathlib import Path
+from typing import (
+ Annotated,
+ Any,
+ TypedDict,
+ TypeVar,
+ cast,
+ overload,
+)
+
+from pydantic import (
+ Field,
+ PositiveInt,
+ SkipValidation,
+ model_validator,
+)
+from typing_extensions import Self, override
+
+from langchain_core._api import deprecated
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+ convert_to_messages,
+)
+from langchain_core.messages.base import get_msg_title_repr
+from langchain_core.prompt_values import ChatPromptValue, ImageURL
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.dict import DictPromptTemplate
+from langchain_core.prompts.image import ImagePromptTemplate
+from langchain_core.prompts.message import (
+ BaseMessagePromptTemplate,
+)
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ PromptTemplateFormat,
+ StringPromptTemplate,
+ get_template_variables,
+)
+from langchain_core.utils import get_colored_text
+from langchain_core.utils.interactive_env import is_interactive_env
+
+
+class MessagesPlaceholder(BaseMessagePromptTemplate):
+ """Prompt template that assumes variable is already list of messages.
+
+ A placeholder which can be used to pass in a list of messages.
+
+ !!! example "Direct usage"
+
+ ```python
+ from langchain_core.prompts import MessagesPlaceholder
+
+ prompt = MessagesPlaceholder("history")
+ prompt.format_messages() # raises KeyError
+
+ prompt = MessagesPlaceholder("history", optional=True)
+ prompt.format_messages() # returns empty list []
+
+ prompt.format_messages(
+ history=[
+ ("system", "You are an AI assistant."),
+ ("human", "Hello!"),
+ ]
+ )
+ # -> [
+ # SystemMessage(content="You are an AI assistant."),
+ # HumanMessage(content="Hello!"),
+ # ]
+ ```
+
+ !!! example "Building a prompt with chat history"
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are a helpful assistant."),
+ MessagesPlaceholder("history"),
+ ("human", "{question}"),
+ ]
+ )
+ prompt.invoke(
+ {
+ "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
+ "question": "now multiply that by 4",
+ }
+ )
+ # -> ChatPromptValue(messages=[
+ # SystemMessage(content="You are a helpful assistant."),
+ # HumanMessage(content="what's 5 + 2"),
+ # AIMessage(content="5 + 2 is 7"),
+ # HumanMessage(content="now multiply that by 4"),
+ # ])
+ ```
+
+ !!! example "Limiting the number of messages"
+
+ ```python
+ from langchain_core.prompts import MessagesPlaceholder
+
+ prompt = MessagesPlaceholder("history", n_messages=1)
+
+ prompt.format_messages(
+ history=[
+ ("system", "You are an AI assistant."),
+ ("human", "Hello!"),
+ ]
+ )
+ # -> [
+ # HumanMessage(content="Hello!"),
+ # ]
+ ```
+ """
+
+ variable_name: str
+ """Name of variable to use as messages."""
+
+ optional: bool = False
+ """Whether `format_messages` must be provided.
+
+ If `True` `format_messages` can be called with no arguments and will return an empty
+ list.
+
+ If `False` then a named argument with name `variable_name` must be passed in, even
+ if the value is an empty list.
+ """
+
+ n_messages: PositiveInt | None = None
+ """Maximum number of messages to include.
+
+ If `None`, then will include all.
+ """
+
+ def __init__(
+ self, variable_name: str, *, optional: bool = False, **kwargs: Any
+ ) -> None:
+ """Create a messages placeholder.
+
+ Args:
+ variable_name: Name of variable to use as messages.
+ optional: Whether `format_messages` must be provided.
+
+ If `True` format_messages can be called with no arguments and will
+ return an empty list.
+
+ If `False` then a named argument with name `variable_name` must be
+ passed in, even if the value is an empty list.
+ """
+ # mypy can't detect the init which is defined in the parent class
+ # b/c these are BaseModel classes.
+ super().__init__(variable_name=variable_name, optional=optional, **kwargs) # type: ignore[call-arg,unused-ignore]
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+
+ Raises:
+ ValueError: If variable is not a list of messages.
+ """
+ value = (
+ kwargs.get(self.variable_name, [])
+ if self.optional
+ else kwargs[self.variable_name]
+ )
+ if not isinstance(value, list):
+ msg = (
+ f"variable {self.variable_name} should be a list of base messages, "
+ f"got {value} of type {type(value)}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ value = convert_to_messages(value)
+ if self.n_messages:
+ value = value[-self.n_messages :]
+ return value
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ return [self.variable_name] if not self.optional else []
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ var = "{" + self.variable_name + "}"
+ if html:
+ title = get_msg_title_repr("Messages Placeholder", bold=True)
+ var = get_colored_text(var, "yellow")
+ else:
+ title = get_msg_title_repr("Messages Placeholder")
+ return f"{title}\n\n{var}"
+
+
+MessagePromptTemplateT = TypeVar(
+ "MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate"
+)
+"""Type variable for message prompt templates."""
+
+
+class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
+ """Base class for message prompt templates that use a string prompt template."""
+
+ prompt: StringPromptTemplate
+ """String prompt template."""
+
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Additional keyword arguments to pass to the prompt template."""
+
+ @classmethod
+ def from_template(
+ cls,
+ template: str,
+ template_format: PromptTemplateFormat = "f-string",
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a string template.
+
+ Args:
+ template: a template.
+ template_format: format of the template.
+ partial_variables: A dictionary of variables that can be used to partially
+ fill in the template.
+
+ For example, if the template is `"{variable1} {variable2}"`, and
+ `partial_variables` is `{"variable1": "foo"}`, then the final prompt
+ will be `"foo {variable2}"`.
+
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt = PromptTemplate.from_template(
+ template,
+ template_format=template_format,
+ partial_variables=partial_variables,
+ )
+ return cls(prompt=prompt, **kwargs)
+
+ @classmethod
+ def from_template_file(
+ cls,
+ template_file: str | Path,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a template file.
+
+ Args:
+ template_file: path to a template file.
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt = PromptTemplate.from_file(template_file)
+ return cls(prompt=prompt, **kwargs)
+
+ @abstractmethod
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ return self.format(**kwargs)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [self.format(**kwargs)]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [await self.aformat(**kwargs)]
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ return self.prompt.input_variables
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: Handle partials
+ title = self.__class__.__name__.replace("MessagePromptTemplate", " Message")
+ title = get_msg_title_repr(title, bold=html)
+ return f"{title}\n\n{self.prompt.pretty_repr(html=html)}"
+
+
+class ChatMessagePromptTemplate(BaseStringMessagePromptTemplate):
+ """Chat message prompt template."""
+
+ role: str
+ """Role of the message."""
+
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ text = self.prompt.format(**kwargs)
+ return ChatMessage(
+ content=text, role=self.role, additional_kwargs=self.additional_kwargs
+ )
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ text = await self.prompt.aformat(**kwargs)
+ return ChatMessage(
+ content=text, role=self.role, additional_kwargs=self.additional_kwargs
+ )
+
+
+class _TextTemplateParam(TypedDict, total=False):
+ text: str | dict
+
+
+class _ImageTemplateParam(TypedDict, total=False):
+ image_url: str | dict
+
+
+class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
+ """Human message prompt template. This is a message sent from the user."""
+
+ prompt: (
+ StringPromptTemplate
+ | list[StringPromptTemplate | ImagePromptTemplate | DictPromptTemplate]
+ )
+ """Prompt template."""
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Additional keyword arguments to pass to the prompt template."""
+
+ _msg_class: type[BaseMessage]
+
+ @classmethod
+ def from_template(
+ cls: type[Self],
+ template: str
+ | list[str | _TextTemplateParam | _ImageTemplateParam | dict[str, Any]],
+ template_format: PromptTemplateFormat = "f-string",
+ *,
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a string template.
+
+ Args:
+ template: a template.
+ template_format: format of the template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ partial_variables: A dictionary of variables that can be used too partially.
+
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+
+ Raises:
+ ValueError: If the template is not a string or list of strings.
+ """
+ if isinstance(template, str):
+ prompt: StringPromptTemplate | list = PromptTemplate.from_template(
+ template,
+ template_format=template_format,
+ partial_variables=partial_variables,
+ )
+ return cls(prompt=prompt, **kwargs)
+ if isinstance(template, list):
+ if (partial_variables is not None) and len(partial_variables) > 0:
+ msg = "Partial variables are not supported for list of templates."
+ raise ValueError(msg)
+ prompt = []
+ for tmpl in template:
+ if isinstance(tmpl, str) or (
+ isinstance(tmpl, dict)
+ and "text" in tmpl
+ and set(tmpl.keys()) <= {"type", "text"}
+ ):
+ if isinstance(tmpl, str):
+ text: str = tmpl
+ else:
+ text = cast("_TextTemplateParam", tmpl)["text"] # type: ignore[assignment]
+ prompt.append(
+ PromptTemplate.from_template(
+ text, template_format=template_format
+ )
+ )
+ elif (
+ isinstance(tmpl, dict)
+ and "image_url" in tmpl
+ and set(tmpl.keys())
+ <= {
+ "type",
+ "image_url",
+ }
+ ):
+ img_template = cast("_ImageTemplateParam", tmpl)["image_url"]
+ input_variables = []
+ if isinstance(img_template, str):
+ variables = get_template_variables(
+ img_template, template_format
+ )
+ if variables:
+ if len(variables) > 1:
+ msg = (
+ "Only one format variable allowed per image"
+ f" template.\nGot: {variables}"
+ f"\nFrom: {tmpl}"
+ )
+ raise ValueError(msg)
+ input_variables = [variables[0]]
+ img_template = {"url": img_template}
+ img_template_obj = ImagePromptTemplate(
+ input_variables=input_variables,
+ template=img_template,
+ template_format=template_format,
+ )
+ elif isinstance(img_template, dict):
+ img_template = dict(img_template)
+ for key in ["url", "path", "detail"]:
+ if key in img_template:
+ input_variables.extend(
+ get_template_variables(
+ img_template[key], template_format
+ )
+ )
+ img_template_obj = ImagePromptTemplate(
+ input_variables=input_variables,
+ template=img_template,
+ template_format=template_format,
+ )
+ else:
+ msg = f"Invalid image template: {tmpl}"
+ raise ValueError(msg)
+ prompt.append(img_template_obj)
+ elif isinstance(tmpl, dict):
+ if template_format == "jinja2":
+ msg = (
+ "jinja2 is unsafe and is not supported for templates "
+ "expressed as dicts. Please use 'f-string' or 'mustache' "
+ "format."
+ )
+ raise ValueError(msg)
+ data_template_obj = DictPromptTemplate(
+ template=cast("dict[str, Any]", tmpl),
+ template_format=template_format,
+ )
+ prompt.append(data_template_obj)
+ else:
+ msg = f"Invalid template: {tmpl}"
+ raise ValueError(msg)
+ return cls(prompt=prompt, **kwargs)
+ msg = f"Invalid template: {template}"
+ raise ValueError(msg)
+
+ @classmethod
+ def from_template_file(
+ cls: type[Self],
+ template_file: str | Path,
+ input_variables: list[str],
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a template file.
+
+ Args:
+ template_file: path to a template file.
+ input_variables: list of input variables.
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ template = Path(template_file).read_text(encoding="utf-8")
+ return cls.from_template(template, input_variables=input_variables, **kwargs)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [self.format(**kwargs)]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [await self.aformat(**kwargs)]
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ prompts = self.prompt if isinstance(self.prompt, list) else [self.prompt]
+ return [iv for prompt in prompts for iv in prompt.input_variables]
+
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ if isinstance(self.prompt, StringPromptTemplate):
+ text = self.prompt.format(**kwargs)
+ return self._msg_class(
+ content=text, additional_kwargs=self.additional_kwargs
+ )
+ content: list = []
+ for prompt in self.prompt:
+ inputs = {var: kwargs[var] for var in prompt.input_variables}
+ if isinstance(prompt, StringPromptTemplate):
+ formatted_text: str = prompt.format(**inputs)
+ if formatted_text != "":
+ content.append({"type": "text", "text": formatted_text})
+ elif isinstance(prompt, ImagePromptTemplate):
+ formatted_image: ImageURL = prompt.format(**inputs)
+ content.append({"type": "image_url", "image_url": formatted_image})
+ elif isinstance(prompt, DictPromptTemplate):
+ formatted_dict: dict[str, Any] = prompt.format(**inputs)
+ content.append(formatted_dict)
+ return self._msg_class(
+ content=content, additional_kwargs=self.additional_kwargs
+ )
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ if isinstance(self.prompt, StringPromptTemplate):
+ text = await self.prompt.aformat(**kwargs)
+ return self._msg_class(
+ content=text, additional_kwargs=self.additional_kwargs
+ )
+ content: list = []
+ for prompt in self.prompt:
+ inputs = {var: kwargs[var] for var in prompt.input_variables}
+ if isinstance(prompt, StringPromptTemplate):
+ formatted_text: str = await prompt.aformat(**inputs)
+ if formatted_text != "":
+ content.append({"type": "text", "text": formatted_text})
+ elif isinstance(prompt, ImagePromptTemplate):
+ formatted_image: ImageURL = await prompt.aformat(**inputs)
+ content.append({"type": "image_url", "image_url": formatted_image})
+ elif isinstance(prompt, DictPromptTemplate):
+ formatted_dict: dict[str, Any] = prompt.format(**inputs)
+ content.append(formatted_dict)
+ return self._msg_class(
+ content=content, additional_kwargs=self.additional_kwargs
+ )
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: Handle partials
+ title = self.__class__.__name__.replace("MessagePromptTemplate", " Message")
+ title = get_msg_title_repr(title, bold=html)
+ prompts = self.prompt if isinstance(self.prompt, list) else [self.prompt]
+ prompt_reprs = "\n\n".join(prompt.pretty_repr(html=html) for prompt in prompts)
+ return f"{title}\n\n{prompt_reprs}"
+
+
+class HumanMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """Human message prompt template.
+
+ This is a message sent from the user.
+ """
+
+ _msg_class: type[BaseMessage] = HumanMessage
+
+
+class AIMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """AI message prompt template.
+
+ This is a message sent from the AI.
+ """
+
+ _msg_class: type[BaseMessage] = AIMessage
+
+
+class SystemMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """System message prompt template.
+
+ This is a message that is not sent to the user.
+ """
+
+ _msg_class: type[BaseMessage] = SystemMessage
+
+
+class BaseChatPromptTemplate(BasePromptTemplate, ABC):
+ """Base class for chat prompt templates."""
+
+ @property
+ @override
+ def lc_attributes(self) -> dict:
+ return {"input_variables": self.input_variables}
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the chat template into a string.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables in all
+ the template messages in this chat template.
+
+ Returns:
+ Formatted string.
+ """
+ return self.format_prompt(**kwargs).to_string()
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the chat template into a string.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables in all
+ the template messages in this chat template.
+
+ Returns:
+ Formatted string.
+ """
+ return (await self.aformat_prompt(**kwargs)).to_string()
+
+ def format_prompt(self, **kwargs: Any) -> ChatPromptValue:
+ """Format prompt.
+
+ Should return a `ChatPromptValue`.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+ """
+ messages = self.format_messages(**kwargs)
+ return ChatPromptValue(messages=messages)
+
+ async def aformat_prompt(self, **kwargs: Any) -> ChatPromptValue:
+ """Async format prompt.
+
+ Should return a `ChatPromptValue`.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+ """
+ messages = await self.aformat_messages(**kwargs)
+ return ChatPromptValue(messages=messages)
+
+ @abstractmethod
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format kwargs into a list of messages.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format kwargs into a list of messages.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return self.format_messages(**kwargs)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+ def pretty_print(self) -> None:
+ """Print a human-readable representation."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+MessageLike = BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate
+
+MessageLikeRepresentation = (
+ MessageLike
+ | tuple[str | type, str | Sequence[dict] | Sequence[object]]
+ | str
+ | dict[str, Any]
+)
+
+
+class ChatPromptTemplate(BaseChatPromptTemplate):
+ """Prompt template for chat models.
+
+ Use to create flexible templated prompts for chat models.
+
+ !!! example
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot. Your name is {name}."),
+ ("human", "Hello, how are you doing?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "{user_input}"),
+ ]
+ )
+
+ prompt_value = template.invoke(
+ {
+ "name": "Bob",
+ "user_input": "What is your name?",
+ }
+ )
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
+ # HumanMessage(content='Hello, how are you doing?'),
+ # AIMessage(content="I'm doing well, thanks!"),
+ # HumanMessage(content='What is your name?')
+ # ]
+ # )
+ ```
+
+ !!! note "Messages Placeholder"
+
+ ```python
+ # In addition to Human/AI/Tool/Function messages,
+ # you can initialize the template with a MessagesPlaceholder
+ # either using the class directly or with the shorthand tuple syntax:
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot."),
+ # Means the template will receive an optional list of messages under
+ # the "conversation" key
+ ("placeholder", "{conversation}"),
+ # Equivalently:
+ # MessagesPlaceholder(variable_name="conversation", optional=True)
+ ]
+ )
+
+ prompt_value = template.invoke(
+ {
+ "conversation": [
+ ("human", "Hi!"),
+ ("ai", "How can I assist you today?"),
+ ("human", "Can you make me an ice cream sundae?"),
+ ("ai", "No."),
+ ]
+ }
+ )
+
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot.'),
+ # HumanMessage(content='Hi!'),
+ # AIMessage(content='How can I assist you today?'),
+ # HumanMessage(content='Can you make me an ice cream sundae?'),
+ # AIMessage(content='No.'),
+ # ]
+ # )
+ ```
+
+ !!! note "Single-variable template"
+
+ If your prompt has only a single input variable (i.e., one instance of
+ `'{variable_nams}'`), and you invoke the template with a non-dict object, the
+ prompt template will inject the provided argument into that variable location.
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot. Your name is Carl."),
+ ("human", "{user_input}"),
+ ]
+ )
+
+ prompt_value = template.invoke("Hello, there!")
+ # Equivalent to
+ # prompt_value = template.invoke({"user_input": "Hello, there!"})
+
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot. Your name is Carl.'),
+ # HumanMessage(content='Hello, there!'),
+ # ]
+ # )
+ ```
+ """
+
+ messages: Annotated[list[MessageLike], SkipValidation()]
+ """List of messages consisting of either message prompt templates or messages."""
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ def __init__(
+ self,
+ messages: Sequence[MessageLikeRepresentation],
+ *,
+ template_format: PromptTemplateFormat = "f-string",
+ **kwargs: Any,
+ ) -> None:
+ """Create a chat prompt template from a variety of message formats.
+
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g.,
+ `'{user_input}'`
+ template_format: Format of the template.
+ **kwargs: Additional keyword arguments passed to `BasePromptTemplate`,
+ including (but not limited to):
+
+ - `input_variables`: A list of the names of the variables whose values
+ are required as inputs to the prompt.
+ - `optional_variables`: A list of the names of the variables for
+ placeholder or `MessagePlaceholder` that are optional.
+
+ These variables are auto inferred from the prompt and user need not
+ provide them.
+
+ - `partial_variables`: A dictionary of the partial variables the prompt
+ template carries.
+
+ Partial variables populate the template so that you don't need to
+ pass them in every time you call the prompt.
+
+ - `validate_template`: Whether to validate the template.
+ - `input_types`: A dictionary of the types of the variables the prompt
+ template expects.
+
+ If not provided, all variables are assumed to be strings.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ template = ChatPromptTemplate(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ]
+ )
+ ```
+
+ Instantiation from mixed message formats:
+
+ ```python
+ template = ChatPromptTemplate(
+ [
+ SystemMessage(content="hello"),
+ ("human", "Hello, how are you?"),
+ ]
+ )
+ ```
+ """
+ messages_ = [
+ _convert_to_message_template(message, template_format)
+ for message in messages
+ ]
+
+ # Automatically infer input variables from messages
+ input_vars: set[str] = set()
+ optional_variables: set[str] = set()
+ partial_vars: dict[str, Any] = {}
+ for message in messages_:
+ if isinstance(message, MessagesPlaceholder) and message.optional:
+ partial_vars[message.variable_name] = []
+ optional_variables.add(message.variable_name)
+ elif isinstance(
+ message, (BaseChatPromptTemplate, BaseMessagePromptTemplate)
+ ):
+ input_vars.update(message.input_variables)
+
+ kwargs = {
+ "input_variables": sorted(input_vars),
+ "optional_variables": sorted(optional_variables),
+ "partial_variables": partial_vars,
+ **kwargs,
+ }
+ cast("type[ChatPromptTemplate]", super()).__init__(messages=messages_, **kwargs)
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "chat"]`
+ """
+ return ["langchain", "prompts", "chat"]
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Combine two prompt templates.
+
+ Args:
+ other: Another prompt template.
+
+ Returns:
+ Combined prompt template.
+ """
+ partials = {**self.partial_variables}
+
+ # Need to check that other has partial variables since it may not be
+ # a ChatPromptTemplate.
+ if hasattr(other, "partial_variables") and other.partial_variables:
+ partials.update(other.partial_variables)
+
+ # Allow for easy combining
+ if isinstance(other, ChatPromptTemplate):
+ return ChatPromptTemplate(messages=self.messages + other.messages).partial(
+ **partials
+ )
+ if isinstance(
+ other, (BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate)
+ ):
+ return ChatPromptTemplate(messages=[*self.messages, other]).partial(
+ **partials
+ )
+ if isinstance(other, (list, tuple)):
+ other_ = ChatPromptTemplate.from_messages(other)
+ return ChatPromptTemplate(messages=self.messages + other_.messages).partial(
+ **partials
+ )
+ if isinstance(other, str):
+ prompt = HumanMessagePromptTemplate.from_template(other)
+ return ChatPromptTemplate(messages=[*self.messages, prompt]).partial(
+ **partials
+ )
+ msg = f"Unsupported operand type for +: {type(other)}"
+ raise NotImplementedError(msg)
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_input_variables(cls, values: dict) -> Any:
+ """Validate input variables.
+
+ If `input_variables` is not set, it will be set to the union of all input
+ variables in the messages.
+
+ Args:
+ values: values to validate.
+
+ Returns:
+ Validated values.
+
+ Raises:
+ ValueError: If input variables do not match.
+ """
+ messages = values["messages"]
+ input_vars: set = set()
+ optional_variables = set()
+ input_types: dict[str, Any] = values.get("input_types", {})
+ for message in messages:
+ if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):
+ input_vars.update(message.input_variables)
+ if isinstance(message, MessagesPlaceholder):
+ if "partial_variables" not in values:
+ values["partial_variables"] = {}
+ if (
+ message.optional
+ and message.variable_name not in values["partial_variables"]
+ ):
+ values["partial_variables"][message.variable_name] = []
+ optional_variables.add(message.variable_name)
+ if message.variable_name not in input_types:
+ input_types[message.variable_name] = list[AnyMessage]
+ if "partial_variables" in values:
+ input_vars -= set(values["partial_variables"])
+ if optional_variables:
+ input_vars -= optional_variables
+ if "input_variables" in values and values.get("validate_template"):
+ if input_vars != set(values["input_variables"]):
+ msg = (
+ "Got mismatched input_variables. "
+ f"Expected: {input_vars}. "
+ f"Got: {values['input_variables']}"
+ )
+ raise ValueError(msg)
+ else:
+ values["input_variables"] = sorted(input_vars)
+ if optional_variables:
+ values["optional_variables"] = sorted(optional_variables)
+ values["input_types"] = input_types
+ return values
+
+ @classmethod
+ def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
+ """Create a chat prompt template from a template string.
+
+ Creates a chat template consisting of a single message assumed to be from the
+ human.
+
+ Args:
+ template: Template string
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt_template = PromptTemplate.from_template(template, **kwargs)
+ message = HumanMessagePromptTemplate(prompt=prompt_template)
+ return cls.from_messages([message])
+
+ @classmethod
+ def from_messages(
+ cls,
+ messages: Sequence[MessageLikeRepresentation],
+ template_format: PromptTemplateFormat = "f-string",
+ ) -> ChatPromptTemplate:
+ """Create a chat prompt template from a variety of message formats.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ]
+ )
+ ```
+
+ Instantiation from mixed message formats:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ SystemMessage(content="hello"),
+ ("human", "Hello, how are you?"),
+ ]
+ )
+ ```
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g.,
+ `'{user_input}'`
+ template_format: Format of the template.
+
+ Returns:
+ A chat prompt template.
+
+ """
+ return cls(messages, template_format=template_format)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format the chat template into a list of finalized messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables
+ in all the template messages in this chat template.
+
+ Raises:
+ ValueError: If messages are of unexpected types.
+
+ Returns:
+ List of formatted messages.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ result = []
+ for message_template in self.messages:
+ if isinstance(message_template, BaseMessage):
+ result.extend([message_template])
+ elif isinstance(
+ message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)
+ ):
+ message = message_template.format_messages(**kwargs)
+ result.extend(message)
+ else:
+ msg = f"Unexpected input: {message_template}"
+ raise ValueError(msg) # noqa: TRY004
+ return result
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format the chat template into a list of finalized messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables
+ in all the template messages in this chat template.
+
+ Returns:
+ List of formatted messages.
+
+ Raises:
+ ValueError: If unexpected input.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ result = []
+ for message_template in self.messages:
+ if isinstance(message_template, BaseMessage):
+ result.extend([message_template])
+ elif isinstance(
+ message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)
+ ):
+ message = await message_template.aformat_messages(**kwargs)
+ result.extend(message)
+ else:
+ msg = f"Unexpected input: {message_template}"
+ raise ValueError(msg) # noqa:TRY004
+ return result
+
+ def partial(self, **kwargs: Any) -> ChatPromptTemplate:
+ """Get a new `ChatPromptTemplate` with some input variables already filled in.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables.
+
+ Ought to be a subset of the input variables.
+
+ Returns:
+ A new `ChatPromptTemplate`.
+
+ Example:
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are an AI assistant named {name}."),
+ ("human", "Hi I'm {user}"),
+ ("ai", "Hi there, {user}, I'm {name}."),
+ ("human", "{input}"),
+ ]
+ )
+ template2 = template.partial(user="Lucy", name="R2D2")
+
+ template2.format_messages(input="hello")
+ ```
+ """
+ prompt_dict = self.__dict__.copy()
+ prompt_dict["input_variables"] = list(
+ set(self.input_variables).difference(kwargs)
+ )
+ prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
+ return type(self)(**prompt_dict)
+
+ def append(self, message: MessageLikeRepresentation) -> None:
+ """Append a message to the end of the chat template.
+
+ Args:
+ message: representation of a message to append.
+ """
+ self.messages.append(_convert_to_message_template(message))
+
+ def extend(self, messages: Sequence[MessageLikeRepresentation]) -> None:
+ """Extend the chat template with a sequence of messages.
+
+ Args:
+ messages: Sequence of message representations to append.
+ """
+ self.messages.extend(
+ [_convert_to_message_template(message) for message in messages]
+ )
+
+ @overload
+ def __getitem__(self, index: int) -> MessageLike: ...
+
+ @overload
+ def __getitem__(self, index: slice) -> ChatPromptTemplate: ...
+
+ def __getitem__(self, index: int | slice) -> MessageLike | ChatPromptTemplate:
+ """Use to index into the chat template.
+
+ Returns:
+ If index is an int, returns the message at that index.
+
+ If index is a slice, returns a new `ChatPromptTemplate` containing the
+ messages in that slice.
+ """
+ if isinstance(index, slice):
+ start, stop, step = index.indices(len(self.messages))
+ messages = self.messages[start:stop:step]
+ return ChatPromptTemplate.from_messages(messages)
+ return self.messages[index]
+
+ def __len__(self) -> int:
+ """Return the length of the chat template."""
+ return len(self.messages)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Name of prompt type. Used for serialization."""
+ return "chat"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save prompt to file.
+
+ Args:
+ file_path: path to file.
+ """
+ raise NotImplementedError
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: handle partials
+ return "\n\n".join(msg.pretty_repr(html=html) for msg in self.messages)
+
+
+def _create_template_from_message_type(
+ message_type: str,
+ template: str | list,
+ template_format: PromptTemplateFormat = "f-string",
+) -> BaseMessagePromptTemplate:
+ """Create a message prompt template from a message type and template string.
+
+ Args:
+ message_type: The type of the message template (e.g., `'human'`, `'ai'`, etc.)
+ template: The template string.
+ template_format: Format of the template.
+
+ Returns:
+ A message prompt template of the appropriate type.
+
+ Raises:
+ ValueError: If unexpected message type.
+ """
+ if message_type in {"human", "user"}:
+ message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(
+ template, template_format=template_format
+ )
+ elif message_type in {"ai", "assistant"}:
+ message = AIMessagePromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ elif message_type == "system":
+ message = SystemMessagePromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ elif message_type == "placeholder":
+ if isinstance(template, str):
+ if template[0] != "{" or template[-1] != "}":
+ msg = (
+ f"Invalid placeholder template: {template}."
+ " Expected a variable name surrounded by curly braces."
+ )
+ raise ValueError(msg)
+ var_name = template[1:-1]
+ message = MessagesPlaceholder(variable_name=var_name, optional=True)
+ else:
+ try:
+ var_name_wrapped, is_optional = template
+ except ValueError as e:
+ msg = (
+ "Unexpected arguments for placeholder message type."
+ " Expected either a single string variable name"
+ " or a list of [variable_name: str, is_optional: bool]."
+ f" Got: {template}"
+ )
+ raise ValueError(msg) from e
+
+ if not isinstance(is_optional, bool):
+ msg = f"Expected is_optional to be a boolean. Got: {is_optional}"
+ raise ValueError(msg) # noqa: TRY004
+
+ if not isinstance(var_name_wrapped, str):
+ msg = f"Expected variable name to be a string. Got: {var_name_wrapped}"
+ raise ValueError(msg) # noqa: TRY004
+ if var_name_wrapped[0] != "{" or var_name_wrapped[-1] != "}":
+ msg = (
+ f"Invalid placeholder template: {var_name_wrapped}."
+ " Expected a variable name surrounded by curly braces."
+ )
+ raise ValueError(msg)
+ var_name = var_name_wrapped[1:-1]
+
+ message = MessagesPlaceholder(variable_name=var_name, optional=is_optional)
+ else:
+ msg = (
+ f"Unexpected message type: {message_type}. Use one of 'human',"
+ f" 'user', 'ai', 'assistant', or 'system'."
+ )
+ raise ValueError(msg)
+ return message
+
+
+def _convert_to_message_template(
+ message: MessageLikeRepresentation,
+ template_format: PromptTemplateFormat = "f-string",
+) -> BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate:
+ """Instantiate a message from a variety of message formats.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g., `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g., `'{user_input}'`
+
+ Args:
+ message: A representation of a message in one of the supported formats.
+ template_format: Format of the template.
+
+ Returns:
+ An instance of a message or a message template.
+
+ Raises:
+ ValueError: If unexpected message type.
+ ValueError: If 2-tuple does not have 2 elements.
+ """
+ if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):
+ message_: BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate = (
+ message
+ )
+ elif isinstance(message, BaseMessage):
+ message_ = message
+ elif isinstance(message, str):
+ message_ = _create_template_from_message_type(
+ "human", message, template_format=template_format
+ )
+ elif isinstance(message, (tuple, dict)):
+ if isinstance(message, dict):
+ if set(message.keys()) != {"content", "role"}:
+ msg = (
+ "Expected dict to have exact keys 'role' and 'content'."
+ f" Got: {message}"
+ )
+ raise ValueError(msg)
+ message_type_str = message["role"]
+ template = message["content"]
+ else:
+ if len(message) != 2: # noqa: PLR2004
+ msg = f"Expected 2-tuple of (role, template), got {message}"
+ raise ValueError(msg)
+ message_type_str, template = message
+
+ if isinstance(message_type_str, str):
+ message_ = _create_template_from_message_type(
+ message_type_str, template, template_format=template_format
+ )
+ elif (
+ hasattr(message_type_str, "model_fields")
+ and "type" in message_type_str.model_fields
+ ):
+ message_type = message_type_str.model_fields["type"].default
+ message_ = _create_template_from_message_type(
+ message_type, template, template_format=template_format
+ )
+ else:
+ message_ = message_type_str(
+ prompt=PromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ )
+ else:
+ msg = f"Unsupported message type: {type(message)}"
+ raise NotImplementedError(msg)
+
+ return message_
+
+
+# For backwards compat:
+_convert_to_message = _convert_to_message_template
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/dict.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a665bfbb836f9c467bdd48f61e1f80ad1169cc0
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/dict.py
@@ -0,0 +1,175 @@
+"""Dictionary prompt template."""
+
+import warnings
+from functools import cached_property
+from typing import Any, Literal, cast
+
+from pydantic import model_validator
+from typing_extensions import override
+
+from langchain_core.load import dumpd
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ get_template_variables,
+)
+from langchain_core.runnables import RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import ensure_config
+
+
+class DictPromptTemplate(RunnableSerializable[dict, dict]):
+ """Template represented by a dictionary.
+
+ Recognizes variables in f-string or mustache formatted string dict values.
+
+ Does NOT recognize variables in dict keys. Applies recursively.
+
+ Example:
+ ```python
+ prompt = DictPromptTemplate(
+ template={
+ "type": "text",
+ "text": "Hello {name}",
+ "metadata": {"source": "{source}"},
+ },
+ template_format="f-string",
+ )
+ prompt.format(name="Alice", source="docs")
+ # {
+ # "type": "text",
+ # "text": "Hello Alice",
+ # "metadata": {"source": "docs"},
+ # }
+ ```
+ """
+
+ template: dict[str, Any]
+ template_format: Literal["f-string", "mustache"]
+
+ @model_validator(mode="after")
+ def validate_template(self) -> "DictPromptTemplate":
+ """Validate that the template structure contains only safe variables."""
+ _get_input_variables(self.template, self.template_format)
+ return self
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Template input variables."""
+ return _get_input_variables(self.template, self.template_format)
+
+ def format(self, **kwargs: Any) -> dict[str, Any]:
+ """Format the prompt with the inputs.
+
+ Returns:
+ A formatted dict.
+ """
+ return _insert_input_variables(self.template, kwargs, self.template_format)
+
+ async def aformat(self, **kwargs: Any) -> dict[str, Any]:
+ """Format the prompt with the inputs.
+
+ Returns:
+ A formatted dict.
+ """
+ return self.format(**kwargs)
+
+ @override
+ def invoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> dict:
+ return self._call_with_config(
+ lambda x: self.format(**x),
+ input,
+ ensure_config(config),
+ run_type="prompt",
+ serialized=self._serialized,
+ **kwargs,
+ )
+
+ @property
+ def _prompt_type(self) -> str:
+ return "dict-prompt"
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumpd uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain_core", "prompts", "dict"]`
+ """
+ return ["langchain_core", "prompts", "dict"]
+
+ def pretty_repr(self, *, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+
+def _get_input_variables(
+ template: dict, template_format: Literal["f-string", "mustache"]
+) -> list[str]:
+ input_variables = []
+ for v in template.values():
+ if isinstance(v, str):
+ input_variables += get_template_variables(v, template_format)
+ elif isinstance(v, dict):
+ input_variables += _get_input_variables(v, template_format)
+ elif isinstance(v, (list, tuple)):
+ for x in v:
+ if isinstance(x, str):
+ input_variables += get_template_variables(x, template_format)
+ elif isinstance(x, dict):
+ input_variables += _get_input_variables(x, template_format)
+ return list(set(input_variables))
+
+
+def _insert_input_variables(
+ template: dict[str, Any],
+ inputs: dict[str, Any],
+ template_format: Literal["f-string", "mustache"],
+) -> dict[str, Any]:
+ formatted: dict[str, Any] = {}
+ formatter = DEFAULT_FORMATTER_MAPPING[template_format]
+ for k, v in template.items():
+ if isinstance(v, str):
+ formatted[k] = formatter(v, **inputs)
+ elif isinstance(v, dict):
+ if k == "image_url" and "path" in v:
+ msg = (
+ "Specifying image inputs via file path in environments with "
+ "user-input paths is a security vulnerability. Out of an abundance "
+ "of caution, the utility has been removed to prevent possible "
+ "misuse."
+ )
+ warnings.warn(msg, stacklevel=2)
+ formatted[k] = _insert_input_variables(v, inputs, template_format)
+ elif isinstance(v, (list, tuple)):
+ formatted_v: list[str | dict[str, Any]] = []
+ for x in v:
+ if isinstance(x, str):
+ formatted_v.append(formatter(x, **inputs))
+ elif isinstance(x, dict):
+ formatted_v.append(
+ _insert_input_variables(x, inputs, template_format)
+ )
+ formatted[k] = type(v)(formatted_v)
+ else:
+ formatted[k] = v
+ return formatted
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e8e9aa3159664a896741d48d6ee9001cf2c51c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot.py
@@ -0,0 +1,483 @@
+"""Prompt template that contains few shot examples."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ model_validator,
+)
+from typing_extensions import override
+
+from langchain_core._api import deprecated
+from langchain_core.example_selectors import BaseExampleSelector
+from langchain_core.messages import BaseMessage, get_buffer_string
+from langchain_core.prompts.chat import BaseChatPromptTemplate
+from langchain_core.prompts.message import BaseMessagePromptTemplate
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from typing_extensions import Self
+
+
+class _FewShotPromptTemplateMixin(BaseModel):
+ """Prompt template that contains few shot examples."""
+
+ examples: list[dict] | None = None
+ """Examples to format into the prompt.
+
+ Either this or `example_selector` should be provided.
+ """
+
+ example_selector: BaseExampleSelector | None = None
+ """`ExampleSelector` to choose the examples to format into the prompt.
+
+ Either this or `examples` should be provided.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_examples_and_selector(cls, values: dict) -> Any:
+ """Check that one and only one of `examples`/`example_selector` are provided.
+
+ Args:
+ values: The values to check.
+
+ Returns:
+ The values if they are valid.
+
+ Raises:
+ ValueError: If neither or both `examples` and `example_selector` are
+ provided.
+ ValueError: If both `examples` and `example_selector` are provided.
+ """
+ examples = values.get("examples")
+ example_selector = values.get("example_selector")
+ if examples and example_selector:
+ msg = "Only one of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ if examples is None and example_selector is None:
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ return values
+
+ def _get_examples(self, **kwargs: Any) -> list[dict]:
+ """Get the examples to use for formatting the prompt.
+
+ Args:
+ **kwargs: Keyword arguments to be passed to the example selector.
+
+ Returns:
+ List of examples.
+
+ Raises:
+ ValueError: If neither `examples` nor `example_selector` are provided.
+ """
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return self.example_selector.select_examples(kwargs)
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ async def _aget_examples(self, **kwargs: Any) -> list[dict]:
+ """Async get the examples to use for formatting the prompt.
+
+ Args:
+ **kwargs: Keyword arguments to be passed to the example selector.
+
+ Returns:
+ List of examples.
+
+ Raises:
+ ValueError: If neither `examples` nor `example_selector` are provided.
+ """
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return await self.example_selector.aselect_examples(kwargs)
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+
+class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
+ """Prompt template that contains few shot examples."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `False` as this class is not serializable."""
+ return False
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ example_prompt: PromptTemplate
+ """`PromptTemplate` used to format an individual example."""
+
+ suffix: str
+ """A prompt template string to put after the examples."""
+
+ example_separator: str = "\n\n"
+ """String separator used to join the prefix, the examples, and suffix."""
+
+ prefix: str = ""
+ """A prompt template string to put before the examples."""
+
+ template_format: Literal["f-string", "jinja2"] = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'jinja2'`.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize the few shot prompt template."""
+ if "input_variables" not in kwargs and "example_prompt" in kwargs:
+ kwargs["input_variables"] = kwargs["example_prompt"].input_variables
+ super().__init__(**kwargs)
+
+ @model_validator(mode="after")
+ def template_is_valid(self) -> Self:
+ """Check that prefix, suffix, and input variables are consistent."""
+ if self.validate_template:
+ check_valid_template(
+ self.prefix + self.suffix,
+ self.template_format,
+ self.input_variables + list(self.partial_variables),
+ )
+ elif self.template_format:
+ self.input_variables = [
+ var
+ for var in get_template_variables(
+ self.prefix + self.suffix, self.template_format
+ )
+ if var not in self.partial_variables
+ ]
+ return self
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ example_strings = [
+ self.example_prompt.format(**example) for example in examples
+ ]
+ # Create the overall template.
+ pieces = [self.prefix, *example_strings, self.suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ example_strings = [
+ await self.example_prompt.aformat(**example) for example in examples
+ ]
+ # Create the overall template.
+ pieces = [self.prefix, *example_strings, self.suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "few_shot"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt template to a file.
+
+ Args:
+ file_path: The path to save the prompt template to.
+
+ Raises:
+ ValueError: If `example_selector` is provided.
+ """
+ if self.example_selector:
+ msg = "Saving an example selector is not currently supported"
+ raise ValueError(msg)
+ return super().save(file_path)
+
+
+class FewShotChatMessagePromptTemplate(
+ BaseChatPromptTemplate, _FewShotPromptTemplateMixin
+):
+ """Chat prompt template that supports few-shot examples.
+
+ The high level structure of produced by this prompt template is a list of messages
+ consisting of prefix message(s), example message(s), and suffix message(s).
+
+ This structure enables creating a conversation with intermediate examples like:
+
+ ```txt
+ System: You are a helpful AI Assistant
+
+ Human: What is 2+2?
+
+ AI: 4
+
+ Human: What is 2+3?
+
+ AI: 5
+
+ Human: What is 4+4?
+ ```
+
+ This prompt template can be used to generate a fixed list of examples or else to
+ dynamically select examples based on the input.
+
+ Examples:
+ Prompt template with a fixed list of examples (matching the sample
+ conversation above):
+
+ ```python
+ from langchain_core.prompts import (
+ FewShotChatMessagePromptTemplate,
+ ChatPromptTemplate,
+ )
+
+ examples = [
+ {"input": "2+2", "output": "4"},
+ {"input": "2+3", "output": "5"},
+ ]
+
+ example_prompt = ChatPromptTemplate.from_messages(
+ [
+ ("human", "What is {input}?"),
+ ("ai", "{output}"),
+ ]
+ )
+
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
+ examples=examples,
+ # This is a prompt template used to format each individual example.
+ example_prompt=example_prompt,
+ )
+
+ final_prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are a helpful AI Assistant"),
+ few_shot_prompt,
+ ("human", "{input}"),
+ ]
+ )
+ final_prompt.format(input="What is 4+4?")
+ ```
+
+ Prompt template with dynamically selected examples:
+
+ ```python
+ from langchain_core.prompts import SemanticSimilarityExampleSelector
+ from langchain_core.embeddings import OpenAIEmbeddings
+ from langchain_core.vectorstores import Chroma
+
+ examples = [
+ {"input": "2+2", "output": "4"},
+ {"input": "2+3", "output": "5"},
+ {"input": "2+4", "output": "6"},
+ # ...
+ ]
+
+ to_vectorize = [" ".join(example.values()) for example in examples]
+ embeddings = OpenAIEmbeddings()
+ vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
+ example_selector = SemanticSimilarityExampleSelector(vectorstore=vectorstore)
+
+ from langchain_core import SystemMessage
+ from langchain_core.prompts import HumanMessagePromptTemplate
+ from langchain_core.prompts.few_shot import FewShotChatMessagePromptTemplate
+
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
+ # Which variable(s) will be passed to the example selector.
+ input_variables=["input"],
+ example_selector=example_selector,
+ # Define how each example will be formatted.
+ # In this case, each example will become 2 messages:
+ # 1 human, and 1 AI
+ example_prompt=(
+ HumanMessagePromptTemplate.from_template("{input}")
+ + AIMessagePromptTemplate.from_template("{output}")
+ ),
+ )
+ # Define the overall prompt.
+ final_prompt = (
+ SystemMessagePromptTemplate.from_template("You are a helpful AI Assistant")
+ + few_shot_prompt
+ + HumanMessagePromptTemplate.from_template("{input}")
+ )
+ # Show the prompt
+ print(final_prompt.format_messages(input="What's 3+3?")) # noqa: T201
+
+ # Use within an LLM
+ from langchain_core.chat_models import ChatAnthropic
+
+ chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
+ chain.invoke({"input": "What's 3+3?"})
+ ```
+ """
+
+ input_variables: list[str] = Field(default_factory=list)
+ """A list of the names of the variables the prompt template will use to pass to
+ the `example_selector`, if provided.
+ """
+
+ example_prompt: BaseMessagePromptTemplate | BaseChatPromptTemplate
+ """The class to format each example."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `False` as this class is not serializable."""
+ return False
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format kwargs into a list of messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in templates in messages.
+
+ Returns:
+ A list of formatted messages with all template variables filled in.
+ """
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ return [
+ message
+ for example in examples
+ for message in self.example_prompt.format_messages(**example)
+ ]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format kwargs into a list of messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in templates in messages.
+
+ Returns:
+ A list of formatted messages with all template variables filled in.
+ """
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ return [
+ message
+ for example in examples
+ for message in await self.example_prompt.aformat_messages(**example)
+ ]
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt consisting of
+ chat messages.
+
+ Useful for feeding into a string-based completion language model or debugging.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt
+ """
+ messages = self.format_messages(**kwargs)
+ return get_buffer_string(messages)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt consisting of
+ chat messages.
+
+ Useful for feeding into a string-based completion language model or debugging.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt
+ """
+ messages = await self.aformat_messages(**kwargs)
+ return get_buffer_string(messages)
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Return a pretty representation of the prompt template.
+
+ Args:
+ html: Whether or not to return an HTML formatted string.
+
+ Returns:
+ A pretty representation of the prompt template.
+ """
+ raise NotImplementedError
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot_with_templates.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot_with_templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca664cabee789a910e45d61eb6f8f96c17f7dad7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/few_shot_with_templates.py
@@ -0,0 +1,237 @@
+"""Prompt template that contains few shot examples."""
+
+from pathlib import Path
+from typing import Any
+
+from pydantic import ConfigDict, model_validator
+from typing_extensions import Self
+
+from langchain_core._api import deprecated
+from langchain_core.example_selectors import BaseExampleSelector
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ StringPromptTemplate,
+)
+
+
+class FewShotPromptWithTemplates(StringPromptTemplate):
+ """Prompt template that contains few shot examples."""
+
+ examples: list[dict] | None = None
+ """Examples to format into the prompt.
+
+ Either this or `example_selector` should be provided.
+ """
+
+ example_selector: BaseExampleSelector | None = None
+ """`ExampleSelector` to choose the examples to format into the prompt.
+
+ Either this or `examples` should be provided.
+ """
+
+ example_prompt: PromptTemplate
+ """`PromptTemplate` used to format an individual example."""
+
+ suffix: StringPromptTemplate
+ """A `PromptTemplate` to put after the examples."""
+
+ example_separator: str = "\n\n"
+ """String separator used to join the prefix, the examples, and suffix."""
+
+ prefix: StringPromptTemplate | None = None
+ """A `PromptTemplate` to put before the examples."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'jinja2'`, `'mustache'`.
+ """
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "few_shot_with_templates"]`
+ """
+ return ["langchain", "prompts", "few_shot_with_templates"]
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_examples_and_selector(cls, values: dict) -> Any:
+ """Check that one and only one of examples/example_selector are provided."""
+ examples = values.get("examples")
+ example_selector = values.get("example_selector")
+ if examples and example_selector:
+ msg = "Only one of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ if examples is None and example_selector is None:
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ return values
+
+ @model_validator(mode="after")
+ def template_is_valid(self) -> Self:
+ """Check that prefix, suffix, and input variables are consistent."""
+ if self.validate_template:
+ input_variables = self.input_variables
+ expected_input_variables = set(self.suffix.input_variables)
+ expected_input_variables |= set(self.partial_variables)
+ if self.prefix is not None:
+ expected_input_variables |= set(self.prefix.input_variables)
+ missing_vars = expected_input_variables.difference(input_variables)
+ if missing_vars:
+ msg = (
+ f"Got input_variables={input_variables}, but based on "
+ f"prefix/suffix expected {expected_input_variables}"
+ )
+ raise ValueError(msg)
+ else:
+ self.input_variables = sorted(
+ set(self.suffix.input_variables)
+ | set(self.prefix.input_variables if self.prefix else [])
+ - set(self.partial_variables)
+ )
+ return self
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def _get_examples(self, **kwargs: Any) -> list[dict]:
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return self.example_selector.select_examples(kwargs)
+ raise ValueError
+
+ async def _aget_examples(self, **kwargs: Any) -> list[dict]:
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return await self.example_selector.aselect_examples(kwargs)
+ raise ValueError
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ # Format the examples.
+ example_strings = [
+ self.example_prompt.format(**example) for example in examples
+ ]
+ # Create the overall prefix.
+ if self.prefix is None:
+ prefix = ""
+ else:
+ prefix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.prefix.input_variables
+ }
+ for k in prefix_kwargs:
+ kwargs.pop(k)
+ prefix = self.prefix.format(**prefix_kwargs)
+
+ # Create the overall suffix
+ suffix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.suffix.input_variables
+ }
+ for k in suffix_kwargs:
+ kwargs.pop(k)
+ suffix = self.suffix.format(
+ **suffix_kwargs,
+ )
+
+ pieces = [prefix, *example_strings, suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ # Format the examples.
+ example_strings = [
+ # We can use the sync method here as PromptTemplate doesn't block
+ self.example_prompt.format(**example)
+ for example in examples
+ ]
+ # Create the overall prefix.
+ if self.prefix is None:
+ prefix = ""
+ else:
+ prefix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.prefix.input_variables
+ }
+ for k in prefix_kwargs:
+ kwargs.pop(k)
+ prefix = await self.prefix.aformat(**prefix_kwargs)
+
+ # Create the overall suffix
+ suffix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.suffix.input_variables
+ }
+ for k in suffix_kwargs:
+ kwargs.pop(k)
+ suffix = await self.suffix.aformat(
+ **suffix_kwargs,
+ )
+
+ pieces = [prefix, *example_strings, suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "few_shot_with_templates"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt to a file.
+
+ Args:
+ file_path: The path to save the prompt to.
+
+ Raises:
+ ValueError: If `example_selector` is provided.
+ """
+ if self.example_selector:
+ msg = "Saving an example selector is not currently supported"
+ raise ValueError(msg)
+ return super().save(file_path)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/image.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee8c9421f2a641db54692a7085ad37a9cdd0d75f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/image.py
@@ -0,0 +1,177 @@
+"""Image prompt template for a multimodal model."""
+
+from typing import Any, Literal, cast
+
+from pydantic import Field
+
+from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ get_template_variables,
+)
+from langchain_core.runnables import run_in_executor
+
+
+class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
+ """Image prompt template for a multimodal model.
+
+ Example:
+ ```python
+ prompt = ImagePromptTemplate(
+ input_variables=["image_id"],
+ template={"url": "https://example.com/{image_id}.png", "detail": "high"},
+ template_format="f-string",
+ )
+ prompt.format(image_id="cat")
+ # {"url": "https://example.com/cat.png", "detail": "high"}
+ ```
+ """
+
+ template: dict = Field(default_factory=dict)
+ """Template for the prompt."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Create an image prompt template.
+
+ Raises:
+ ValueError: If the input variables contain `'url'`, `'path'`, or
+ `'detail'`.
+ """
+ if "input_variables" not in kwargs:
+ kwargs["input_variables"] = []
+
+ overlap = set(kwargs["input_variables"]) & {"url", "path", "detail"}
+ if overlap:
+ msg = (
+ "input_variables for the image template cannot contain"
+ " any of 'url', 'path', or 'detail'."
+ f" Found: {overlap}"
+ )
+ raise ValueError(msg)
+
+ template = kwargs.get("template", {})
+ template_format = kwargs.get("template_format", "f-string")
+ for value in template.values():
+ if isinstance(value, str):
+ get_template_variables(value, template_format)
+
+ super().__init__(**kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "image-prompt"
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "image"]`
+ """
+ return ["langchain", "prompts", "image"]
+
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return ImagePromptValue(image_url=self.format(**kwargs))
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return ImagePromptValue(image_url=await self.aformat(**kwargs))
+
+ def format(
+ self,
+ **kwargs: Any,
+ ) -> ImageURL:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Raises:
+ ValueError: If the url is not provided.
+ ValueError: If the url is not a string.
+ ValueError: If `'path'` is provided in the template or kwargs.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+ formatted = {}
+ for k, v in self.template.items():
+ if isinstance(v, str):
+ formatted[k] = DEFAULT_FORMATTER_MAPPING[self.template_format](
+ v, **kwargs
+ )
+ else:
+ formatted[k] = v
+ url = kwargs.get("url") or formatted.get("url")
+ if kwargs.get("path") or formatted.get("path"):
+ msg = (
+ "Loading images from 'path' has been removed as of 0.3.15 for security "
+ "reasons. Please specify images by 'url'."
+ )
+ raise ValueError(msg)
+ detail = kwargs.get("detail") or formatted.get("detail")
+ if not url:
+ msg = "Must provide url."
+ raise ValueError(msg)
+ if not isinstance(url, str):
+ msg = "url must be a string."
+ raise ValueError(msg) # noqa: TRY004
+ output: ImageURL = {"url": url}
+ if detail:
+ # Don't check literal values here: let the API check them
+ output["detail"] = cast("Literal['auto', 'low', 'high']", detail)
+ return output
+
+ async def aformat(self, **kwargs: Any) -> ImageURL:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return await run_in_executor(None, self.format, **kwargs)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Return a pretty representation of the prompt.
+
+ Args:
+ html: Whether to return an html formatted string.
+
+ Returns:
+ A pretty representation of the prompt.
+ """
+ raise NotImplementedError
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/loading.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/loading.py
new file mode 100644
index 0000000000000000000000000000000000000000..d130f9d8714041409d72ea5fc3385229bf34ab91
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/loading.py
@@ -0,0 +1,289 @@
+"""Load prompts."""
+
+import json
+import logging
+from collections.abc import Callable
+from pathlib import Path
+
+import yaml
+
+from langchain_core._api import deprecated
+from langchain_core.output_parsers.string import StrOutputParser
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.chat import ChatPromptTemplate
+from langchain_core.prompts.few_shot import FewShotPromptTemplate
+from langchain_core.prompts.prompt import PromptTemplate
+
+URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/prompts/"
+logger = logging.getLogger(__name__)
+
+
+def _validate_path(path: Path) -> None:
+ """Reject absolute paths and ``..`` traversal components.
+
+ Args:
+ path: The path to validate.
+
+ Raises:
+ ValueError: If the path is absolute or contains ``..`` components.
+ """
+ if path.is_absolute():
+ msg = (
+ f"Path '{path}' is absolute. Absolute paths are not allowed "
+ f"when loading prompt configurations to prevent path traversal "
+ f"attacks. Use relative paths instead, or pass "
+ f"`allow_dangerous_paths=True` if you trust the input."
+ )
+ raise ValueError(msg)
+ if ".." in path.parts:
+ msg = (
+ f"Path '{path}' contains '..' components. Directory traversal "
+ f"sequences are not allowed when loading prompt configurations. "
+ f"Use direct relative paths instead, or pass "
+ f"`allow_dangerous_paths=True` if you trust the input."
+ )
+ raise ValueError(msg)
+
+
+@deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+)
+def load_prompt_from_config(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> BasePromptTemplate:
+ """Load prompt from config dict.
+
+ Args:
+ config: Dict containing the prompt configuration.
+ allow_dangerous_paths: If ``False`` (default), file paths in the
+ config (such as ``template_path``, ``examples``, and
+ ``example_prompt_path``) are validated to reject absolute paths
+ and directory traversal (``..``) sequences. Set to ``True`` only
+ if you trust the source of the config.
+
+ Returns:
+ A `PromptTemplate` object.
+
+ Raises:
+ ValueError: If the prompt type is not supported.
+ """
+ if "_type" not in config:
+ logger.warning("No `_type` key found, defaulting to `prompt`.")
+ config_type = config.pop("_type", "prompt")
+
+ if config_type not in type_to_loader_dict:
+ msg = f"Loading {config_type} prompt not supported"
+ raise ValueError(msg)
+
+ prompt_loader = type_to_loader_dict[config_type]
+ return prompt_loader(config, allow_dangerous_paths=allow_dangerous_paths)
+
+
+def _load_template(
+ var_name: str, config: dict, *, allow_dangerous_paths: bool = False
+) -> dict:
+ """Load template from the path if applicable."""
+ # Check if template_path exists in config.
+ if f"{var_name}_path" in config:
+ # If it does, make sure template variable doesn't also exist.
+ if var_name in config:
+ msg = f"Both `{var_name}_path` and `{var_name}` cannot be provided."
+ raise ValueError(msg)
+ # Pop the template path from the config.
+ template_path = Path(config.pop(f"{var_name}_path"))
+ if not allow_dangerous_paths:
+ _validate_path(template_path)
+ # Resolve symlinks before checking the suffix so that a symlink named
+ # "exploit.txt" pointing to a non-.txt file is caught.
+ resolved_path = template_path.resolve()
+ # Load the template.
+ if resolved_path.suffix == ".txt":
+ template = resolved_path.read_text(encoding="utf-8")
+ else:
+ raise ValueError
+ # Set the template variable to the extracted variable.
+ config[var_name] = template
+ return config
+
+
+def _load_examples(config: dict, *, allow_dangerous_paths: bool = False) -> dict:
+ """Load examples if necessary."""
+ if isinstance(config["examples"], list):
+ pass
+ elif isinstance(config["examples"], str):
+ path = Path(config["examples"])
+ if not allow_dangerous_paths:
+ _validate_path(path)
+ with path.open(encoding="utf-8") as f:
+ if path.suffix == ".json":
+ examples = json.load(f)
+ elif path.suffix in {".yaml", ".yml"}:
+ examples = yaml.safe_load(f)
+ else:
+ msg = "Invalid file format. Only json or yaml formats are supported."
+ raise ValueError(msg)
+ config["examples"] = examples
+ else:
+ msg = "Invalid examples format. Only list or string are supported."
+ raise ValueError(msg) # noqa:TRY004
+ return config
+
+
+def _load_output_parser(config: dict) -> dict:
+ """Load output parser."""
+ if config_ := config.get("output_parser"):
+ if output_parser_type := config_.get("_type") != "default":
+ msg = f"Unsupported output parser {output_parser_type}"
+ raise ValueError(msg)
+ config["output_parser"] = StrOutputParser(**config_)
+ return config
+
+
+def _load_few_shot_prompt(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> FewShotPromptTemplate:
+ """Load the "few shot" prompt from the config."""
+ # Load the suffix and prefix templates.
+ config = _load_template(
+ "suffix", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ config = _load_template(
+ "prefix", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ # Load the example prompt.
+ if "example_prompt_path" in config:
+ if "example_prompt" in config:
+ msg = (
+ "Only one of example_prompt and example_prompt_path should "
+ "be specified."
+ )
+ raise ValueError(msg)
+ example_prompt_path = Path(config.pop("example_prompt_path"))
+ if not allow_dangerous_paths:
+ _validate_path(example_prompt_path)
+ config["example_prompt"] = load_prompt(
+ example_prompt_path, allow_dangerous_paths=allow_dangerous_paths
+ )
+ else:
+ config["example_prompt"] = load_prompt_from_config(
+ config["example_prompt"], allow_dangerous_paths=allow_dangerous_paths
+ )
+ # Load the examples.
+ config = _load_examples(config, allow_dangerous_paths=allow_dangerous_paths)
+ config = _load_output_parser(config)
+ return FewShotPromptTemplate(**config)
+
+
+def _load_prompt(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> PromptTemplate:
+ """Load the prompt template from config."""
+ # Load the template from disk if necessary.
+ config = _load_template(
+ "template", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ config = _load_output_parser(config)
+
+ template_format = config.get("template_format", "f-string")
+ if template_format == "jinja2":
+ # Disabled due to:
+ # https://github.com/langchain-ai/langchain/issues/4394
+ msg = (
+ f"Loading templates with '{template_format}' format is no longer supported "
+ f"since it can lead to arbitrary code execution. Please migrate to using "
+ f"the 'f-string' template format, which does not suffer from this issue."
+ )
+ raise ValueError(msg)
+
+ return PromptTemplate(**config)
+
+
+@deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+)
+def load_prompt(
+ path: str | Path,
+ encoding: str | None = None,
+ *,
+ allow_dangerous_paths: bool = False,
+) -> BasePromptTemplate:
+ """Unified method for loading a prompt from LangChainHub or local filesystem.
+
+ Args:
+ path: Path to the prompt file.
+ encoding: Encoding of the file.
+ allow_dangerous_paths: If ``False`` (default), file paths referenced
+ inside the loaded config (such as ``template_path``, ``examples``,
+ and ``example_prompt_path``) are validated to reject absolute paths
+ and directory traversal (``..``) sequences. Set to ``True`` only
+ if you trust the source of the config.
+
+ Returns:
+ A `PromptTemplate` object.
+
+ Raises:
+ RuntimeError: If the path is a LangChainHub path.
+ """
+ if isinstance(path, str) and path.startswith("lc://"):
+ msg = (
+ "Loading from the deprecated github-based Hub is no longer supported. "
+ "Please use the new LangChain Hub at https://smith.langchain.com/hub "
+ "instead."
+ )
+ raise RuntimeError(msg)
+ return _load_prompt_from_file(
+ path, encoding, allow_dangerous_paths=allow_dangerous_paths
+ )
+
+
+def _load_prompt_from_file(
+ file: str | Path,
+ encoding: str | None = None,
+ *,
+ allow_dangerous_paths: bool = False,
+) -> BasePromptTemplate:
+ """Load prompt from file."""
+ # Convert file to a Path object.
+ file_path = Path(file)
+ # Load from either json or yaml.
+ if file_path.suffix == ".json":
+ with file_path.open(encoding=encoding) as f:
+ config = json.load(f)
+ elif file_path.suffix.endswith((".yaml", ".yml")):
+ with file_path.open(encoding=encoding) as f:
+ config = yaml.safe_load(f)
+ else:
+ msg = f"Got unsupported file type {file_path.suffix}"
+ raise ValueError(msg)
+ # Load the prompt from the config now.
+ return load_prompt_from_config(config, allow_dangerous_paths=allow_dangerous_paths)
+
+
+def _load_chat_prompt(
+ config: dict,
+ *,
+ allow_dangerous_paths: bool = False, # noqa: ARG001
+) -> ChatPromptTemplate:
+ """Load chat prompt from config."""
+ messages = config.pop("messages")
+ template = messages[0]["prompt"].pop("template") if messages else None
+ config.pop("input_variables")
+
+ if not template:
+ msg = "Can't load chat prompt without template"
+ raise ValueError(msg)
+
+ return ChatPromptTemplate.from_template(template=template, **config)
+
+
+type_to_loader_dict: dict[str, Callable[..., BasePromptTemplate]] = {
+ "prompt": _load_prompt,
+ "few_shot": _load_few_shot_prompt,
+ "chat": _load_chat_prompt,
+}
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/message.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce20a4930183769996d9422f743992ee7da6c4b9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/message.py
@@ -0,0 +1,97 @@
+"""Message prompt templates."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.load import Serializable
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from langchain_core.messages import BaseMessage
+ from langchain_core.prompts.chat import ChatPromptTemplate
+
+
+class BaseMessagePromptTemplate(Serializable, ABC):
+ """Base class for message prompt templates."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "chat"]`
+ """
+ return ["langchain", "prompts", "chat"]
+
+ @abstractmethod
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Should return a list of `BaseMessage` objects.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return self.format_messages(**kwargs)
+
+ @property
+ @abstractmethod
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variables.
+ """
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+ def pretty_print(self) -> None:
+ """Print a human-readable representation."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Combine two prompt templates.
+
+ Args:
+ other: Another prompt template.
+
+ Returns:
+ Combined prompt template.
+ """
+ # Import locally to avoid circular import.
+ from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
+
+ prompt = ChatPromptTemplate(messages=[self])
+ return prompt.__add__(other)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/prompt.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/prompt.py
new file mode 100644
index 0000000000000000000000000000000000000000..cef55a5c2ff63120032e5d5402a9f36fee874a08
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/prompt.py
@@ -0,0 +1,312 @@
+"""Prompt schema definition."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel, model_validator
+from typing_extensions import override
+
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+ mustache_schema,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.config import RunnableConfig
+
+
+class PromptTemplate(StringPromptTemplate):
+ """Prompt template for a language model.
+
+ A prompt template consists of a string template. It accepts a set of parameters
+ from the user that can be used to generate a prompt for a language model.
+
+ The template can be formatted using either f-strings (default), jinja2, or mustache
+ syntax.
+
+ !!! warning "Security"
+
+ Prefer using `template_format='f-string'` instead of `template_format='jinja2'`,
+ or make sure to NEVER accept jinja2 templates from untrusted sources as they may
+ lead to arbitrary Python code execution.
+
+ As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
+ SandboxedEnvironment by default. This sand-boxing should be treated as a
+ best-effort approach rather than a guarantee of security, as it is an opt-out
+ rather than opt-in approach.
+
+ Despite the sandboxing, we recommend to never use jinja2 templates from
+ untrusted sources.
+
+ Example:
+ ```python
+ from langchain_core.prompts import PromptTemplate
+
+ # Instantiation using from_template (recommended)
+ prompt = PromptTemplate.from_template("Say {foo}")
+ prompt.format(foo="bar")
+
+ # Instantiation using initializer
+ prompt = PromptTemplate(template="Say {foo}")
+ ```
+ """
+
+ @property
+ @override
+ def lc_attributes(self) -> dict[str, Any]:
+ return {
+ "template_format": self.template_format,
+ }
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "prompt"]`
+ """
+ return ["langchain", "prompts", "prompt"]
+
+ template: str
+ """The prompt template."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ """
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def pre_init_validation(cls, values: dict) -> Any:
+ """Check that template and input variables are consistent."""
+ if values.get("template") is None:
+ # Will let pydantic fail with a ValidationError if template
+ # is not provided.
+ return values
+
+ # Set some default values based on the field defaults
+ values.setdefault("template_format", "f-string")
+ values.setdefault("partial_variables", {})
+
+ if values.get("validate_template"):
+ if values["template_format"] == "mustache":
+ msg = "Mustache templates cannot be validated."
+ raise ValueError(msg)
+
+ if "input_variables" not in values:
+ msg = "Input variables must be provided to validate the template."
+ raise ValueError(msg)
+
+ all_inputs = values["input_variables"] + list(values["partial_variables"])
+ check_valid_template(
+ values["template"], values["template_format"], all_inputs
+ )
+
+ if values["template_format"]:
+ values["input_variables"] = [
+ var
+ for var in get_template_variables(
+ values["template"], values["template_format"]
+ )
+ if var not in values["partial_variables"]
+ ]
+
+ return values
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema for the prompt.
+
+ Args:
+ config: The runnable configuration.
+
+ Returns:
+ The input schema for the prompt.
+ """
+ if self.template_format != "mustache":
+ return super().get_input_schema(config)
+
+ return mustache_schema(self.template)
+
+ def __add__(self, other: Any) -> PromptTemplate:
+ """Override the `+` operator to allow for combining prompt templates.
+
+ Raises:
+ ValueError: If the template formats are not f-string or if there are
+ conflicting partial variables.
+ NotImplementedError: If the other object is not a `PromptTemplate` or str.
+
+ Returns:
+ A new `PromptTemplate` that is the combination of the two.
+ """
+ # Allow for easy combining
+ if isinstance(other, PromptTemplate):
+ if self.template_format != other.template_format:
+ msg = "Cannot add templates of different formats"
+ raise ValueError(msg)
+ input_variables = list(
+ set(self.input_variables) | set(other.input_variables)
+ )
+ template = self.template + other.template
+ # If any do not want to validate, then don't
+ validate_template = self.validate_template and other.validate_template
+ partial_variables = dict(self.partial_variables.items())
+ for k, v in other.partial_variables.items():
+ if k in partial_variables:
+ msg = "Cannot have same variable partialed twice."
+ raise ValueError(msg)
+ partial_variables[k] = v
+ return PromptTemplate(
+ template=template,
+ input_variables=input_variables,
+ partial_variables=partial_variables,
+ template_format=self.template_format,
+ validate_template=validate_template,
+ )
+ if isinstance(other, str):
+ prompt = PromptTemplate.from_template(
+ other,
+ template_format=self.template_format,
+ )
+ return self + prompt
+ msg = f"Unsupported operand type for +: {type(other)}"
+ raise NotImplementedError(msg)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "prompt"
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[str],
+ suffix: str,
+ input_variables: list[str],
+ example_separator: str = "\n\n",
+ prefix: str = "",
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Take examples in list format with prefix and suffix to create a prompt.
+
+ Intended to be used as a way to dynamically create a prompt from examples.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ suffix: String to go after the list of examples.
+
+ Should generally set up the user's input.
+ input_variables: A list of variable names the final prompt template will
+ expect.
+ example_separator: The separator to use in between examples.
+ prefix: String that should go before any examples.
+
+ Generally includes examples.
+
+ Returns:
+ The final prompt generated.
+ """
+ template = example_separator.join([prefix, *examples, suffix])
+ return cls(input_variables=input_variables, template=template, **kwargs)
+
+ @classmethod
+ def from_file(
+ cls,
+ template_file: str | Path,
+ encoding: str | None = None,
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Load a prompt from a file.
+
+ Args:
+ template_file: The path to the file containing the prompt template.
+ encoding: The encoding system for opening the template file.
+
+ If not provided, will use the OS default.
+
+ Returns:
+ The prompt loaded from the file.
+ """
+ template = Path(template_file).read_text(encoding=encoding)
+ return cls.from_template(template=template, **kwargs)
+
+ @classmethod
+ def from_template(
+ cls,
+ template: str,
+ *,
+ template_format: PromptTemplateFormat = "f-string",
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Load a prompt template from a template.
+
+ !!! warning "Security"
+
+ Prefer using `template_format='f-string'` instead of
+ `template_format='jinja2'`, or make sure to NEVER accept jinja2 templates
+ from untrusted sources as they may lead to arbitrary Python code execution.
+
+ As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
+ SandboxedEnvironment by default. This sand-boxing should be treated as a
+ best-effort approach rather than a guarantee of security, as it is an
+ opt-out rather than opt-in approach.
+
+ Despite the sandboxing, we recommend to never use jinja2 templates from
+ untrusted sources.
+
+ Args:
+ template: The template to load.
+ template_format: The format of the template.
+
+ Use `jinja2` for jinja2, `mustache` for mustache, and `f-string` for
+ f-strings.
+ partial_variables: A dictionary of variables that can be used to partially
+ fill in the template.
+
+ For example, if the template is `'{variable1} {variable2}'`, and
+ `partial_variables` is `{"variable1": "foo"}`, then the final prompt
+ will be `'foo {variable2}'`.
+ **kwargs: Any other arguments to pass to the prompt template.
+
+ Returns:
+ The prompt template loaded from the template.
+ """
+ input_variables = get_template_variables(template, template_format)
+ partial_variables_ = partial_variables or {}
+
+ if partial_variables_:
+ input_variables = [
+ var for var in input_variables if var not in partial_variables_
+ ]
+
+ return cls(
+ input_variables=input_variables,
+ template=template,
+ template_format=template_format,
+ partial_variables=partial_variables_,
+ **kwargs,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/string.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/string.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37bdba22197c549e8a66362a55fc3b57a90018a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/string.py
@@ -0,0 +1,399 @@
+"""`BasePrompt` schema definition."""
+
+from __future__ import annotations
+
+import warnings
+from abc import ABC, abstractmethod
+from string import Formatter
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from pydantic import BaseModel, create_model
+from typing_extensions import override
+
+from langchain_core.prompt_values import PromptValue, StringPromptValue
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.utils import get_colored_text, mustache
+from langchain_core.utils.formatting import formatter
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Sequence
+
+try:
+ from jinja2 import meta
+ from jinja2.sandbox import SandboxedEnvironment
+
+ _HAS_JINJA2 = True
+except ImportError:
+ _HAS_JINJA2 = False
+
+PromptTemplateFormat = Literal["f-string", "mustache", "jinja2"]
+
+
+def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
+ """Format a template using jinja2.
+
+ !!! warning "Security"
+
+ As of LangChain 0.0.329, this method uses Jinja2's `SandboxedEnvironment` by
+ default. However, this sandboxing should be treated as a best-effort approach
+ rather than a guarantee of security.
+
+ Do not accept jinja2 templates from untrusted sources as they may lead
+ to arbitrary Python code execution.
+
+ [More information.](https://jinja.palletsprojects.com/en/3.1.x/sandbox/)
+
+ Args:
+ template: The template string.
+ **kwargs: The variables to format the template with.
+
+ Returns:
+ The formatted string.
+
+ Raises:
+ ImportError: If jinja2 is not installed.
+ """
+ if not _HAS_JINJA2:
+ msg = (
+ "jinja2 not installed, which is needed to use the jinja2_formatter. "
+ "Please install it with `pip install jinja2`."
+ "Please be cautious when using jinja2 templates. "
+ "Do not expand jinja2 templates using unverified or user-controlled "
+ "inputs as that can result in arbitrary Python code execution."
+ )
+ raise ImportError(msg)
+
+ # Use Jinja2's SandboxedEnvironment which blocks access to dunder attributes
+ # (e.g., __class__, __globals__) to prevent sandbox escapes.
+ # Note: regular attribute access (e.g., {{obj.attr}}) and method calls are
+ # still allowed. This is a best-effort measure — do not use with untrusted
+ # templates.
+ return SandboxedEnvironment().from_string(template).render(**kwargs)
+
+
+def validate_jinja2(template: str, input_variables: list[str]) -> None:
+ """Validate that the input variables are valid for the template.
+
+ Issues a warning if missing or extra variables are found.
+
+ Args:
+ template: The template string.
+ input_variables: The input variables.
+ """
+ input_variables_set = set(input_variables)
+ valid_variables = _get_jinja2_variables_from_template(template)
+ missing_variables = valid_variables - input_variables_set
+ extra_variables = input_variables_set - valid_variables
+
+ warning_message = ""
+ if missing_variables:
+ warning_message += f"Missing variables: {missing_variables} "
+
+ if extra_variables:
+ warning_message += f"Extra variables: {extra_variables}"
+
+ if warning_message:
+ warnings.warn(warning_message.strip(), stacklevel=7)
+
+
+def _get_jinja2_variables_from_template(template: str) -> set[str]:
+ if not _HAS_JINJA2:
+ msg = (
+ "jinja2 not installed, which is needed to use the jinja2_formatter. "
+ "Please install it with `pip install jinja2`."
+ )
+ raise ImportError(msg)
+ env = SandboxedEnvironment()
+ ast = env.parse(template)
+ return meta.find_undeclared_variables(ast)
+
+
+def mustache_formatter(template: str, /, **kwargs: Any) -> str:
+ """Format a template using mustache.
+
+ Args:
+ template: The template string.
+ **kwargs: The variables to format the template with.
+
+ Returns:
+ The formatted string.
+ """
+ return mustache.render(template, kwargs)
+
+
+def mustache_template_vars(
+ template: str,
+) -> set[str]:
+ """Get the top-level variables from a mustache template.
+
+ For nested variables like `{{person.name}}`, only the top-level key (`person`) is
+ returned.
+
+ Args:
+ template: The template string.
+
+ Returns:
+ The top-level variables from the template.
+ """
+ variables: set[str] = set()
+ section_depth = 0
+ for type_, key in mustache.tokenize(template):
+ if type_ == "end":
+ section_depth -= 1
+ elif (
+ type_ in {"variable", "section", "inverted section", "no escape"}
+ and key != "."
+ and section_depth == 0
+ ):
+ variables.add(key.split(".")[0])
+ if type_ in {"section", "inverted section"}:
+ section_depth += 1
+ return variables
+
+
+Defs = dict[str, "Defs"]
+
+
+def mustache_schema(template: str) -> type[BaseModel]:
+ """Get the variables from a mustache template.
+
+ Args:
+ template: The template string.
+
+ Returns:
+ The variables from the template as a Pydantic model.
+ """
+ fields = {}
+ prefix: tuple[str, ...] = ()
+ section_stack: list[tuple[str, ...]] = []
+ for type_, key in mustache.tokenize(template):
+ if key == ".":
+ continue
+ if type_ == "end":
+ if section_stack:
+ prefix = section_stack.pop()
+ elif type_ in {"section", "inverted section"}:
+ section_stack.append(prefix)
+ prefix += tuple(key.split("."))
+ fields[prefix] = False
+ elif type_ in {"variable", "no escape"}:
+ fields[prefix + tuple(key.split("."))] = True
+
+ for fkey, fval in fields.items():
+ fields[fkey] = fval and not any(
+ is_subsequence(fkey, k) for k in fields if k != fkey
+ )
+ defs: Defs = {} # None means leaf node
+ while fields:
+ field, is_leaf = fields.popitem()
+ current = defs
+ for part in field[:-1]:
+ current = current.setdefault(part, {})
+ current.setdefault(field[-1], "" if is_leaf else {}) # type: ignore[arg-type]
+ return _create_model_recursive("PromptInput", defs)
+
+
+def _create_model_recursive(name: str, defs: Defs) -> type[BaseModel]:
+ return cast(
+ "type[BaseModel]",
+ create_model( # type: ignore[call-overload]
+ name,
+ **{
+ k: (_create_model_recursive(k, v), None) if v else (type(v), None)
+ for k, v in defs.items()
+ },
+ ),
+ )
+
+
+DEFAULT_FORMATTER_MAPPING: dict[str, Callable[..., str]] = {
+ "f-string": formatter.format,
+ "mustache": mustache_formatter,
+ "jinja2": jinja2_formatter,
+}
+
+DEFAULT_VALIDATOR_MAPPING: dict[str, Callable] = {
+ "f-string": formatter.validate_input_variables,
+ "jinja2": validate_jinja2,
+}
+
+
+def _parse_f_string_fields(template: str) -> list[tuple[str, str | None]]:
+ fields: list[tuple[str, str | None]] = []
+ for _, field_name, format_spec, _ in Formatter().parse(template):
+ if field_name is not None:
+ fields.append((field_name, format_spec))
+ return fields
+
+
+def validate_f_string_template(template: str) -> list[str]:
+ """Validate an f-string template and return its input variables."""
+ input_variables = set()
+ for var, format_spec in _parse_f_string_fields(template):
+ if "." in var or "[" in var or "]" in var:
+ msg = (
+ f"Invalid variable name {var!r} in f-string template. "
+ f"Variable names cannot contain attribute "
+ f"access (.) or indexing ([])."
+ )
+ raise ValueError(msg)
+
+ if var.isdigit():
+ msg = (
+ f"Invalid variable name {var!r} in f-string template. "
+ f"Variable names cannot be all digits as they are interpreted "
+ f"as positional arguments."
+ )
+ raise ValueError(msg)
+
+ if format_spec and ("{" in format_spec or "}" in format_spec):
+ msg = (
+ "Invalid format specifier in f-string template. "
+ "Nested replacement fields are not allowed."
+ )
+ raise ValueError(msg)
+
+ input_variables.add(var)
+
+ return sorted(input_variables)
+
+
+def check_valid_template(
+ template: str, template_format: str, input_variables: list[str]
+) -> None:
+ """Check that template string is valid.
+
+ Args:
+ template: The template string.
+ template_format: The template format.
+
+ Should be one of `'f-string'` or `'jinja2'`.
+ input_variables: The input variables.
+
+ Raises:
+ ValueError: If the template format is not supported.
+ ValueError: If the prompt schema is invalid.
+ """
+ try:
+ validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]
+ except KeyError as exc:
+ msg = (
+ f"Invalid template format {template_format!r}, should be one of"
+ f" {list(DEFAULT_FORMATTER_MAPPING)}."
+ )
+ raise ValueError(msg) from exc
+ if template_format == "f-string":
+ validate_f_string_template(template)
+ try:
+ validator_func(template, input_variables)
+ except (KeyError, IndexError) as exc:
+ msg = (
+ "Invalid prompt schema; check for mismatched or missing input parameters"
+ f" from {input_variables}."
+ )
+ raise ValueError(msg) from exc
+
+
+def get_template_variables(template: str, template_format: str) -> list[str]:
+ """Get the variables from the template.
+
+ Args:
+ template: The template string.
+ template_format: The template format.
+
+ Should be one of `'f-string'`, `'mustache'` or `'jinja2'`.
+
+ Returns:
+ The variables from the template.
+
+ Raises:
+ ValueError: If the template format is not supported.
+ """
+ input_variables: list[str] | set[str]
+ if template_format == "jinja2":
+ # Get the variables for the template
+ input_variables = sorted(_get_jinja2_variables_from_template(template))
+ elif template_format == "f-string":
+ input_variables = validate_f_string_template(template)
+ elif template_format == "mustache":
+ input_variables = mustache_template_vars(template)
+ else:
+ msg = f"Unsupported template format: {template_format}"
+ raise ValueError(msg)
+
+ return sorted(input_variables)
+
+
+class StringPromptTemplate(BasePromptTemplate, ABC):
+ """String prompt that exposes the format method, returning a prompt."""
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "base"]`
+ """
+ return ["langchain", "prompts", "base"]
+
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return StringPromptValue(text=self.format(**kwargs))
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return StringPromptValue(text=await self.aformat(**kwargs))
+
+ @override
+ @abstractmethod
+ def format(self, **kwargs: Any) -> str: ...
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Get a pretty representation of the prompt.
+
+ Args:
+ html: Whether to return an HTML-formatted string.
+
+ Returns:
+ A pretty representation of the prompt.
+ """
+ # TODO: handle partials
+ dummy_vars = {
+ input_var: "{" + f"{input_var}" + "}" for input_var in self.input_variables
+ }
+ if html:
+ dummy_vars = {
+ k: get_colored_text(v, "yellow") for k, v in dummy_vars.items()
+ }
+ return self.format(**dummy_vars)
+
+ def pretty_print(self) -> None:
+ """Print a pretty representation of the prompt."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+def is_subsequence(child: Sequence, parent: Sequence) -> bool:
+ """Return `True` if child is subsequence of parent."""
+ if len(child) == 0 or len(parent) == 0:
+ return False
+ if len(parent) < len(child):
+ return False
+ return all(child[i] == parent[i] for i in range(len(child)))
diff --git a/python/user_packages/Python313/site-packages/langchain_core/prompts/structured.py b/python/user_packages/Python313/site-packages/langchain_core/prompts/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ac407fb7206f2f7376dfde46b6e965f2d9ec86
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/prompts/structured.py
@@ -0,0 +1,183 @@
+"""Structured prompt template for a language model."""
+
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from typing import (
+ Any,
+)
+
+from pydantic import BaseModel, Field
+from typing_extensions import override
+
+from langchain_core._api.beta_decorator import beta
+from langchain_core.language_models.base import BaseLanguageModel
+from langchain_core.prompts.chat import (
+ ChatPromptTemplate,
+ MessageLikeRepresentation,
+)
+from langchain_core.prompts.string import PromptTemplateFormat
+from langchain_core.runnables.base import (
+ Other,
+ Runnable,
+ RunnableSequence,
+ RunnableSerializable,
+)
+from langchain_core.utils import get_pydantic_field_names
+
+
+@beta()
+class StructuredPrompt(ChatPromptTemplate):
+ """Structured prompt template for a language model."""
+
+ schema_: dict | type
+ """Schema for the structured prompt."""
+
+ structured_output_kwargs: dict[str, Any] = Field(default_factory=dict)
+
+ def __init__(
+ self,
+ messages: Sequence[MessageLikeRepresentation],
+ schema_: dict | type[BaseModel] | None = None,
+ *,
+ structured_output_kwargs: dict[str, Any] | None = None,
+ template_format: PromptTemplateFormat = "f-string",
+ **kwargs: Any,
+ ) -> None:
+ """Create a structured prompt template.
+
+ Args:
+ messages: Sequence of messages.
+ schema_: Schema for the structured prompt.
+ structured_output_kwargs: Additional kwargs for structured output.
+ template_format: Template format for the prompt.
+
+ Raises:
+ ValueError: If schema is not provided.
+ """
+ schema_ = schema_ or kwargs.pop("schema", None)
+ if not schema_:
+ err_msg = (
+ "Must pass in a non-empty structured output schema. Received: "
+ f"{schema_}"
+ )
+ raise ValueError(err_msg)
+ structured_output_kwargs = structured_output_kwargs or {}
+ for k in set(kwargs).difference(get_pydantic_field_names(self.__class__)):
+ structured_output_kwargs[k] = kwargs.pop(k)
+ super().__init__(
+ messages=messages,
+ schema_=schema_,
+ structured_output_kwargs=structured_output_kwargs,
+ template_format=template_format,
+ **kwargs,
+ )
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ For example, if the class is `langchain.llms.openai.OpenAI`, then the namespace
+ is `["langchain", "llms", "openai"]`
+
+ Returns:
+ The namespace of the LangChain object.
+ """
+ return cls.__module__.split(".")
+
+ @classmethod
+ def from_messages_and_schema(
+ cls,
+ messages: Sequence[MessageLikeRepresentation],
+ schema: dict | type,
+ **kwargs: Any,
+ ) -> ChatPromptTemplate:
+ """Create a chat prompt template from a variety of message formats.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ from langchain_core.prompts import StructuredPrompt
+
+
+ class OutputSchema(BaseModel):
+ name: str
+ value: int
+
+
+ template = StructuredPrompt(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ],
+ OutputSchema,
+ )
+ ```
+
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `("human", "{user_input}")`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `("human", template)`; e.g.,
+ `"{user_input}"`
+ schema: A dictionary representation of function call, or a Pydantic model.
+ **kwargs: Any additional kwargs to pass through to
+ `ChatModel.with_structured_output(schema, **kwargs)`.
+
+ Returns:
+ A structured prompt template
+ """
+ return cls(messages, schema, **kwargs)
+
+ @override
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[dict, Other]:
+ return self.pipe(other)
+
+ def pipe(
+ self,
+ *others: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ name: str | None = None,
+ ) -> RunnableSerializable[dict, Other]:
+ """Pipe the structured prompt to a language model.
+
+ Args:
+ others: The language model to pipe the structured prompt to.
+ name: The name of the pipeline.
+
+ Returns:
+ A `RunnableSequence` object.
+
+ Raises:
+ NotImplementedError: If the first element of `others` is not a language
+ model.
+ """
+ if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
+ others[0], "with_structured_output"
+ ):
+ return RunnableSequence(
+ self,
+ others[0].with_structured_output(
+ self.schema_, **self.structured_output_kwargs
+ ),
+ *others[1:],
+ name=name,
+ )
+ msg = "Structured prompts need to be piped to a language model."
+ raise NotImplementedError(msg)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d619bfa88d6642b027c05402c7bf909ea8e02d17
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/__init__.py
@@ -0,0 +1,136 @@
+"""LangChain **Runnable** and the **LangChain Expression Language (LCEL)**.
+
+The LangChain Expression Language (LCEL) offers a declarative method to build
+production-grade programs that harness the power of LLMs.
+
+Programs created using LCEL and LangChain `Runnable` objects inherently support
+synchronous asynchronous, batch, and streaming operations.
+
+Support for **async** allows servers hosting LCEL based programs to scale bette for
+higher concurrent loads.
+
+**Batch** operations allow for processing multiple inputs in parallel.
+
+**Streaming** of intermediate outputs, as they're being generated, allows for creating
+more responsive UX.
+
+This module contains schema and implementation of LangChain `Runnable` object
+primitives.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.base import (
+ Runnable,
+ RunnableBinding,
+ RunnableGenerator,
+ RunnableLambda,
+ RunnableMap,
+ RunnableParallel,
+ RunnableSequence,
+ RunnableSerializable,
+ chain,
+ )
+ from langchain_core.runnables.branch import RunnableBranch
+ from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_config_list,
+ patch_config,
+ run_in_executor,
+ )
+ from langchain_core.runnables.fallbacks import RunnableWithFallbacks
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+ from langchain_core.runnables.passthrough import (
+ RunnableAssign,
+ RunnablePassthrough,
+ RunnablePick,
+ )
+ from langchain_core.runnables.router import RouterInput, RouterRunnable
+ from langchain_core.runnables.utils import (
+ AddableDict,
+ ConfigurableField,
+ ConfigurableFieldMultiOption,
+ ConfigurableFieldSingleOption,
+ ConfigurableFieldSpec,
+ aadd,
+ add,
+ )
+
+__all__ = (
+ "AddableDict",
+ "ConfigurableField",
+ "ConfigurableFieldMultiOption",
+ "ConfigurableFieldSingleOption",
+ "ConfigurableFieldSpec",
+ "RouterInput",
+ "RouterRunnable",
+ "Runnable",
+ "RunnableAssign",
+ "RunnableBinding",
+ "RunnableBranch",
+ "RunnableConfig",
+ "RunnableGenerator",
+ "RunnableLambda",
+ "RunnableMap",
+ "RunnableParallel",
+ "RunnablePassthrough",
+ "RunnablePick",
+ "RunnableSequence",
+ "RunnableSerializable",
+ "RunnableWithFallbacks",
+ "RunnableWithMessageHistory",
+ "aadd",
+ "add",
+ "chain",
+ "ensure_config",
+ "get_config_list",
+ "patch_config",
+ "run_in_executor",
+)
+
+_dynamic_imports = {
+ "chain": "base",
+ "Runnable": "base",
+ "RunnableBinding": "base",
+ "RunnableGenerator": "base",
+ "RunnableLambda": "base",
+ "RunnableMap": "base",
+ "RunnableParallel": "base",
+ "RunnableSequence": "base",
+ "RunnableSerializable": "base",
+ "RunnableBranch": "branch",
+ "RunnableConfig": "config",
+ "ensure_config": "config",
+ "get_config_list": "config",
+ "patch_config": "config",
+ "run_in_executor": "config",
+ "RunnableWithFallbacks": "fallbacks",
+ "RunnableWithMessageHistory": "history",
+ "RunnableAssign": "passthrough",
+ "RunnablePassthrough": "passthrough",
+ "RunnablePick": "passthrough",
+ "RouterInput": "router",
+ "RouterRunnable": "router",
+ "AddableDict": "utils",
+ "ConfigurableField": "utils",
+ "ConfigurableFieldMultiOption": "utils",
+ "ConfigurableFieldSingleOption": "utils",
+ "ConfigurableFieldSpec": "utils",
+ "aadd": "utils",
+ "add": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5361401fa53532d7eb3c04019fdc5aeb851dc32
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/branch.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/branch.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b80dae43b35a38ae1c35f66ce82d2b66ddf4f38
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/branch.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/config.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..caf9fb026102b8e82eb21d7c89529e07207b5807
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/config.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..133b6b999be53a576d59dcef54e9e55556baabbf
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c0535e355a42045c8b279d8f9a8891afe195488
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e29b14b5b6bb162607fb441c06fa96de15344ae
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..498dfb1bea9e67d23309c95f4f36c442cb3264c7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b1d81608225439ef54dad6b048c102ce6b4f0b5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f66afa2c70b3180678707350b61ab092ba5db3c4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/history.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/history.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ecb406bc5e4947e50d28e597875655c536ffb7c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/history.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6dc535ca580ac18cd128fa94afbfb17a33a5d965
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/retry.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bcd6ea808e4c58a21f9f628922920998ea338b76
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/retry.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/router.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/router.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48538fa3d01b3357fa3ffdd9be427648b1036ae0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/router.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/schema.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/schema.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a7057c8eb61ddcbefb21232d1a784fb831d3bfa
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/schema.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ef19751d92df3ba62d4f4f2f66e94dd792334be
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/runnables/__pycache__/utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/base.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a9b0cdcfcf32335ee492e733c4813f49eb57b1c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/base.py
@@ -0,0 +1,6574 @@
+"""Base classes and utilities for `Runnable` objects."""
+
+from __future__ import annotations
+
+import asyncio
+import collections
+import contextlib
+import functools
+import inspect
+import threading
+from abc import ABC, abstractmethod
+from collections.abc import (
+ AsyncGenerator,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Coroutine,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from concurrent.futures import FIRST_COMPLETED, wait
+from functools import wraps
+from itertools import tee
+from operator import itemgetter
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ Literal,
+ Protocol,
+ TypeVar,
+ cast,
+ get_args,
+ get_type_hints,
+ overload,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel
+from typing_extensions import override
+
+from langchain_core._api import beta_decorator
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.load.serializable import (
+ Serializable,
+ SerializedConstructor,
+ SerializedNotImplemented,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ get_config_list,
+ get_executor_for_config,
+ merge_configs,
+ patch_config,
+ run_in_executor,
+ set_config_context,
+)
+from langchain_core.runnables.utils import (
+ AddableDict,
+ AnyConfigurableField,
+ ConfigurableField,
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ accepts_config,
+ accepts_run_manager,
+ coro_with_context,
+ gated_coro,
+ gather_with_concurrency,
+ get_function_first_arg_dict_keys,
+ get_function_nonlocals,
+ get_lambda_source,
+ get_unique_config_specs,
+ indent_lines_after_first,
+ is_async_callable,
+ is_async_generator,
+)
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.event_stream import (
+ _astream_events_implementation_v1,
+ _astream_events_implementation_v2,
+)
+from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ _astream_log_implementation,
+)
+from langchain_core.tracers.root_listeners import (
+ AsyncRootListenersTracer,
+ RootListenersTracer,
+)
+from langchain_core.utils.aiter import aclosing, atee
+from langchain_core.utils.iter import safetee
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+ from langchain_core.prompts.base import BasePromptTemplate
+ from langchain_core.runnables.fallbacks import (
+ RunnableWithFallbacks as RunnableWithFallbacksT,
+ )
+ from langchain_core.runnables.graph import Graph
+ from langchain_core.runnables.retry import ExponentialJitterParams
+ from langchain_core.runnables.schema import StreamEvent
+ from langchain_core.tools import BaseTool
+ from langchain_core.tracers.log_stream import RunLog, RunLogPatch
+ from langchain_core.tracers.root_listeners import AsyncListener
+ from langchain_core.tracers.schemas import Run
+
+
+Other = TypeVar("Other")
+
+_RUNNABLE_GENERIC_NUM_ARGS = 2 # Input and Output
+
+
+class Runnable(ABC, Generic[Input, Output]):
+ """A unit of work that can be invoked, batched, streamed, transformed and composed.
+
+ Key Methods
+ ===========
+
+ - `invoke`/`ainvoke`: Transforms a single input into an output.
+ - `batch`/`abatch`: Efficiently transforms multiple inputs into outputs.
+ - `stream`/`astream`: Streams output from a single input as it's produced.
+ - `astream_log`: Streams output and selected intermediate results from an
+ input.
+
+ Built-in optimizations:
+
+ - **Batch**: By default, batch runs invoke() in parallel using a thread pool
+ executor. Override to optimize batching.
+
+ - **Async**: Methods with `'a'` prefix are asynchronous. By default, they execute
+ the sync counterpart using asyncio's thread pool.
+ Override for native async.
+
+ All methods accept an optional config argument, which can be used to configure
+ execution, add tags and metadata for tracing and debugging etc.
+
+ Runnables expose schematic information about their input, output and config via
+ the `input_schema` property, the `output_schema` property and `config_schema`
+ method.
+
+ Composition
+ ===========
+
+ Runnable objects can be composed together to create chains in a declarative way.
+
+ Any chain constructed this way will automatically have sync, async, batch, and
+ streaming support.
+
+ The main composition primitives are `RunnableSequence` and `RunnableParallel`.
+
+ **`RunnableSequence`** invokes a series of runnables sequentially, with
+ one Runnable's output serving as the next's input. Construct using
+ the `|` operator or by passing a list of runnables to `RunnableSequence`.
+
+ **`RunnableParallel`** invokes runnables concurrently, providing the same input
+ to each. Construct it using a dict literal within a sequence or by passing a
+ dict to `RunnableParallel`.
+
+
+ For example,
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ # A RunnableSequence constructed using the `|` operator
+ sequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)
+ sequence.invoke(1) # 4
+ sequence.batch([1, 2, 3]) # [4, 6, 8]
+
+
+ # A sequence that contains a RunnableParallel constructed using a dict literal
+ sequence = RunnableLambda(lambda x: x + 1) | {
+ "mul_2": RunnableLambda(lambda x: x * 2),
+ "mul_5": RunnableLambda(lambda x: x * 5),
+ }
+ sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
+ ```
+
+ Standard Methods
+ ================
+
+ All `Runnable`s expose additional methods that can be used to modify their
+ behavior (e.g., add a retry policy, add lifecycle listeners, make them
+ configurable, etc.).
+
+ These methods will work on any `Runnable`, including `Runnable` chains
+ constructed by composing other `Runnable`s.
+ See the individual methods for details.
+
+ For example,
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ import random
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def buggy_double(y: int) -> int:
+ \"\"\"Buggy code that will fail 70% of the time\"\"\"
+ if random.random() > 0.3:
+ print('This code failed, and will probably be retried!') # noqa: T201
+ raise ValueError('Triggered buggy code')
+ return y * 2
+
+ sequence = (
+ RunnableLambda(add_one) |
+ RunnableLambda(buggy_double).with_retry( # Retry on failure
+ stop_after_attempt=10,
+ wait_exponential_jitter=False
+ )
+ )
+
+ print(sequence.input_schema.model_json_schema()) # Show inferred input schema
+ print(sequence.output_schema.model_json_schema()) # Show inferred output schema
+ print(sequence.invoke(2)) # invoke the sequence (note the retry above!!)
+ ```
+
+ Debugging and tracing
+ =====================
+
+ As the chains get longer, it can be useful to be able to see intermediate results
+ to debug and trace the chain.
+
+ You can set the global debug flag to True to enable debug output for all chains:
+
+ ```python
+ from langchain_core.globals import set_debug
+
+ set_debug(True)
+ ```
+
+ Alternatively, you can pass existing or custom callbacks to any given chain:
+
+ ```python
+ from langchain_core.tracers import ConsoleCallbackHandler
+
+ chain.invoke(..., config={"callbacks": [ConsoleCallbackHandler()]})
+ ```
+
+ For a UI (and much more) checkout [LangSmith](https://docs.langchain.com/langsmith/home).
+
+ """
+
+ name: str | None
+ """The name of the `Runnable`. Used for debugging and tracing."""
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ """Get the name of the `Runnable`.
+
+ Args:
+ suffix: An optional suffix to append to the name.
+ name: An optional name to use instead of the `Runnable`'s name.
+
+ Returns:
+ The name of the `Runnable`.
+ """
+ if name:
+ name_ = name
+ elif hasattr(self, "name") and self.name:
+ name_ = self.name
+ else:
+ # Here we handle a case where the runnable subclass is also a pydantic
+ # model.
+ cls = self.__class__
+ # Then it's a pydantic sub-class, and we have to check
+ # whether it's a generic, and if so recover the original name.
+ if (
+ hasattr(
+ cls,
+ "__pydantic_generic_metadata__",
+ )
+ and "origin" in cls.__pydantic_generic_metadata__
+ and cls.__pydantic_generic_metadata__["origin"] is not None
+ ):
+ name_ = cls.__pydantic_generic_metadata__["origin"].__name__
+ else:
+ name_ = cls.__name__
+
+ if suffix:
+ if name_[0].isupper():
+ return name_ + suffix.title()
+ return name_ + "_" + suffix.lower()
+ return name_
+
+ @property
+ def InputType(self) -> type[Input]: # noqa: N802
+ """Input type.
+
+ The type of input this `Runnable` accepts specified as a type annotation.
+
+ Raises:
+ TypeError: If the input type cannot be inferred.
+ """
+ # First loop through all parent classes and if any of them is
+ # a Pydantic model, we will pick up the generic parameterization
+ # from that model via the __pydantic_generic_metadata__ attribute.
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if (
+ "args" in metadata
+ and len(metadata["args"]) == _RUNNABLE_GENERIC_NUM_ARGS
+ ):
+ return cast("type[Input]", metadata["args"][0])
+
+ # If we didn't find a Pydantic model in the parent classes,
+ # then loop through __orig_bases__. This corresponds to
+ # Runnables that are not pydantic models.
+ for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
+ type_args = get_args(cls)
+ if type_args and len(type_args) == _RUNNABLE_GENERIC_NUM_ARGS:
+ return cast("type[Input]", type_args[0])
+
+ msg = (
+ f"Runnable {self.get_name()} doesn't have an inferable InputType. "
+ "Override the InputType property to specify the input type."
+ )
+ raise TypeError(msg)
+
+ @property
+ def OutputType(self) -> type[Output]: # noqa: N802
+ """Output Type.
+
+ The type of output this `Runnable` produces specified as a type annotation.
+
+ Raises:
+ TypeError: If the output type cannot be inferred.
+ """
+ # First loop through bases -- this will help generic
+ # any pydantic models.
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if (
+ "args" in metadata
+ and len(metadata["args"]) == _RUNNABLE_GENERIC_NUM_ARGS
+ ):
+ return cast("type[Output]", metadata["args"][1])
+
+ for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
+ type_args = get_args(cls)
+ if type_args and len(type_args) == _RUNNABLE_GENERIC_NUM_ARGS:
+ return cast("type[Output]", type_args[1])
+
+ msg = (
+ f"Runnable {self.get_name()} doesn't have an inferable OutputType. "
+ "Override the OutputType property to specify the output type."
+ )
+ raise TypeError(msg)
+
+ @property
+ def input_schema(self) -> type[BaseModel]:
+ """The type of input this `Runnable` accepts specified as a Pydantic model."""
+ return self.get_input_schema()
+
+ def get_input_schema(
+ self,
+ config: RunnableConfig | None = None,
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate input to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic input schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an input schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate input.
+ """
+ _ = config
+ root_type = self.InputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Input"),
+ root=root_type,
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ def get_input_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the input to the `Runnable`.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A JSON schema that represents the input to the `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ print(runnable.get_input_jsonschema())
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.get_input_schema(config).model_json_schema()
+
+ @property
+ def output_schema(self) -> type[BaseModel]:
+ """Output schema.
+
+ The type of output this `Runnable` produces specified as a Pydantic model.
+ """
+ return self.get_output_schema()
+
+ def get_output_schema(
+ self,
+ config: RunnableConfig | None = None,
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate output to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic output schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an output schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate output.
+ """
+ _ = config
+ root_type = self.OutputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ def get_output_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the output of the `Runnable`.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A JSON schema that represents the output of the `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ print(runnable.get_output_jsonschema())
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.get_output_schema(config).model_json_schema()
+
+ @property
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """List configurable fields for this `Runnable`."""
+ return []
+
+ def config_schema(self, *, include: Sequence[str] | None = None) -> type[BaseModel]:
+ """The type of config this `Runnable` accepts specified as a Pydantic model.
+
+ To mark a field as configurable, see the `configurable_fields`
+ and `configurable_alternatives` methods.
+
+ Args:
+ include: A list of fields to include in the config schema.
+
+ Returns:
+ A Pydantic model that can be used to validate config.
+
+ """
+ include = include or []
+ config_specs = self.config_specs
+ configurable = (
+ create_model_v2(
+ "Configurable",
+ field_definitions={
+ spec.id: (
+ spec.annotation,
+ Field(
+ spec.default, title=spec.name, description=spec.description
+ ),
+ )
+ for spec in config_specs
+ },
+ )
+ if config_specs
+ else None
+ )
+
+ # Many need to create a typed dict instead to implement NotRequired!
+ all_fields = {
+ **({"configurable": (configurable, None)} if configurable else {}),
+ **{
+ field_name: (field_type, None)
+ for field_name, field_type in get_type_hints(RunnableConfig).items()
+ if field_name in [i for i in include if i != "configurable"]
+ },
+ }
+ return create_model_v2(self.get_name("Config"), field_definitions=all_fields)
+
+ def get_config_jsonschema(
+ self, *, include: Sequence[str] | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the config of the `Runnable`.
+
+ Args:
+ include: A list of fields to include in the config schema.
+
+ Returns:
+ A JSON schema that represents the config of the `Runnable`.
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.config_schema(include=include).model_json_schema()
+
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Return a graph representation of this `Runnable`."""
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ try:
+ input_node = graph.add_node(self.get_input_schema(config))
+ except TypeError:
+ input_node = graph.add_node(create_model_v2(self.get_name("Input")))
+ runnable_node = graph.add_node(
+ self, metadata=config.get("metadata") if config else None
+ )
+ try:
+ output_node = graph.add_node(self.get_output_schema(config))
+ except TypeError:
+ output_node = graph.add_node(create_model_v2(self.get_name("Output")))
+ graph.add_edge(input_node, runnable_node)
+ graph.add_edge(runnable_node, output_node)
+ return graph
+
+ def get_prompts(
+ self, config: RunnableConfig | None = None
+ ) -> list[BasePromptTemplate]:
+ """Return a list of prompts used by this `Runnable`."""
+ # Import locally to prevent circular import
+ from langchain_core.prompts.base import BasePromptTemplate # noqa: PLC0415
+
+ return [
+ node.data
+ for node in self.get_graph(config=config).nodes.values()
+ if isinstance(node.data, BasePromptTemplate)
+ ]
+
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[Input, Other]:
+ """Runnable "or" operator.
+
+ Compose this `Runnable` with another object to create a
+ `RunnableSequence`.
+
+ Args:
+ other: Another `Runnable` or a `Runnable`-like object.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(self, coerce_to_runnable(other))
+
+ def __ror__(
+ self,
+ other: Runnable[Other, Any]
+ | Callable[[Iterator[Other]], Iterator[Any]]
+ | Callable[[AsyncIterator[Other]], AsyncIterator[Any]]
+ | Callable[[Other], Any]
+ | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any],
+ ) -> RunnableSerializable[Other, Output]:
+ """Runnable "reverse-or" operator.
+
+ Compose this `Runnable` with another object to create a
+ `RunnableSequence`.
+
+ Args:
+ other: Another `Runnable` or a `Runnable`-like object.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(coerce_to_runnable(other), self)
+
+ def pipe(
+ self,
+ *others: Runnable[Any, Other] | Callable[[Any], Other],
+ name: str | None = None,
+ ) -> RunnableSerializable[Input, Other]:
+ """Pipe `Runnable` objects.
+
+ Compose this `Runnable` with `Runnable`-like objects to make a
+ `RunnableSequence`.
+
+ Equivalent to `RunnableSequence(self, *others)` or `self | others[0] | ...`
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ sequence = runnable_1.pipe(runnable_2)
+ # Or equivalently:
+ # sequence = runnable_1 | runnable_2
+ # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+ # -> 4
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ # -> [4, 6, 8]
+ ```
+
+ Args:
+ *others: Other `Runnable` or `Runnable`-like objects to compose
+ name: An optional name for the resulting `RunnableSequence`.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(self, *others, name=name)
+
+ def pick(self, keys: str | list[str]) -> RunnableSerializable[Any, Any]:
+ """Pick keys from the output `dict` of this `Runnable`.
+
+ !!! example "Pick a single key"
+
+ ```python
+ import json
+
+ from langchain_core.runnables import RunnableLambda, RunnableMap
+
+ as_str = RunnableLambda(str)
+ as_json = RunnableLambda(json.loads)
+ chain = RunnableMap(str=as_str, json=as_json)
+
+ chain.invoke("[1, 2, 3]")
+ # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]}
+
+ json_only_chain = chain.pick("json")
+ json_only_chain.invoke("[1, 2, 3]")
+ # -> [1, 2, 3]
+ ```
+
+ !!! example "Pick a list of keys"
+
+ ```python
+ from typing import Any
+
+ import json
+
+ from langchain_core.runnables import RunnableLambda, RunnableMap
+
+ as_str = RunnableLambda(str)
+ as_json = RunnableLambda(json.loads)
+
+
+ def as_bytes(x: Any) -> bytes:
+ return bytes(x, "utf-8")
+
+
+ chain = RunnableMap(
+ str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)
+ )
+
+ chain.invoke("[1, 2, 3]")
+ # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
+
+ json_and_bytes_chain = chain.pick(["json", "bytes"])
+ json_and_bytes_chain.invoke("[1, 2, 3]")
+ # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
+ ```
+
+ Args:
+ keys: A key or list of keys to pick from the output dict.
+
+ Returns:
+ a new `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import RunnablePick # noqa: PLC0415
+
+ return self | RunnablePick(keys)
+
+ def assign(
+ self,
+ **kwargs: Runnable[dict[str, Any], Any]
+ | Callable[[dict[str, Any]], Any]
+ | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]],
+ ) -> RunnableSerializable[Any, Any]:
+ """Assigns new fields to the `dict` output of this `Runnable`.
+
+ ```python
+ from langchain_core.language_models.fake import FakeStreamingListLLM
+ from langchain_core.output_parsers import StrOutputParser
+ from langchain_core.prompts import SystemMessagePromptTemplate
+ from langchain_core.runnables import Runnable
+ from operator import itemgetter
+
+ prompt = (
+ SystemMessagePromptTemplate.from_template("You are a nice assistant.")
+ + "{question}"
+ )
+ model = FakeStreamingListLLM(responses=["foo-lish"])
+
+ chain: Runnable = prompt | model | {"str": StrOutputParser()}
+
+ chain_with_assign = chain.assign(hello=itemgetter("str") | model)
+
+ print(chain_with_assign.input_schema.model_json_schema())
+ # {'title': 'PromptInput', 'type': 'object', 'properties':
+ {'question': {'title': 'Question', 'type': 'string'}}}
+ print(chain_with_assign.output_schema.model_json_schema())
+ # {'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
+ {'str': {'title': 'Str',
+ 'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
+ ```
+
+ Args:
+ **kwargs: A mapping of keys to `Runnable` or `Runnable`-like objects
+ that will be invoked with the entire output dict of this `Runnable`.
+
+ Returns:
+ A new `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import RunnableAssign # noqa: PLC0415
+
+ return self | RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
+
+ """ --- Public API --- """
+
+ @abstractmethod
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Output:
+ """Transform a single input into an output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+
+ Returns:
+ The output of the `Runnable`.
+ """
+
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Output:
+ """Transform a single input into an output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+
+ Returns:
+ The output of the `Runnable`.
+ """
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Default implementation runs invoke in parallel using a thread pool executor.
+
+ The default implementation of batch works well for IO bound runnables.
+
+ Subclasses must override this method if they can batch more efficiently;
+ e.g., if the underlying `Runnable` uses an API which supports a batch mode.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`. The config supports
+ standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work
+ to do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A list of outputs from the `Runnable`.
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+
+ def invoke(input_: Input, config: RunnableConfig) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return self.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return self.invoke(input_, config, **kwargs)
+
+ # If there's only one input, don't bother with the executor
+ if len(inputs) == 1:
+ return cast("list[Output]", [invoke(inputs[0], configs[0])])
+
+ with get_executor_for_config(configs[0]) as executor:
+ return cast("list[Output]", list(executor.map(invoke, inputs, configs)))
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output]]: ...
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output | Exception]]: ...
+
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> Iterator[tuple[int, Output | Exception]]:
+ """Run `invoke` in parallel on a list of inputs.
+
+ Yields results as they complete.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ Tuples of the index of the input and the output from the `Runnable`.
+
+ """
+ if not inputs:
+ return
+
+ configs = get_config_list(config, len(inputs))
+
+ def invoke(
+ i: int, input_: Input, config: RunnableConfig
+ ) -> tuple[int, Output | Exception]:
+ if return_exceptions:
+ try:
+ out: Output | Exception = self.invoke(input_, config, **kwargs)
+ except Exception as e:
+ out = e
+ else:
+ out = self.invoke(input_, config, **kwargs)
+
+ return (i, out)
+
+ if len(inputs) == 1:
+ yield invoke(0, inputs[0], configs[0])
+ return
+
+ with get_executor_for_config(configs[0]) as executor:
+ futures = {
+ executor.submit(invoke, i, input_, config)
+ for i, (input_, config) in enumerate(zip(inputs, configs, strict=False))
+ }
+
+ try:
+ while futures:
+ done, futures = wait(futures, return_when=FIRST_COMPLETED)
+ while done:
+ yield done.pop().result()
+ finally:
+ for future in futures:
+ future.cancel()
+
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Default implementation runs `ainvoke` in parallel using `asyncio.gather`.
+
+ The default implementation of `batch` works well for IO bound runnables.
+
+ Subclasses must override this method if they can batch more efficiently;
+ e.g., if the underlying `Runnable` uses an API which supports a batch mode.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A list of outputs from the `Runnable`.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+
+ async def ainvoke(value: Input, config: RunnableConfig) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return await self.ainvoke(value, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await self.ainvoke(value, config, **kwargs)
+
+ coros = map(ainvoke, inputs, configs)
+ return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros)
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output]]: ...
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]: ...
+
+ async def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]:
+ """Run `ainvoke` in parallel on a list of inputs.
+
+ Yields results as they complete.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ A tuple of the index of the input and the output from the `Runnable`.
+
+ """
+ if not inputs:
+ return
+
+ configs = get_config_list(config, len(inputs))
+ # Get max_concurrency from first config, defaulting to None (unlimited)
+ max_concurrency = configs[0].get("max_concurrency") if configs else None
+ semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else None
+
+ async def ainvoke_task(
+ i: int, input_: Input, config: RunnableConfig
+ ) -> tuple[int, Output | Exception]:
+ if return_exceptions:
+ try:
+ out: Output | Exception = await self.ainvoke(
+ input_, config, **kwargs
+ )
+ except Exception as e:
+ out = e
+ else:
+ out = await self.ainvoke(input_, config, **kwargs)
+ return (i, out)
+
+ coros = [
+ gated_coro(semaphore, ainvoke_task(i, input_, config))
+ if semaphore
+ else ainvoke_task(i, input_, config)
+ for i, (input_, config) in enumerate(zip(inputs, configs, strict=False))
+ ]
+
+ for coro in asyncio.as_completed(coros):
+ yield await coro
+
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Default implementation of `stream`, which calls `invoke`.
+
+ Subclasses must override this method if they support streaming output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ yield self.invoke(input, config, **kwargs)
+
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Default implementation of `astream`, which calls `ainvoke`.
+
+ Subclasses must override this method if they support streaming output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ yield await self.ainvoke(input, config, **kwargs)
+
+ @overload
+ def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: Literal[True] = True,
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLogPatch]: ...
+
+ @overload
+ def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: Literal[False],
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLog]: ...
+
+ async def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: bool = True,
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]:
+ """Stream all output from a `Runnable`, as reported to the callback system.
+
+ This includes all inner runs of LLMs, Retrievers, Tools, etc.
+
+ Output is streamed as Log objects, which include a list of
+ Jsonpatch ops that describe how the state of the run has changed in each
+ step, and the final state of the run.
+
+ The Jsonpatch ops can be applied in order to construct state.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ diff: Whether to yield diffs between each step or the current state.
+ with_streamed_output_list: Whether to yield the `streamed_output` list.
+ include_names: Only include logs with these names.
+ include_types: Only include logs with these types.
+ include_tags: Only include logs with these tags.
+ exclude_names: Exclude logs with these names.
+ exclude_types: Exclude logs with these types.
+ exclude_tags: Exclude logs with these tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ A `RunLogPatch` or `RunLog` object.
+
+ """
+ warn_deprecated(
+ since="1.3.3",
+ message=("astream_log is deprecated. Use astream instead."),
+ removal="2.0.0",
+ )
+ stream = LogStreamCallbackHandler(
+ auto_close=False,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ _schema_format="original",
+ )
+
+ # Mypy isn't resolving the overloads here
+ # Likely an issue b/c `self` is being passed through
+ # and it's can't map it to Runnable[Input,Output]?
+ async for item in _astream_log_implementation( # type: ignore[call-overload]
+ self,
+ input,
+ config,
+ diff=diff,
+ stream=stream,
+ with_streamed_output_list=with_streamed_output_list,
+ **kwargs,
+ ):
+ yield item
+
+ @overload
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Generate a stream of events.
+
+ Use to create an iterator over `StreamEvent` that provide real-time information
+ about the progress of the `Runnable`, including `StreamEvent` from intermediate
+ results.
+
+ A `StreamEvent` is a dictionary with the following schema:
+
+ - `event`: Event names are of the format:
+ `on_[runnable_type]_(start|stream|end)`.
+ - `name`: The name of the `Runnable` that generated the event.
+ - `run_id`: Randomly generated ID associated with the given execution of the
+ `Runnable` that emitted the event. A child `Runnable` that gets invoked as
+ part of the execution of a parent `Runnable` is assigned its own unique ID.
+ - `parent_ids`: The IDs of the parent runnables that generated the event. The
+ root `Runnable` will have an empty list. The order of the parent IDs is from
+ the root to the immediate parent. Only available for v2 version of the API.
+ The v1 version of the API will return an empty list.
+ - `tags`: The tags of the `Runnable` that generated the event.
+ - `metadata`: The metadata of the `Runnable` that generated the event.
+ - `data`: The data associated with the event. The contents of this field
+ depend on the type of event. See the table below for more details.
+
+ Below is a table that illustrates some events that might be emitted by various
+ chains. Metadata fields have been omitted from the table for brevity.
+ Chain definitions have been included after the table.
+
+ !!! note
+ This reference table is for the v2 version of the schema.
+
+ | event | name | chunk | input | output |
+ | ---------------------- | -------------------- | ----------------------------------- | ------------------------------------------------- | --------------------------------------------------- |
+ | `on_chat_model_start` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | |
+ | `on_chat_model_stream` | `'[model name]'` | `AIMessageChunk(content="hello")` | | |
+ | `on_chat_model_end` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | `AIMessageChunk(content="hello world")` |
+ | `on_llm_start` | `'[model name]'` | | `{'input': 'hello'}` | |
+ | `on_llm_stream` | `'[model name]'` | `'Hello' ` | | |
+ | `on_llm_end` | `'[model name]'` | | `'Hello human!'` | |
+ | `on_chain_start` | `'format_docs'` | | | |
+ | `on_chain_stream` | `'format_docs'` | `'hello world!, goodbye world!'` | | |
+ | `on_chain_end` | `'format_docs'` | | `[Document(...)]` | `'hello world!, goodbye world!'` |
+ | `on_tool_start` | `'some_tool'` | | `{"x": 1, "y": "2"}` | |
+ | `on_tool_end` | `'some_tool'` | | | `{"x": 1, "y": "2"}` |
+ | `on_retriever_start` | `'[retriever name]'` | | `{"query": "hello"}` | |
+ | `on_retriever_end` | `'[retriever name]'` | | `{"query": "hello"}` | `[Document(...), ..]` |
+ | `on_prompt_start` | `'[template_name]'` | | `{"question": "hello"}` | |
+ | `on_prompt_end` | `'[template_name]'` | | `{"question": "hello"}` | `ChatPromptValue(messages: [SystemMessage, ...])` |
+
+ In addition to the standard events, users can also dispatch custom events (see example below).
+
+ Custom events will be only be surfaced with in the v2 version of the API!
+
+ A custom event has following format:
+
+ | Attribute | Type | Description |
+ | ----------- | ------ | --------------------------------------------------------------------------------------------------------- |
+ | `name` | `str` | A user defined name for the event. |
+ | `data` | `Any` | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
+
+ Here are declarations associated with the standard events shown above:
+
+ `format_docs`:
+
+ ```python
+ def format_docs(docs: list[Document]) -> str:
+ '''Format the docs.'''
+ return ", ".join([doc.page_content for doc in docs])
+
+
+ format_docs = RunnableLambda(format_docs)
+ ```
+
+ `some_tool`:
+
+ ```python
+ @tool
+ def some_tool(x: int, y: str) -> dict:
+ '''Some_tool.'''
+ return {"x": x, "y": y}
+ ```
+
+ `prompt`:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are Cat Agent 007"),
+ ("human", "{question}"),
+ ]
+ ).with_config({"run_name": "my_template", "tags": ["my_template"]})
+ ```
+
+ !!! example
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ async def reverse(s: str) -> str:
+ return s[::-1]
+
+
+ chain = RunnableLambda(func=reverse)
+
+ events = [
+ event async for event in chain.astream_events("hello", version="v2")
+ ]
+
+ # Will produce the following events
+ # (run_id, and parent_ids has been omitted for brevity):
+ [
+ {
+ "data": {"input": "hello"},
+ "event": "on_chain_start",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"chunk": "olleh"},
+ "event": "on_chain_stream",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"output": "olleh"},
+ "event": "on_chain_end",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ ]
+ ```
+
+ ```python title="Dispatch custom event"
+ from langchain_core.callbacks.manager import (
+ adispatch_custom_event,
+ )
+ from langchain_core.runnables import RunnableLambda, RunnableConfig
+ import asyncio
+
+
+ async def slow_thing(some_input: str, config: RunnableConfig) -> str:
+ \"\"\"Do something that takes a long time.\"\"\"
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ await adispatch_custom_event(
+ "progress_event",
+ {"message": "Finished step 1 of 3"},
+ config=config # Must be included for python < 3.10
+ )
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ await adispatch_custom_event(
+ "progress_event",
+ {"message": "Finished step 2 of 3"},
+ config=config # Must be included for python < 3.10
+ )
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ return "Done"
+
+ slow_thing = RunnableLambda(slow_thing)
+
+ async for event in slow_thing.astream_events("some_input", version="v2"):
+ print(event)
+ ```
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ version: The version of the schema to use. One of `'v1'`, `'v2'`,
+ or `'v3'`.
+
+ Most callers should use `'v2'` (the default), which yields
+ `StreamEvent` dicts and supports custom events.
+
+ `'v3'` selects the typed, content-block-centric streaming
+ protocol and is only supported on `Runnable` subclasses that
+ implement it (currently `BaseChatModel` and
+ `langgraph.CompiledGraph`); on a generic `Runnable` it raises
+ `NotImplementedError`. The `'v3'` API is in beta and may
+ change. See the subclass override (e.g.
+ `BaseChatModel.astream_events`) for the v3 return shape.
+
+ `'v1'` is retained for backwards compatibility and will be
+ deprecated in `0.4.0`. Custom events are only surfaced in
+ `'v2'` / `'v3'`.
+ include_names: Only include events from `Runnable` objects with matching names.
+ include_types: Only include events from `Runnable` objects with matching types.
+ include_tags: Only include events from `Runnable` objects with matching tags.
+ exclude_names: Exclude events from `Runnable` objects with matching names.
+ exclude_types: Exclude events from `Runnable` objects with matching types.
+ exclude_tags: Exclude events from `Runnable` objects with matching tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ An async stream of `StreamEvent`.
+
+ Raises:
+ NotImplementedError: If the version is not `'v1'`, `'v2'`, or `'v3'`, or
+ if `'v3'` is requested on a `Runnable` that does not implement the v3
+ streaming protocol.
+
+ """ # noqa: E501
+ if version == "v3":
+ return self._astream_events_v3_unsupported()
+ return self._astream_events_v1_v2(
+ input,
+ config=config,
+ version=version,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+
+ async def _astream_events_v3_unsupported(self) -> Any:
+ """Coroutine that raises when v3 isn't implemented on this Runnable.
+
+ Lets the public `astream_events(version="v3")` return an awaitable
+ whose error surfaces on `await`, matching the v3 contract on
+ subclasses that do implement the protocol.
+ """
+ msg = (
+ "astream_events(version='v3') is only supported on Runnable "
+ "subclasses that implement the v3 streaming protocol "
+ "(BaseChatModel, CompiledGraph). "
+ f"Got: {type(self).__name__}"
+ )
+ raise NotImplementedError(msg)
+
+ async def _astream_events_v1_v2(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]:
+ if version == "v2":
+ event_stream = _astream_events_implementation_v2(
+ self,
+ input,
+ config=config,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+ elif version == "v1":
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "astream_events version='v1' is deprecated. "
+ "Use version='v2' or astream instead."
+ ),
+ removal="2.0.0",
+ )
+ # First implementation, built on top of astream_log API
+ # This implementation will be deprecated as of 0.2.0
+ event_stream = _astream_events_implementation_v1(
+ self,
+ input,
+ config=config,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+ else:
+ msg = f"Unsupported version: {version!r}. Expected 'v1', 'v2', or 'v3'."
+ raise NotImplementedError(msg)
+
+ async with aclosing(event_stream):
+ async for event in event_stream:
+ yield event
+
+ @overload
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Iterator[Any]: ...
+
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | Iterator[Any]:
+ """Generate a stream of events synchronously.
+
+ Synchronous counterpart to `astream_events`. For `version='v3'`, subclasses
+ that implement the v3 streaming protocol (`BaseChatModel`, `CompiledGraph`)
+ override this method. All other versions and base-class calls raise
+ `NotImplementedError`.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ version: The version of the schema to use. `'v3'` requires a subclass
+ that implements the v3 streaming protocol. `'v1'` and `'v2'` are not
+ supported on the sync path.
+ include_names: Only include events from `Runnable` objects with matching
+ names.
+ include_types: Only include events from `Runnable` objects with matching
+ types.
+ include_tags: Only include events from `Runnable` objects with matching
+ tags.
+ exclude_names: Exclude events from `Runnable` objects with matching names.
+ exclude_types: Exclude events from `Runnable` objects with matching types.
+ exclude_tags: Exclude events from `Runnable` objects with matching tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Raises:
+ NotImplementedError: Always. Subclasses override this method for supported
+ versions.
+
+ """
+ # Base impl always raises; consume args so they don't trip ARG002.
+ del input, config, include_names, include_types, include_tags
+ del exclude_names, exclude_types, exclude_tags, kwargs
+ if version == "v3":
+ msg = (
+ "stream_events(version='v3') is only supported on Runnable subclasses "
+ "that implement the v3 streaming protocol "
+ "(BaseChatModel, CompiledGraph). "
+ f"Got: {type(self).__name__}"
+ )
+ raise NotImplementedError(msg)
+ msg = (
+ f"stream_events(version={version!r}) is not supported. "
+ "Use astream_events() for v1/v2, or stream_events(version='v3') "
+ "on a supported subclass."
+ )
+ raise NotImplementedError(msg)
+
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Transform inputs to outputs.
+
+ Default implementation of transform, which buffers input and calls `astream`.
+
+ Subclasses must override this method if they can start producing output while
+ input is still being generated.
+
+ Args:
+ input: An iterator of inputs to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ final: Input
+ got_first_val = False
+
+ for ichunk in input:
+ # The default implementation of transform is to buffer input and
+ # then call stream.
+ # It'll attempt to gather all input into a single chunk using
+ # the `+` operator.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk,
+ # and we'll iterate until we get to the last chunk.
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if got_first_val:
+ yield from self.stream(final, config, **kwargs)
+
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Transform inputs to outputs.
+
+ Default implementation of atransform, which buffers input and calls `astream`.
+
+ Subclasses must override this method if they can start producing output while
+ input is still being generated.
+
+ Args:
+ input: An async iterator of inputs to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ final: Input
+ got_first_val = False
+
+ async for ichunk in input:
+ # The default implementation of transform is to buffer input and
+ # then call stream.
+ # It'll attempt to gather all input into a single chunk using
+ # the `+` operator.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk,
+ # and we'll iterate until we get to the last chunk.
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if got_first_val:
+ async for output in self.astream(final, config, **kwargs):
+ yield output
+
+ def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
+ """Bind arguments to a `Runnable`, returning a new `Runnable`.
+
+ Useful when a `Runnable` in a chain requires an argument that is not
+ in the output of the previous `Runnable` or included in the user input.
+
+ Args:
+ **kwargs: The arguments to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the arguments bound.
+
+ Example:
+ ```python
+ from langchain_ollama import ChatOllama
+ from langchain_core.output_parsers import StrOutputParser
+
+ model = ChatOllama(model="llama3.1")
+
+ # Without bind
+ chain = model | StrOutputParser()
+
+ chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
+ # Output is 'One two three four five.'
+
+ # With bind
+ chain = model.bind(stop=["three"]) | StrOutputParser()
+
+ chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
+ # Output is 'One two'
+ ```
+ """
+ return RunnableBinding(bound=self, kwargs=kwargs, config={})
+
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well-supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ """Bind config to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ config: The config to bind to the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the config bound.
+
+ """
+ return RunnableBinding(
+ bound=self,
+ config=cast(
+ "RunnableConfig",
+ {**(config or {}), **kwargs},
+ ),
+ kwargs={},
+ )
+
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The Run object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+ from langchain_core.tracers.schemas import Run
+
+ import time
+
+
+ def test_runnable(time_to_sleep: int):
+ time.sleep(time_to_sleep)
+
+
+ def fn_start(run_obj: Run):
+ print("start_time:", run_obj.start_time)
+
+
+ def fn_end(run_obj: Run):
+ print("end_time:", run_obj.end_time)
+
+
+ chain = RunnableLambda(test_runnable).with_listeners(
+ on_start=fn_start, on_end=fn_end
+ )
+ chain.invoke(2)
+ ```
+ """
+ return RunnableBinding(
+ bound=self,
+ config_factories=[
+ lambda config: {
+ "callbacks": [
+ RootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+ ],
+ )
+
+ def with_alisteners(
+ self,
+ *,
+ on_start: AsyncListener | None = None,
+ on_end: AsyncListener | None = None,
+ on_error: AsyncListener | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind async lifecycle listeners to a `Runnable`.
+
+ Returns a new `Runnable`.
+
+ The Run object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called asynchronously before the `Runnable` starts running,
+ with the `Run` object.
+ on_end: Called asynchronously after the `Runnable` finishes running,
+ with the `Run` object.
+ on_error: Called asynchronously if the `Runnable` throws an error,
+ with the `Run` object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda, Runnable
+ from datetime import datetime, timezone
+ import time
+ import asyncio
+
+
+ def format_t(timestamp: float) -> str:
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat()
+
+
+ async def test_runnable(time_to_sleep: int):
+ print(f"Runnable[{time_to_sleep}s]: starts at {format_t(time.time())}")
+ await asyncio.sleep(time_to_sleep)
+ print(f"Runnable[{time_to_sleep}s]: ends at {format_t(time.time())}")
+
+
+ async def fn_start(run_obj: Runnable):
+ print(f"on start callback starts at {format_t(time.time())}")
+ await asyncio.sleep(3)
+ print(f"on start callback ends at {format_t(time.time())}")
+
+
+ async def fn_end(run_obj: Runnable):
+ print(f"on end callback starts at {format_t(time.time())}")
+ await asyncio.sleep(2)
+ print(f"on end callback ends at {format_t(time.time())}")
+
+
+ runnable = RunnableLambda(test_runnable).with_alisteners(
+ on_start=fn_start, on_end=fn_end
+ )
+
+
+ async def concurrent_runs():
+ await asyncio.gather(runnable.ainvoke(2), runnable.ainvoke(3))
+
+
+ asyncio.run(concurrent_runs())
+ # Result:
+ # on start callback starts at 2025-03-01T07:05:22.875378+00:00
+ # on start callback starts at 2025-03-01T07:05:22.875495+00:00
+ # on start callback ends at 2025-03-01T07:05:25.878862+00:00
+ # on start callback ends at 2025-03-01T07:05:25.878947+00:00
+ # Runnable[2s]: starts at 2025-03-01T07:05:25.879392+00:00
+ # Runnable[3s]: starts at 2025-03-01T07:05:25.879804+00:00
+ # Runnable[2s]: ends at 2025-03-01T07:05:27.881998+00:00
+ # on end callback starts at 2025-03-01T07:05:27.882360+00:00
+ # Runnable[3s]: ends at 2025-03-01T07:05:28.881737+00:00
+ # on end callback starts at 2025-03-01T07:05:28.882428+00:00
+ # on end callback ends at 2025-03-01T07:05:29.883893+00:00
+ # on end callback ends at 2025-03-01T07:05:30.884831+00:00
+ ```
+ """
+ return RunnableBinding(
+ bound=self,
+ config_factories=[
+ lambda config: {
+ "callbacks": [
+ AsyncRootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+ ],
+ )
+
+ def with_types(
+ self,
+ *,
+ input_type: type[Input] | None = None,
+ output_type: type[Output] | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind input and output types to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ input_type: The input type to bind to the `Runnable`.
+ output_type: The output type to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the types bound.
+ """
+ return RunnableBinding(
+ bound=self,
+ custom_input_type=input_type,
+ custom_output_type=output_type,
+ kwargs={},
+ )
+
+ def with_retry(
+ self,
+ *,
+ retry_if_exception_type: tuple[type[BaseException], ...] = (Exception,),
+ wait_exponential_jitter: bool = True,
+ exponential_jitter_params: ExponentialJitterParams | None = None,
+ stop_after_attempt: int = 3,
+ ) -> Runnable[Input, Output]:
+ """Create a new `Runnable` that retries the original `Runnable` on exceptions.
+
+ Args:
+ retry_if_exception_type: A tuple of exception types to retry on.
+ wait_exponential_jitter: Whether to add jitter to the wait
+ time between retries.
+ stop_after_attempt: The maximum number of attempts to make before
+ giving up.
+ exponential_jitter_params: Parameters for
+ `tenacity.wait_exponential_jitter`. Namely: `initial`, `max`,
+ `exp_base`, and `jitter` (all `float` values).
+
+ Returns:
+ A new `Runnable` that retries the original `Runnable` on exceptions.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ count = 0
+
+
+ def _lambda(x: int) -> None:
+ global count
+ count = count + 1
+ if x == 1:
+ raise ValueError("x is 1")
+ else:
+ pass
+
+
+ runnable = RunnableLambda(_lambda)
+ try:
+ runnable.with_retry(
+ stop_after_attempt=2,
+ retry_if_exception_type=(ValueError,),
+ ).invoke(1)
+ except ValueError:
+ pass
+
+ assert count == 2
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.retry import RunnableRetry # noqa: PLC0415
+
+ return RunnableRetry(
+ bound=self,
+ kwargs={},
+ config={},
+ retry_exception_types=retry_if_exception_type,
+ wait_exponential_jitter=wait_exponential_jitter,
+ max_attempt_number=stop_after_attempt,
+ exponential_jitter_params=exponential_jitter_params,
+ )
+
+ def map(self) -> Runnable[list[Input], list[Output]]:
+ """Return a new `Runnable` that maps a list of inputs to a list of outputs.
+
+ Calls `invoke` with each input.
+
+ Returns:
+ A new `Runnable` that maps a list of inputs to a list of outputs.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def _lambda(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(_lambda)
+ print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
+ ```
+ """
+ return RunnableEach(bound=self)
+
+ def with_fallbacks(
+ self,
+ fallbacks: Sequence[Runnable[Input, Output]],
+ *,
+ exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,),
+ exception_key: str | None = None,
+ ) -> RunnableWithFallbacksT[Input, Output]:
+ """Add fallbacks to a `Runnable`, returning a new `Runnable`.
+
+ The new `Runnable` will try the original `Runnable`, and then each fallback
+ in order, upon failures.
+
+ Args:
+ fallbacks: A sequence of runnables to try if the original `Runnable`
+ fails.
+ exceptions_to_handle: A tuple of exception types to handle.
+ exception_key: If `string` is specified then handled exceptions will be
+ passed to fallbacks as part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a
+ dictionary as input.
+
+ Returns:
+ A new `Runnable` that will try the original `Runnable`, and then each
+ Fallback in order, upon failures.
+
+ Example:
+ ```python
+ from typing import Iterator
+
+ from langchain_core.runnables import RunnableGenerator
+
+
+ def _generate_immediate_error(input: Iterator) -> Iterator[str]:
+ raise ValueError()
+ yield ""
+
+
+ def _generate(input: Iterator) -> Iterator[str]:
+ yield from "foo bar"
+
+
+ runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
+ [RunnableGenerator(_generate)]
+ )
+ print("".join(runnable.stream({}))) # foo bar
+ ```
+
+ Args:
+ fallbacks: A sequence of runnables to try if the original `Runnable`
+ fails.
+ exceptions_to_handle: A tuple of exception types to handle.
+ exception_key: If `string` is specified then handled exceptions will be
+ passed to fallbacks as part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a
+ dictionary as input.
+
+ Returns:
+ A new `Runnable` that will try the original `Runnable`, and then each
+ Fallback in order, upon failures.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.fallbacks import ( # noqa: PLC0415
+ RunnableWithFallbacks,
+ )
+
+ return RunnableWithFallbacks(
+ runnable=self,
+ fallbacks=fallbacks,
+ exceptions_to_handle=exceptions_to_handle,
+ exception_key=exception_key,
+ )
+
+ """ --- Helper methods for Subclasses --- """
+
+ def _call_with_config(
+ self,
+ func: Callable[[Input], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ input_: Input,
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ serialized: dict[str, Any] | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Call with config.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `invoke` in subclasses.
+
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ serialized,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ output = cast(
+ "Output",
+ context.run(
+ call_func_with_variable_args, # type: ignore[arg-type]
+ func,
+ input_,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ )
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+
+ async def _acall_with_config(
+ self,
+ func: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ input_: Input,
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ serialized: dict[str, Any] | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Async call with config.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `ainvoke` in subclasses.
+ """
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ serialized,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ coro = acall_func_with_variable_args(
+ func, input_, config, run_manager, **kwargs
+ )
+ output: Output = await coro_with_context(coro, context)
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+
+ def _batch_with_config(
+ self,
+ func: Callable[[list[Input]], list[Exception | Output]]
+ | Callable[
+ [list[Input], list[CallbackManagerForChainRun]], list[Exception | Output]
+ ]
+ | Callable[
+ [list[Input], list[CallbackManagerForChainRun], list[RunnableConfig]],
+ list[Exception | Output],
+ ],
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks. Use this method to implement `invoke` in subclasses.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [get_callback_manager_for_config(c) for c in configs]
+ run_managers = [
+ callback_manager.on_chain_start(
+ None,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for callback_manager, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+ try:
+ if accepts_config(func):
+ kwargs["config"] = [
+ patch_config(c, callbacks=rm.get_child())
+ for c, rm in zip(configs, run_managers, strict=False)
+ ]
+ if accepts_run_manager(func):
+ kwargs["run_manager"] = run_managers
+ output = func(inputs, **kwargs) # type: ignore[call-arg]
+ except BaseException as e:
+ for run_manager in run_managers:
+ run_manager.on_chain_error(e)
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ for run_manager, out in zip(run_managers, output, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ run_manager.on_chain_error(out)
+ else:
+ run_manager.on_chain_end(out)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", output)
+ raise first_exception
+
+ async def _abatch_with_config(
+ self,
+ func: Callable[[list[Input]], Awaitable[list[Exception | Output]]]
+ | Callable[
+ [list[Input], list[AsyncCallbackManagerForChainRun]],
+ Awaitable[list[Exception | Output]],
+ ]
+ | Callable[
+ [list[Input], list[AsyncCallbackManagerForChainRun], list[RunnableConfig]],
+ Awaitable[list[Exception | Output]],
+ ],
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `invoke` in subclasses.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [get_async_callback_manager_for_config(c) for c in configs]
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ callback_manager.on_chain_start(
+ None,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for callback_manager, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+ try:
+ if accepts_config(func):
+ kwargs["config"] = [
+ patch_config(c, callbacks=rm.get_child())
+ for c, rm in zip(configs, run_managers, strict=False)
+ ]
+ if accepts_run_manager(func):
+ kwargs["run_manager"] = run_managers
+ output = await func(inputs, **kwargs) # type: ignore[call-arg]
+ except BaseException as e:
+ await asyncio.gather(
+ *(run_manager.on_chain_error(e) for run_manager in run_managers)
+ )
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ coros: list[Awaitable[None]] = []
+ for run_manager, out in zip(run_managers, output, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ coros.append(run_manager.on_chain_error(out))
+ else:
+ coros.append(run_manager.on_chain_end(out))
+ await asyncio.gather(*coros)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", output)
+ raise first_exception
+
+ def _transform_stream_with_config(
+ self,
+ inputs: Iterator[Input],
+ transformer: Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]]
+ | Callable[
+ [Iterator[Input], CallbackManagerForChainRun, RunnableConfig],
+ Iterator[Output],
+ ],
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Transform a stream with config.
+
+ Helper method to transform an `Iterator` of `Input` values into an
+ `Iterator` of `Output` values, with callbacks.
+
+ Use this to implement `stream` or `transform` in `Runnable` subclasses.
+
+ """
+ # Extract defers_inputs from kwargs if present
+ defers_inputs = kwargs.pop("defers_inputs", False)
+
+ # tee the input so we can iterate over it twice
+ input_for_tracing, input_for_transform = tee(inputs, 2)
+ # Start the input iterator to ensure the input Runnable starts before this one
+ final_input: Input | None = next(input_for_tracing, None)
+ final_input_supported = True
+ final_output: Output | None = None
+ final_output_supported = True
+
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ {"input": ""},
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ defers_inputs=defers_inputs,
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ if accepts_config(transformer):
+ kwargs["config"] = child_config
+ if accepts_run_manager(transformer):
+ kwargs["run_manager"] = run_manager
+ with set_config_context(child_config) as context:
+ iterator = context.run(transformer, input_for_transform, **kwargs) # type: ignore[arg-type]
+ if stream_handler := next(
+ (
+ cast("_StreamingCallbackHandler", h)
+ for h in run_manager.handlers
+ # instance check OK here, it's a mixin
+ if isinstance(h, _StreamingCallbackHandler)
+ ),
+ None,
+ ):
+ # populates streamed_output in astream_log() output if needed
+ iterator = stream_handler.tap_output_iter(
+ run_manager.run_id, iterator
+ )
+ try:
+ while True:
+ chunk: Output = context.run(next, iterator)
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = chunk
+ final_output_supported = False
+ else:
+ final_output = chunk
+ except (StopIteration, GeneratorExit):
+ pass
+ for ichunk in input_for_tracing:
+ if final_input_supported:
+ if final_input is None:
+ final_input = ichunk
+ else:
+ try:
+ final_input = final_input + ichunk # type: ignore[operator]
+ except TypeError:
+ final_input = ichunk
+ final_input_supported = False
+ else:
+ final_input = ichunk
+ except BaseException as e:
+ run_manager.on_chain_error(e, inputs=final_input)
+ raise
+ else:
+ run_manager.on_chain_end(final_output, inputs=final_input)
+
+ async def _atransform_stream_with_config(
+ self,
+ inputs: AsyncIterator[Input],
+ transformer: Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | Callable[
+ [AsyncIterator[Input], AsyncCallbackManagerForChainRun],
+ AsyncIterator[Output],
+ ]
+ | Callable[
+ [AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig],
+ AsyncIterator[Output],
+ ],
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Transform a stream with config.
+
+ Helper method to transform an Async `Iterator` of `Input` values into an
+ Async `Iterator` of `Output` values, with callbacks.
+
+ Use this to implement `astream` or `atransform` in `Runnable` subclasses.
+
+ """
+ # Extract defers_inputs from kwargs if present
+ defers_inputs = kwargs.pop("defers_inputs", False)
+
+ # tee the input so we can iterate over it twice
+ input_for_tracing, input_for_transform = atee(inputs, 2)
+ # Start the input iterator to ensure the input Runnable starts before this one
+ final_input: Input | None = await anext(input_for_tracing, None)
+ final_input_supported = True
+ final_output: Output | None = None
+ final_output_supported = True
+
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ {"input": ""},
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ defers_inputs=defers_inputs,
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ if accepts_config(transformer):
+ kwargs["config"] = child_config
+ if accepts_run_manager(transformer):
+ kwargs["run_manager"] = run_manager
+ with set_config_context(child_config) as context:
+ iterator_ = context.run(transformer, input_for_transform, **kwargs) # type: ignore[arg-type]
+
+ if stream_handler := next(
+ (
+ cast("_StreamingCallbackHandler", h)
+ for h in run_manager.handlers
+ # instance check OK here, it's a mixin
+ if isinstance(h, _StreamingCallbackHandler)
+ ),
+ None,
+ ):
+ # populates streamed_output in astream_log() output if needed
+ iterator = stream_handler.tap_output_aiter(
+ run_manager.run_id, iterator_
+ )
+ else:
+ iterator = iterator_
+ try:
+ while True:
+ chunk = await coro_with_context(anext(iterator), context)
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk
+ except TypeError:
+ final_output = chunk
+ final_output_supported = False
+ else:
+ final_output = chunk
+ except StopAsyncIteration:
+ pass
+ async for ichunk in input_for_tracing:
+ if final_input_supported:
+ if final_input is None:
+ final_input = ichunk
+ else:
+ try:
+ final_input = final_input + ichunk # type: ignore[operator]
+ except TypeError:
+ final_input = ichunk
+ final_input_supported = False
+ else:
+ final_input = ichunk
+ except BaseException as e:
+ await run_manager.on_chain_error(e, inputs=final_input)
+ raise
+ else:
+ await run_manager.on_chain_end(final_output, inputs=final_input)
+ finally:
+ if iterator_ is not None and hasattr(iterator_, "aclose"):
+ await iterator_.aclose()
+
+ @beta_decorator.beta(message="This API is in beta and may change in the future.")
+ def as_tool(
+ self,
+ args_schema: type[BaseModel] | None = None,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ arg_types: dict[str, type] | None = None,
+ ) -> BaseTool:
+ """Create a `BaseTool` from a `Runnable`.
+
+ `as_tool` will instantiate a `BaseTool` with a name, description, and
+ `args_schema` from a `Runnable`. Where possible, schemas are inferred
+ from `runnable.get_input_schema`.
+
+ Alternatively (e.g., if the `Runnable` takes a dict as input and the specific
+ `dict` keys are not typed), the schema can be specified directly with
+ `args_schema`.
+
+ You can also pass `arg_types` to just specify the required arguments and their
+ types.
+
+ Args:
+ args_schema: The schema for the tool.
+ name: The name of the tool.
+ description: The description of the tool.
+ arg_types: A dictionary of argument names to types.
+
+ Returns:
+ A `BaseTool` instance.
+
+ !!! example "`TypedDict` input"
+
+ ```python
+ from typing_extensions import TypedDict
+ from langchain_core.runnables import RunnableLambda
+
+
+ class Args(TypedDict):
+ a: int
+ b: list[int]
+
+
+ def f(x: Args) -> str:
+ return str(x["a"] * max(x["b"]))
+
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool()
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`dict` input, specifying schema via `args_schema`"
+
+ ```python
+ from typing import Any
+ from pydantic import BaseModel, Field
+ from langchain_core.runnables import RunnableLambda
+
+ def f(x: dict[str, Any]) -> str:
+ return str(x["a"] * max(x["b"]))
+
+ class FSchema(BaseModel):
+ \"\"\"Apply a function to an integer and list of integers.\"\"\"
+
+ a: int = Field(..., description="Integer")
+ b: list[int] = Field(..., description="List of ints")
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool(FSchema)
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`dict` input, specifying schema via `arg_types`"
+
+ ```python
+ from typing import Any
+ from langchain_core.runnables import RunnableLambda
+
+
+ def f(x: dict[str, Any]) -> str:
+ return str(x["a"] * max(x["b"]))
+
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]})
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`str` input"
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def f(x: str) -> str:
+ return x + "a"
+
+
+ def g(x: str) -> str:
+ return x + "z"
+
+
+ runnable = RunnableLambda(f) | g
+ as_tool = runnable.as_tool()
+ as_tool.invoke("b")
+ ```
+ """
+ # Avoid circular import
+ from langchain_core.tools import convert_runnable_to_tool # noqa: PLC0415
+
+ return convert_runnable_to_tool(
+ self,
+ args_schema=args_schema,
+ name=name,
+ description=description,
+ arg_types=arg_types,
+ )
+
+
+class RunnableSerializable(Serializable, Runnable[Input, Output]):
+ """Runnable that can be serialized to JSON."""
+
+ name: str | None = None
+ """The name of the `Runnable`.
+
+ Used for debugging and tracing.
+ """
+
+ model_config = ConfigDict(
+ # Suppress warnings from pydantic protected namespaces
+ # (e.g., `model_`)
+ protected_namespaces=(),
+ )
+
+ @override
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
+ """Serialize the `Runnable` to JSON.
+
+ Returns:
+ A JSON-serializable representation of the `Runnable`.
+
+ """
+ dumped = super().to_json()
+ with contextlib.suppress(Exception):
+ dumped["name"] = self.get_name()
+ return dumped
+
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ """Configure particular `Runnable` fields at runtime.
+
+ Args:
+ **kwargs: A dictionary of `ConfigurableField` instances to configure.
+
+ Raises:
+ ValueError: If a configuration key is not found in the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the fields configured.
+
+ !!! example
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(max_tokens=20).configurable_fields(
+ max_tokens=ConfigurableField(
+ id="output_token_number",
+ name="Max tokens in the output",
+ description="The maximum number of tokens in the output",
+ )
+ )
+
+ # max_tokens = 20
+ print(
+ "max_tokens_20: ", model.invoke("tell me something about chess").content
+ )
+
+ # max_tokens = 200
+ print(
+ "max_tokens_200: ",
+ model.with_config(configurable={"output_token_number": 200})
+ .invoke("tell me something about chess")
+ .content,
+ )
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
+ RunnableConfigurableFields,
+ )
+
+ model_fields = type(self).model_fields
+ for key in kwargs:
+ if key not in model_fields:
+ msg = (
+ f"Configuration key {key} not found in {self}: "
+ f"available keys are {model_fields.keys()}"
+ )
+ raise ValueError(msg)
+
+ return RunnableConfigurableFields(default=self, fields=kwargs)
+
+ def configurable_alternatives(
+ self,
+ which: ConfigurableField,
+ *,
+ default_key: str = "default",
+ prefix_keys: bool = False,
+ **kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
+ ) -> RunnableSerializable[Input, Output]:
+ """Configure alternatives for `Runnable` objects that can be set at runtime.
+
+ Args:
+ which: The `ConfigurableField` instance that will be used to select the
+ alternative.
+ default_key: The default key to use if no alternative is selected.
+ prefix_keys: Whether to prefix the keys with the `ConfigurableField` id.
+ **kwargs: A dictionary of keys to `Runnable` instances or callables that
+ return `Runnable` instances.
+
+ Returns:
+ A new `Runnable` with the alternatives configured.
+
+ !!! example
+
+ ```python
+ from langchain_anthropic import ChatAnthropic
+ from langchain_core.runnables.utils import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatAnthropic(
+ model_name="claude-sonnet-4-5-20250929"
+ ).configurable_alternatives(
+ ConfigurableField(id="llm"),
+ default_key="anthropic",
+ openai=ChatOpenAI(),
+ )
+
+ # uses the default model ChatAnthropic
+ print(model.invoke("which organization created you?").content)
+
+ # uses ChatOpenAI
+ print(
+ model.with_config(configurable={"llm": "openai"})
+ .invoke("which organization created you?")
+ .content
+ )
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
+ RunnableConfigurableAlternatives,
+ )
+
+ return RunnableConfigurableAlternatives(
+ which=which,
+ default=self,
+ alternatives=kwargs,
+ default_key=default_key,
+ prefix_keys=prefix_keys,
+ )
+
+
+def _seq_input_schema(
+ steps: list[Runnable[Any, Any]], config: RunnableConfig | None
+) -> type[BaseModel]:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
+ RunnableAssign,
+ RunnablePick,
+ )
+
+ first = steps[0]
+ if len(steps) == 1:
+ return first.get_input_schema(config)
+ if isinstance(first, RunnableAssign):
+ next_input_schema = _seq_input_schema(steps[1:], config)
+ if not issubclass(next_input_schema, RootModel):
+ # it's a dict as expected
+ return create_model_v2(
+ "RunnableSequenceInput",
+ field_definitions={
+ k: (v.annotation, v.default)
+ for k, v in next_input_schema.model_fields.items()
+ if k not in first.mapper.steps__
+ },
+ )
+ elif isinstance(first, RunnablePick):
+ return _seq_input_schema(steps[1:], config)
+
+ return first.get_input_schema(config)
+
+
+def _seq_output_schema(
+ steps: list[Runnable[Any, Any]], config: RunnableConfig | None
+) -> type[BaseModel]:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
+ RunnableAssign,
+ RunnablePick,
+ )
+
+ last = steps[-1]
+ if len(steps) == 1:
+ return last.get_input_schema(config)
+ if isinstance(last, RunnableAssign):
+ mapper_output_schema = last.mapper.get_output_schema(config)
+ prev_output_schema = _seq_output_schema(steps[:-1], config)
+ if not issubclass(prev_output_schema, RootModel):
+ # it's a dict as expected
+ return create_model_v2(
+ "RunnableSequenceOutput",
+ field_definitions={
+ **{
+ k: (v.annotation, v.default)
+ for k, v in prev_output_schema.model_fields.items()
+ },
+ **{
+ k: (v.annotation, v.default)
+ for k, v in mapper_output_schema.model_fields.items()
+ },
+ },
+ )
+ elif isinstance(last, RunnablePick):
+ prev_output_schema = _seq_output_schema(steps[:-1], config)
+ if not issubclass(prev_output_schema, RootModel):
+ # it's a dict as expected
+ if isinstance(last.keys, list):
+ return create_model_v2(
+ "RunnableSequenceOutput",
+ field_definitions={
+ k: (v.annotation, v.default)
+ for k, v in prev_output_schema.model_fields.items()
+ if k in last.keys
+ },
+ )
+ field = prev_output_schema.model_fields[last.keys]
+ return create_model_v2(
+ "RunnableSequenceOutput", root=(field.annotation, field.default)
+ )
+
+ return last.get_output_schema(config)
+
+
+_RUNNABLE_SEQUENCE_MIN_STEPS = 2
+
+
+class RunnableSequence(RunnableSerializable[Input, Output]):
+ """Sequence of `Runnable` objects, where the output of one is the input of the next.
+
+ **`RunnableSequence`** is the most important composition operator in LangChain
+ as it is used in virtually every chain.
+
+ A `RunnableSequence` can be instantiated directly or more commonly by using the
+ `|` operator where either the left or right operands (or both) must be a
+ `Runnable`.
+
+ Any `RunnableSequence` automatically supports sync, async, batch.
+
+ The default implementations of `batch` and `abatch` utilize threadpools and
+ asyncio gather and will be faster than naive invocation of `invoke` or `ainvoke`
+ for IO bound `Runnable`s.
+
+ Batching is implemented by invoking the batch method on each component of the
+ `RunnableSequence` in order.
+
+ A `RunnableSequence` preserves the streaming properties of its components, so if
+ all components of the sequence implement a `transform` method -- which
+ is the method that implements the logic to map a streaming input to a streaming
+ output -- then the sequence will be able to stream input to output!
+
+ If any component of the sequence does not implement transform then the
+ streaming will only begin after this component is run. If there are
+ multiple blocking components, streaming begins after the last one.
+
+ !!! note
+ `RunnableLambdas` do not support `transform` by default! So if you need to
+ use a `RunnableLambdas` be careful about where you place them in a
+ `RunnableSequence` (if you need to use the `stream`/`astream` methods).
+
+ If you need arbitrary logic and need streaming, you can subclass
+ Runnable, and implement `transform` for whatever logic you need.
+
+ Here is a simple example that uses simple functions to illustrate the use of
+ `RunnableSequence`:
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ sequence = runnable_1 | runnable_2
+ # Or equivalently:
+ # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ ```
+
+ Here's an example that uses streams JSON output generated by an LLM:
+
+ ```python
+ from langchain_core.output_parsers.json import SimpleJsonOutputParser
+ from langchain_openai import ChatOpenAI
+
+ prompt = PromptTemplate.from_template(
+ "In JSON format, give me a list of {topic} and their "
+ "corresponding names in French, Spanish and in a "
+ "Cat Language."
+ )
+
+ model = ChatOpenAI()
+ chain = prompt | model | SimpleJsonOutputParser()
+
+ async for chunk in chain.astream({"topic": "colors"}):
+ print("-") # noqa: T201
+ print(chunk, sep="", flush=True) # noqa: T201
+ ```
+ """
+
+ # The steps are broken into first, middle and last, solely for type checking
+ # purposes. It allows specifying the `Input` on the first type, the `Output` of
+ # the last type.
+ first: Runnable[Input, Any]
+ """The first `Runnable` in the sequence."""
+ middle: list[Runnable[Any, Any]] = Field(default_factory=list)
+ """The middle `Runnable` in the sequence."""
+ last: Runnable[Any, Output]
+ """The last `Runnable` in the sequence."""
+
+ def __init__(
+ self,
+ *steps: RunnableLike,
+ name: str | None = None,
+ first: Runnable[Any, Any] | None = None,
+ middle: list[Runnable[Any, Any]] | None = None,
+ last: Runnable[Any, Any] | None = None,
+ ) -> None:
+ """Create a new `RunnableSequence`.
+
+ Args:
+ steps: The steps to include in the sequence.
+ name: The name of the `Runnable`.
+ first: The first `Runnable` in the sequence.
+ middle: The middle `Runnable` objects in the sequence.
+ last: The last `Runnable` in the sequence.
+
+ Raises:
+ ValueError: If the sequence has less than 2 steps.
+ """
+ steps_flat: list[Runnable] = []
+ if not steps and first is not None and last is not None:
+ steps_flat = [first] + (middle or []) + [last]
+ for step in steps:
+ if isinstance(step, RunnableSequence):
+ steps_flat.extend(step.steps)
+ else:
+ steps_flat.append(coerce_to_runnable(step))
+ if len(steps_flat) < _RUNNABLE_SEQUENCE_MIN_STEPS:
+ msg = (
+ f"RunnableSequence must have at least {_RUNNABLE_SEQUENCE_MIN_STEPS} "
+ f"steps, got {len(steps_flat)}"
+ )
+ raise ValueError(msg)
+ super().__init__(
+ first=steps_flat[0],
+ middle=list(steps_flat[1:-1]),
+ last=steps_flat[-1],
+ name=name,
+ )
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ def steps(self) -> list[Runnable[Any, Any]]:
+ """All the `Runnable`s that make up the sequence in order.
+
+ Returns:
+ A list of `Runnable`s.
+ """
+ return [self.first, *self.middle, self.last]
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ """The type of the input to the `Runnable`."""
+ return self.first.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ """The type of the output of the `Runnable`."""
+ return self.last.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema of the `Runnable`.
+
+ """
+ return _seq_input_schema(self.steps, config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get the output schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The output schema of the `Runnable`.
+
+ """
+ return _seq_output_schema(self.steps, config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the config specs of the `Runnable`.
+
+ Returns:
+ The config specs of the `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ return get_unique_config_specs(
+ [spec for step in self.steps for spec in step.config_specs]
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Get the graph representation of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The graph representation of the `Runnable`.
+
+ Raises:
+ ValueError: If a `Runnable` has no first or last node.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ for step in self.steps:
+ current_last_node = graph.last_node()
+ step_graph = step.get_graph(config)
+ if step is not self.first:
+ step_graph.trim_first_node()
+ if step is not self.last:
+ step_graph.trim_last_node()
+ step_first_node, _ = graph.extend(step_graph)
+ if not step_first_node:
+ msg = f"Runnable {step} has no first node"
+ raise ValueError(msg)
+ if current_last_node:
+ graph.add_edge(current_last_node, step_first_node)
+
+ return graph
+
+ @override
+ def __repr__(self) -> str:
+ return "\n| ".join(
+ repr(s) if i == 0 else indent_lines_after_first(repr(s), "| ")
+ for i, s in enumerate(self.steps)
+ )
+
+ @override
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[Input, Other]:
+ if isinstance(other, RunnableSequence):
+ return RunnableSequence(
+ self.first,
+ *self.middle,
+ self.last,
+ other.first,
+ *other.middle,
+ other.last,
+ name=self.name or other.name,
+ )
+ return RunnableSequence(
+ self.first,
+ *self.middle,
+ self.last,
+ coerce_to_runnable(other),
+ name=self.name,
+ )
+
+ @override
+ def __ror__(
+ self,
+ other: Runnable[Other, Any]
+ | Callable[[Iterator[Other]], Iterator[Any]]
+ | Callable[[AsyncIterator[Other]], AsyncIterator[Any]]
+ | Callable[[Other], Any]
+ | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any],
+ ) -> RunnableSerializable[Other, Output]:
+ if isinstance(other, RunnableSequence):
+ return RunnableSequence(
+ other.first,
+ *other.middle,
+ other.last,
+ self.first,
+ *self.middle,
+ self.last,
+ name=other.name or self.name,
+ )
+ return RunnableSequence(
+ coerce_to_runnable(other),
+ self.first,
+ *self.middle,
+ self.last,
+ name=self.name,
+ )
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ # setup callbacks and context
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ input_ = input
+
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ with set_config_context(config) as context:
+ if i == 0:
+ input_ = context.run(step.invoke, input_, config, **kwargs)
+ else:
+ input_ = context.run(step.invoke, input_, config)
+ # finish the root run
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(input_)
+ return cast("Output", input_)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ # setup callbacks and context
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ input_ = input
+
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ with set_config_context(config) as context:
+ if i == 0:
+ part = functools.partial(step.ainvoke, input_, config, **kwargs)
+ else:
+ part = functools.partial(step.ainvoke, input_, config)
+ input_ = await coro_with_context(part(), context, create_task=True)
+ # finish the root run
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(input_)
+ return cast("Output", input_)
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ # setup callbacks and context
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers = [
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+
+ # invoke
+ try:
+ if return_exceptions:
+ # Track which inputs (by index) failed so far
+ # If an input has failed it will be present in this map,
+ # and the value will be the exception that was raised.
+ failed_inputs_map: dict[int, Exception] = {}
+ for stepidx, step in enumerate(self.steps):
+ # Assemble the original indexes of the remaining inputs
+ # (i.e. the ones that haven't failed yet)
+ remaining_idxs = [
+ i for i in range(len(configs)) if i not in failed_inputs_map
+ ]
+ # Invoke the step on the remaining inputs
+ inputs = step.batch(
+ [
+ inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if i not in failed_inputs_map
+ ],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config,
+ callbacks=rm.get_child(f"seq:step:{stepidx + 1}"),
+ )
+ for i, (rm, config) in enumerate(
+ zip(run_managers, configs, strict=False)
+ )
+ if i not in failed_inputs_map
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if stepidx == 0 else {}),
+ )
+ # If an input failed, add it to the map
+ failed_inputs_map.update(
+ {
+ i: inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if isinstance(inp, Exception)
+ }
+ )
+ inputs = [inp for inp in inputs if not isinstance(inp, Exception)]
+ # If all inputs have failed, stop processing
+ if len(failed_inputs_map) == len(configs):
+ break
+
+ # Reassemble the outputs, inserting Exceptions for failed inputs
+ inputs_copy = inputs.copy()
+ inputs = []
+ for i in range(len(configs)):
+ if i in failed_inputs_map:
+ inputs.append(cast("Input", failed_inputs_map[i]))
+ else:
+ inputs.append(inputs_copy.pop(0))
+ else:
+ for i, step in enumerate(self.steps):
+ inputs = step.batch(
+ inputs,
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config, callbacks=rm.get_child(f"seq:step:{i + 1}")
+ )
+ for rm, config in zip(run_managers, configs, strict=False)
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if i == 0 else {}),
+ )
+
+ # finish the root runs
+ except BaseException as e:
+ for rm in run_managers:
+ rm.on_chain_error(e)
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ for run_manager, out in zip(run_managers, inputs, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ run_manager.on_chain_error(out)
+ else:
+ run_manager.on_chain_end(out)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", inputs)
+ raise first_exception
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ # setup callbacks and context
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+
+ # invoke .batch() on each step
+ # this uses batching optimizations in Runnable subclasses, like LLM
+ try:
+ if return_exceptions:
+ # Track which inputs (by index) failed so far
+ # If an input has failed it will be present in this map,
+ # and the value will be the exception that was raised.
+ failed_inputs_map: dict[int, Exception] = {}
+ for stepidx, step in enumerate(self.steps):
+ # Assemble the original indexes of the remaining inputs
+ # (i.e. the ones that haven't failed yet)
+ remaining_idxs = [
+ i for i in range(len(configs)) if i not in failed_inputs_map
+ ]
+ # Invoke the step on the remaining inputs
+ inputs = await step.abatch(
+ [
+ inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if i not in failed_inputs_map
+ ],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config,
+ callbacks=rm.get_child(f"seq:step:{stepidx + 1}"),
+ )
+ for i, (rm, config) in enumerate(
+ zip(run_managers, configs, strict=False)
+ )
+ if i not in failed_inputs_map
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if stepidx == 0 else {}),
+ )
+ # If an input failed, add it to the map
+ failed_inputs_map.update(
+ {
+ i: inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if isinstance(inp, Exception)
+ }
+ )
+ inputs = [inp for inp in inputs if not isinstance(inp, Exception)]
+ # If all inputs have failed, stop processing
+ if len(failed_inputs_map) == len(configs):
+ break
+
+ # Reassemble the outputs, inserting Exceptions for failed inputs
+ inputs_copy = inputs.copy()
+ inputs = []
+ for i in range(len(configs)):
+ if i in failed_inputs_map:
+ inputs.append(cast("Input", failed_inputs_map[i]))
+ else:
+ inputs.append(inputs_copy.pop(0))
+ else:
+ for i, step in enumerate(self.steps):
+ inputs = await step.abatch(
+ inputs,
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config, callbacks=rm.get_child(f"seq:step:{i + 1}")
+ )
+ for rm, config in zip(run_managers, configs, strict=False)
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if i == 0 else {}),
+ )
+ # finish the root runs
+ except BaseException as e:
+ await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ coros: list[Awaitable[None]] = []
+ for run_manager, out in zip(run_managers, inputs, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ coros.append(run_manager.on_chain_error(out))
+ else:
+ coros.append(run_manager.on_chain_end(out))
+ await asyncio.gather(*coros)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", inputs)
+ raise first_exception
+
+ def _transform(
+ self,
+ inputs: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ steps = [self.first, *self.middle, self.last]
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ final_pipeline = cast("Iterator[Output]", inputs)
+ for idx, step in enumerate(steps):
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{idx + 1}")
+ )
+ if idx == 0:
+ final_pipeline = step.transform(final_pipeline, config, **kwargs)
+ else:
+ final_pipeline = step.transform(final_pipeline, config)
+
+ yield from final_pipeline
+
+ async def _atransform(
+ self,
+ inputs: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ steps = [self.first, *self.middle, self.last]
+ # stream the last steps
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ final_pipeline = cast("AsyncIterator[Output]", inputs)
+ for idx, step in enumerate(steps):
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{idx + 1}"),
+ )
+ if idx == 0:
+ final_pipeline = step.atransform(final_pipeline, config, **kwargs)
+ else:
+ final_pipeline = step.atransform(final_pipeline, config)
+ async for output in final_pipeline:
+ yield output
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self._transform_stream_with_config(
+ input,
+ self._transform,
+ patch_config(config, run_name=(config or {}).get("run_name") or self.name),
+ **kwargs,
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for chunk in self._atransform_stream_with_config(
+ input,
+ self._atransform,
+ patch_config(config, run_name=(config or {}).get("run_name") or self.name),
+ **kwargs,
+ ):
+ yield chunk
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
+ """Runnable that runs a mapping of `Runnable`s in parallel.
+
+ Returns a mapping of their outputs.
+
+ `RunnableParallel` is one of the two main composition primitives,
+ alongside `RunnableSequence`. It invokes `Runnable`s concurrently, providing the
+ same input to each.
+
+ A `RunnableParallel` can be instantiated directly or by using a dict literal
+ within a sequence.
+
+ Here is a simple example that uses functions to illustrate the use of
+ `RunnableParallel`:
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ def mul_three(x: int) -> int:
+ return x * 3
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ runnable_3 = RunnableLambda(mul_three)
+
+ sequence = runnable_1 | { # this dict is coerced to a RunnableParallel
+ "mul_two": runnable_2,
+ "mul_three": runnable_3,
+ }
+ # Or equivalently:
+ # sequence = runnable_1 | RunnableParallel(
+ # {"mul_two": runnable_2, "mul_three": runnable_3}
+ # )
+ # Also equivalently:
+ # sequence = runnable_1 | RunnableParallel(
+ # mul_two=runnable_2,
+ # mul_three=runnable_3,
+ # )
+
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ ```
+
+ `RunnableParallel` makes it easy to run `Runnable`s in parallel. In the below
+ example, we simultaneously stream output from two different `Runnable` objects:
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.runnables import RunnableParallel
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI()
+ joke_chain = (
+ ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
+ )
+ poem_chain = (
+ ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
+ | model
+ )
+
+ runnable = RunnableParallel(joke=joke_chain, poem=poem_chain)
+
+ # Display stream
+ output = {key: "" for key, _ in runnable.output_schema()}
+ for chunk in runnable.stream({"topic": "bear"}):
+ for key in chunk:
+ output[key] = output[key] + chunk[key].content
+ print(output) # noqa: T201
+ ```
+ """
+
+ steps__: Mapping[str, Runnable[Input, Any]]
+
+ def __init__(
+ self,
+ steps__: Mapping[
+ str,
+ Runnable[Input, Any]
+ | Callable[[Input], Any]
+ | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]],
+ ]
+ | None = None,
+ **kwargs: Runnable[Input, Any]
+ | Callable[[Input], Any]
+ | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]],
+ ) -> None:
+ """Create a `RunnableParallel`.
+
+ Args:
+ steps__: The steps to include.
+ **kwargs: Additional steps to include.
+
+ """
+ merged = {**steps__} if steps__ is not None else {}
+ merged.update(kwargs)
+ super().__init__(
+ steps__={key: coerce_to_runnable(r) for key, r in merged.items()}
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ """Get the name of the `Runnable`.
+
+ Args:
+ suffix: The suffix to use.
+ name: The name to use.
+
+ Returns:
+ The name of the `Runnable`.
+
+ """
+ name = name or self.name or f"RunnableParallel<{','.join(self.steps__.keys())}>"
+ return super().get_name(suffix, name=name)
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """The type of the input to the `Runnable`."""
+ for step in self.steps__.values():
+ if step.InputType:
+ return step.InputType
+
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema of the `Runnable`.
+
+ """
+ if all(
+ s.get_input_schema(config).model_json_schema().get("type", "object")
+ == "object"
+ for s in self.steps__.values()
+ ):
+ for step in self.steps__.values():
+ fields = step.get_input_schema(config).model_fields
+ root_field = fields.get("root")
+ if root_field is not None and root_field.annotation != Any:
+ return super().get_input_schema(config)
+
+ # This is correct, but pydantic typings/mypy don't think so.
+ return create_model_v2(
+ self.get_name("Input"),
+ field_definitions={
+ k: (v.annotation, v.default)
+ for step in self.steps__.values()
+ for k, v in step.get_input_schema(config).model_fields.items()
+ if k != "__root__"
+ },
+ )
+
+ return super().get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get the output schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The output schema of the `Runnable`.
+
+ """
+ fields = {k: (v.OutputType, ...) for k, v in self.steps__.items()}
+ return create_model_v2(self.get_name("Output"), field_definitions=fields)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the config specs of the `Runnable`.
+
+ Returns:
+ The config specs of the `Runnable`.
+
+ """
+ return get_unique_config_specs(
+ spec for step in self.steps__.values() for spec in step.config_specs
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Get the graph representation of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The graph representation of the `Runnable`.
+
+ Raises:
+ ValueError: If a `Runnable` has no first or last node.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ input_node = graph.add_node(self.get_input_schema(config))
+ output_node = graph.add_node(self.get_output_schema(config))
+ for step in self.steps__.values():
+ step_graph = step.get_graph()
+ step_graph.trim_first_node()
+ step_graph.trim_last_node()
+ if not step_graph:
+ graph.add_edge(input_node, output_node)
+ else:
+ step_first_node, step_last_node = graph.extend(step_graph)
+ if not step_first_node:
+ msg = f"Runnable {step} has no first node"
+ raise ValueError(msg)
+ if not step_last_node:
+ msg = f"Runnable {step} has no last node"
+ raise ValueError(msg)
+ graph.add_edge(input_node, step_first_node)
+ graph.add_edge(step_last_node, output_node)
+
+ return graph
+
+ @override
+ def __repr__(self) -> str:
+ map_for_repr = ",\n ".join(
+ f"{k}: {indent_lines_after_first(repr(v), ' ' + k + ': ')}"
+ for k, v in self.steps__.items()
+ )
+ return "{\n " + map_for_repr + "\n}"
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> dict[str, Any]:
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ def _invoke_step(
+ step: Runnable[Input, Any], input_: Input, config: RunnableConfig, key: str
+ ) -> Any:
+ child_config = patch_config(
+ config,
+ # mark each step as a child run
+ callbacks=run_manager.get_child(f"map:key:{key}"),
+ )
+ with set_config_context(child_config) as context:
+ return context.run(
+ step.invoke,
+ input_,
+ child_config,
+ )
+
+ # gather results from all steps
+ try:
+ # copy to avoid issues from the caller mutating the steps during invoke()
+ steps = dict(self.steps__)
+
+ with get_executor_for_config(config) as executor:
+ futures = [
+ executor.submit(_invoke_step, step, input, config, key)
+ for key, step in steps.items()
+ ]
+ output = {
+ key: future.result()
+ for key, future in zip(steps, futures, strict=False)
+ }
+ # finish the root run
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> dict[str, Any]:
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ async def _ainvoke_step(
+ step: Runnable[Input, Any], input_: Input, config: RunnableConfig, key: str
+ ) -> Any:
+ child_config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"map:key:{key}"),
+ )
+ with set_config_context(child_config) as context:
+ return await coro_with_context(
+ step.ainvoke(input_, child_config), context, create_task=True
+ )
+
+ # gather results from all steps
+ try:
+ # copy to avoid issues from the caller mutating the steps during invoke()
+ steps = dict(self.steps__)
+ results = await asyncio.gather(
+ *(
+ _ainvoke_step(
+ step,
+ input,
+ # mark each step as a child run
+ config,
+ key,
+ )
+ for key, step in steps.items()
+ )
+ )
+ output = dict(zip(steps, results, strict=False))
+ # finish the root run
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+
+ def _transform(
+ self,
+ inputs: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ ) -> Iterator[AddableDict]:
+ # Shallow copy steps to ignore mutations while in progress
+ steps = dict(self.steps__)
+ # Each step gets a copy of the input iterator,
+ # which is consumed in parallel in a separate thread.
+ input_copies = list(safetee(inputs, len(steps), lock=threading.Lock()))
+ with get_executor_for_config(config) as executor:
+ # Create the transform() generator for each step
+ named_generators = [
+ (
+ name,
+ step.transform(
+ input_copies.pop(),
+ patch_config(
+ config, callbacks=run_manager.get_child(f"map:key:{name}")
+ ),
+ ),
+ )
+ for name, step in steps.items()
+ ]
+ # Start the first iteration of each generator
+ futures = {
+ executor.submit(next, generator): (step_name, generator)
+ for step_name, generator in named_generators
+ }
+ # Yield chunks from each as they become available,
+ # and start the next iteration of that generator that yielded it.
+ # When all generators are exhausted, stop.
+ while futures:
+ completed_futures, _ = wait(futures, return_when=FIRST_COMPLETED)
+ for future in completed_futures:
+ (step_name, generator) = futures.pop(future)
+ try:
+ chunk = AddableDict({step_name: future.result()})
+ yield chunk
+ futures[executor.submit(next, generator)] = (
+ step_name,
+ generator,
+ )
+ except StopIteration:
+ pass
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self.transform(iter([input]), config)
+
+ async def _atransform(
+ self,
+ inputs: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ ) -> AsyncIterator[AddableDict]:
+ # Shallow copy steps to ignore mutations while in progress
+ steps = dict(self.steps__)
+ # Each step gets a copy of the input iterator,
+ # which is consumed in parallel in a separate thread.
+ input_copies = list(atee(inputs, len(steps), lock=asyncio.Lock()))
+ # Create the transform() generator for each step
+ named_generators = [
+ (
+ name,
+ step.atransform(
+ input_copies.pop(),
+ patch_config(
+ config, callbacks=run_manager.get_child(f"map:key:{name}")
+ ),
+ ),
+ )
+ for name, step in steps.items()
+ ]
+
+ # Wrap in a coroutine to satisfy linter
+ async def get_next_chunk(generator: AsyncIterator) -> Output | None:
+ return await anext(generator)
+
+ # Start the first iteration of each generator
+ tasks = {
+ asyncio.create_task(get_next_chunk(generator)): (step_name, generator)
+ for step_name, generator in named_generators
+ }
+ # Yield chunks from each as they become available,
+ # and start the next iteration of the generator that yielded it.
+ # When all generators are exhausted, stop.
+ while tasks:
+ completed_tasks, _ = await asyncio.wait(
+ tasks, return_when=asyncio.FIRST_COMPLETED
+ )
+ for task in completed_tasks:
+ (step_name, generator) = tasks.pop(task)
+ try:
+ chunk = AddableDict({step_name: task.result()})
+ yield chunk
+ new_task = asyncio.create_task(get_next_chunk(generator))
+ tasks[new_task] = (step_name, generator)
+ except StopAsyncIteration:
+ pass
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config):
+ yield chunk
+
+
+# We support both names
+RunnableMap = RunnableParallel
+
+
+class RunnableGenerator(Runnable[Input, Output]):
+ """`Runnable` that runs a generator function.
+
+ `RunnableGenerator`s can be instantiated directly or by using a generator within
+ a sequence.
+
+ `RunnableGenerator`s can be used to implement custom behavior, such as custom
+ output parsers, while preserving streaming capabilities. Given a generator function
+ with a signature `Iterator[A] -> Iterator[B]`, wrapping it in a
+ `RunnableGenerator` allows it to emit output chunks as soon as they are streamed
+ in from the previous step.
+
+ !!! note
+ If a generator function has a `signature A -> Iterator[B]`, such that it
+ requires its input from the previous step to be completed before emitting chunks
+ (e.g., most LLMs need the entire prompt available to start generating), it can
+ instead be wrapped in a `RunnableLambda`.
+
+ Here is an example to show the basic mechanics of a `RunnableGenerator`:
+
+ ```python
+ from typing import Any, AsyncIterator, Iterator
+
+ from langchain_core.runnables import RunnableGenerator
+
+
+ def gen(input: Iterator[Any]) -> Iterator[str]:
+ for token in ["Have", " a", " nice", " day"]:
+ yield token
+
+
+ runnable = RunnableGenerator(gen)
+ runnable.invoke(None) # "Have a nice day"
+ list(runnable.stream(None)) # ["Have", " a", " nice", " day"]
+ runnable.batch([None, None]) # ["Have a nice day", "Have a nice day"]
+
+
+ # Async version:
+ async def agen(input: AsyncIterator[Any]) -> AsyncIterator[str]:
+ for token in ["Have", " a", " nice", " day"]:
+ yield token
+
+
+ runnable = RunnableGenerator(agen)
+ await runnable.ainvoke(None) # "Have a nice day"
+ [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
+ ```
+
+ `RunnableGenerator` makes it easy to implement custom behavior within a streaming
+ context. Below we show an example:
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.runnables import RunnableGenerator, RunnableLambda
+ from langchain_openai import ChatOpenAI
+ from langchain_core.output_parsers import StrOutputParser
+
+
+ model = ChatOpenAI()
+ chant_chain = (
+ ChatPromptTemplate.from_template("Give me a 3 word chant about {topic}")
+ | model
+ | StrOutputParser()
+ )
+
+
+ def character_generator(input: Iterator[str]) -> Iterator[str]:
+ for token in input:
+ if "," in token or "." in token:
+ yield "👏" + token
+ else:
+ yield token
+
+
+ runnable = chant_chain | character_generator
+ assert type(runnable.last) is RunnableGenerator
+ "".join(runnable.stream({"topic": "waste"})) # Reduce👏, Reuse👏, Recycle👏.
+
+
+ # Note that RunnableLambda can be used to delay streaming of one step in a
+ # sequence until the previous step is finished:
+ def reverse_generator(input: str) -> Iterator[str]:
+ # Yield characters of input in reverse order.
+ for character in input[::-1]:
+ yield character
+
+
+ runnable = chant_chain | RunnableLambda(reverse_generator)
+ "".join(runnable.stream({"topic": "waste"})) # ".elcycer ,esuer ,ecudeR"
+ ```
+ """
+
+ def __init__(
+ self,
+ transform: Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[AsyncIterator[Input]], AsyncIterator[Output]],
+ atransform: Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | None = None,
+ *,
+ name: str | None = None,
+ ) -> None:
+ """Initialize a `RunnableGenerator`.
+
+ Args:
+ transform: The transform function.
+ atransform: The async transform function.
+ name: The name of the `Runnable`.
+
+ Raises:
+ TypeError: If the transform is not a generator function.
+
+ """
+ if atransform is not None:
+ self._atransform = atransform
+ func_for_name: Callable = atransform
+
+ if is_async_generator(transform):
+ self._atransform = transform
+ func_for_name = transform
+ elif inspect.isgeneratorfunction(transform):
+ self._transform = transform
+ func_for_name = transform
+ else:
+ msg = (
+ "Expected a generator function type for `transform`."
+ f"Instead got an unsupported type: {type(transform)}"
+ )
+ raise TypeError(msg)
+
+ try:
+ self.name = name or func_for_name.__name__
+ except AttributeError:
+ self.name = "RunnableGenerator"
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ func = getattr(self, "_transform", None) or self._atransform
+ try:
+ params = inspect.signature(func).parameters
+ first_param = next(iter(params.values()), None)
+ if first_param and first_param.annotation != inspect.Parameter.empty:
+ return getattr(first_param.annotation, "__args__", (Any,))[0]
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable generator, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.InputType
+
+ func = getattr(self, "_transform", None) or self._atransform
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Input"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ func = getattr(self, "_transform", None) or self._atransform
+ try:
+ sig = inspect.signature(func)
+ return (
+ getattr(sig.return_annotation, "__args__", (Any,))[0]
+ if sig.return_annotation != inspect.Signature.empty
+ else Any
+ )
+ except ValueError:
+ return Any
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable generator, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.OutputType
+ func = getattr(self, "_transform", None) or self._atransform
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, RunnableGenerator):
+ if hasattr(self, "_transform") and hasattr(other, "_transform"):
+ return self._transform == other._transform
+ if hasattr(self, "_atransform") and hasattr(other, "_atransform"):
+ return self._atransform == other._atransform
+ return False
+ return False
+
+ __hash__ = None # type: ignore[assignment]
+
+ @override
+ def __repr__(self) -> str:
+ return f"RunnableGenerator({self.name})"
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ if not hasattr(self, "_transform"):
+ msg = f"{self!r} only supports async methods."
+ raise NotImplementedError(msg)
+ return self._transform_stream_with_config(
+ input,
+ self._transform, # type: ignore[arg-type]
+ config,
+ defers_inputs=True,
+ **kwargs,
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ final: Output | None = None
+ for output in self.stream(input, config, **kwargs):
+ final = output if final is None else final + output # type: ignore[operator]
+ return cast("Output", final)
+
+ @override
+ def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ if not hasattr(self, "_atransform"):
+ msg = f"{self!r} only supports sync methods."
+ raise NotImplementedError(msg)
+
+ return self._atransform_stream_with_config(
+ input, self._atransform, config, defers_inputs=True, **kwargs
+ )
+
+ @override
+ def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ return self.atransform(input_aiter(), config, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ final: Output | None = None
+ async for output in self.astream(input, config, **kwargs):
+ final = output if final is None else final + output # type: ignore[operator]
+ return cast("Output", final)
+
+
+class RunnableLambda(Runnable[Input, Output]):
+ """`RunnableLambda` converts a python callable into a `Runnable`.
+
+ Wrapping a callable in a `RunnableLambda` makes the callable usable
+ within either a sync or async context.
+
+ `RunnableLambda` can be composed as any other `Runnable` and provides
+ seamless integration with LangChain tracing.
+
+ `RunnableLambda` is best suited for code that does not need to support
+ streaming. If you need to support streaming (i.e., be able to operate
+ on chunks of inputs and yield chunks of outputs), use `RunnableGenerator`
+ instead.
+
+ Note that if a `RunnableLambda` returns an instance of `Runnable`, that
+ instance is invoked (or streamed) during execution.
+
+ Examples:
+ ```python
+ # This is a RunnableLambda
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ runnable.invoke(1) # returns 2
+ runnable.batch([1, 2, 3]) # returns [2, 3, 4]
+
+ # Async is supported by default by delegating to the sync implementation
+ await runnable.ainvoke(1) # returns 2
+ await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
+
+
+ # Alternatively, can provide both synd and sync implementations
+ async def add_one_async(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one, afunc=add_one_async)
+ runnable.invoke(1) # Uses add_one
+ await runnable.ainvoke(1) # Uses add_one_async
+ ```
+ """
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, RunnableConfig], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], AsyncIterator[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, RunnableConfig], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Iterator[Output]],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Runnable[Input, Output]],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, CallbackManagerForChainRun], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ func: Callable[[Input], Iterator[Output]]
+ | Callable[[Input], Runnable[Input, Output]]
+ | Callable[[Input], Output]
+ | Callable[[Input, RunnableConfig], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]
+ | Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None:
+ """Create a `RunnableLambda` from a callable, and async callable or both.
+
+ Accepts both sync and async variants to allow providing efficient
+ implementations for sync and async execution.
+
+ Args:
+ func: Either sync or async callable
+ afunc: An async callable that takes an input and returns an output.
+
+ name: The name of the `Runnable`.
+
+ Raises:
+ TypeError: If the `func` is not a callable type.
+ TypeError: If both `func` and `afunc` are provided.
+
+ """
+ if afunc is not None:
+ self.afunc = afunc
+ func_for_name: Callable = afunc
+
+ if is_async_callable(func) or is_async_generator(func):
+ if afunc is not None:
+ msg = (
+ "Func was provided as a coroutine function, but afunc was "
+ "also provided. If providing both, func should be a regular "
+ "function to avoid ambiguity."
+ )
+ raise TypeError(msg)
+ self.afunc = func
+ func_for_name = func
+ elif callable(func):
+ self.func = cast("Callable[[Input], Output]", func)
+ func_for_name = func
+ else:
+ msg = (
+ "Expected a callable type for `func`."
+ f"Instead got an unsupported type: {type(func)}"
+ )
+ raise TypeError(msg)
+
+ try:
+ if name is not None:
+ self.name = name
+ elif func_for_name.__name__ != "":
+ self.name = func_for_name.__name__
+ except AttributeError:
+ pass
+
+ self._repr: str | None = None
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """The type of the input to this `Runnable`."""
+ func = getattr(self, "func", None) or self.afunc
+ try:
+ params = inspect.signature(func).parameters
+ first_param = next(iter(params.values()), None)
+ if first_param and first_param.annotation != inspect.Parameter.empty:
+ return first_param.annotation
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """The Pydantic schema for the input to this `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema for this `Runnable`.
+
+ """
+ func = getattr(self, "func", None) or self.afunc
+
+ if isinstance(func, itemgetter):
+ # This is terrible, but afaict it's not possible to access _items
+ # on itemgetter objects, so we have to parse the repr
+ items = str(func).replace("operator.itemgetter(", "")[:-1].split(", ")
+ if all(
+ item[0] == "'" and item[-1] == "'" and item != "''" for item in items
+ ):
+ fields = {item[1:-1]: (Any, ...) for item in items}
+ # It's a dict, lol
+ return create_model_v2(self.get_name("Input"), field_definitions=fields)
+ module = getattr(func, "__module__", None)
+ return create_model_v2(
+ self.get_name("Input"),
+ root=list[Any],
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ if self.InputType != Any:
+ return super().get_input_schema(config)
+
+ if dict_keys := get_function_first_arg_dict_keys(func):
+ return create_model_v2(
+ self.get_name("Input"),
+ field_definitions=dict.fromkeys(dict_keys, (Any, ...)),
+ )
+
+ return super().get_input_schema(config)
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """The type of the output of this `Runnable` as a type annotation.
+
+ Returns:
+ The type of the output of this `Runnable`.
+
+ """
+ func = getattr(self, "func", None) or self.afunc
+ try:
+ sig = inspect.signature(func)
+ if sig.return_annotation != inspect.Signature.empty:
+ # unwrap iterator types
+ if getattr(sig.return_annotation, "__origin__", None) in {
+ collections.abc.Iterator,
+ collections.abc.AsyncIterator,
+ }:
+ return getattr(sig.return_annotation, "__args__", (Any,))[0]
+ return sig.return_annotation
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable lambda, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.OutputType
+ func = getattr(self, "func", None) or self.afunc
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @functools.cached_property
+ def deps(self) -> list[Runnable]:
+ """The dependencies of this `Runnable`.
+
+ Returns:
+ The dependencies of this `Runnable`. If the function has nonlocal
+ variables that are `Runnable`s, they are considered dependencies.
+
+ """
+ if hasattr(self, "func"):
+ objects = get_function_nonlocals(self.func)
+ elif hasattr(self, "afunc"):
+ objects = get_function_nonlocals(self.afunc)
+ else:
+ objects = []
+
+ deps: list[Runnable] = []
+ for obj in objects:
+ if isinstance(obj, Runnable):
+ deps.append(obj)
+ elif isinstance(getattr(obj, "__self__", None), Runnable):
+ deps.append(obj.__self__)
+ return deps
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec for dep in self.deps for spec in dep.config_specs
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ if deps := self.deps:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ input_node = graph.add_node(self.get_input_schema(config))
+ output_node = graph.add_node(self.get_output_schema(config))
+ for dep in deps:
+ dep_graph = dep.get_graph()
+ dep_graph.trim_first_node()
+ dep_graph.trim_last_node()
+ if not dep_graph:
+ graph.add_edge(input_node, output_node)
+ else:
+ dep_first_node, dep_last_node = graph.extend(dep_graph)
+ if not dep_first_node:
+ msg = f"Runnable {dep} has no first node"
+ raise ValueError(msg)
+ if not dep_last_node:
+ msg = f"Runnable {dep} has no last node"
+ raise ValueError(msg)
+ graph.add_edge(input_node, dep_first_node)
+ graph.add_edge(dep_last_node, output_node)
+ else:
+ graph = super().get_graph(config)
+
+ return graph
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, RunnableLambda):
+ if hasattr(self, "func") and hasattr(other, "func"):
+ return self.func == other.func
+ if hasattr(self, "afunc") and hasattr(other, "afunc"):
+ return self.afunc == other.afunc
+ return False
+ return False
+
+ __hash__ = None # type: ignore[assignment]
+
+ def __repr__(self) -> str:
+ """Return a string representation of this `Runnable`."""
+ if self._repr is None:
+ if hasattr(self, "func") and isinstance(self.func, itemgetter):
+ self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})"
+ elif hasattr(self, "func"):
+ self._repr = f"RunnableLambda({get_lambda_source(self.func) or '...'})"
+ elif hasattr(self, "afunc"):
+ self._repr = (
+ f"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})"
+ )
+ else:
+ self._repr = "RunnableLambda(...)"
+ return self._repr
+
+ def _invoke(
+ self,
+ input_: Input,
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ if inspect.isgeneratorfunction(self.func):
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ cast("Callable[[Input], Iterator[Output]]", self.func),
+ input_,
+ config,
+ run_manager,
+ **kwargs,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = call_func_with_variable_args(
+ self.func, input_, config, run_manager, **kwargs
+ )
+ # If the output is a Runnable, invoke it
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {input_}."
+ )
+ raise RecursionError(msg)
+ output = output.invoke(
+ input_,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ )
+ return cast("Output", output)
+
+ async def _ainvoke(
+ self,
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ if hasattr(self, "afunc"):
+ afunc = self.afunc
+ else:
+ if inspect.isgeneratorfunction(self.func):
+
+ def func(
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ cast("Callable[[Input], Iterator[Output]]", self.func),
+ value,
+ config,
+ run_manager.get_sync(),
+ **kwargs,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ return cast("Output", output)
+
+ else:
+
+ def func(
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ return call_func_with_variable_args(
+ self.func, value, config, run_manager.get_sync(), **kwargs
+ )
+
+ @wraps(func)
+ async def f(*args: Any, **kwargs: Any) -> Any:
+ return await run_in_executor(config, func, *args, **kwargs)
+
+ afunc = f
+
+ if is_async_generator(afunc):
+ output: Output | None = None
+ async with aclosing(
+ cast(
+ "AsyncGenerator[Any, Any]",
+ acall_func_with_variable_args(
+ cast("Callable", afunc),
+ value,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ )
+ ) as stream:
+ async for chunk in cast(
+ "AsyncIterator[Output]",
+ stream,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = await acall_func_with_variable_args(
+ cast("Callable", afunc), value, config, run_manager, **kwargs
+ )
+ # If the output is a Runnable, invoke it
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {value}."
+ )
+ raise RecursionError(msg)
+ output = await output.ainvoke(
+ value,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ )
+ return cast("Output", output)
+
+ @override
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Invoke this `Runnable` synchronously.
+
+ Args:
+ input: The input to this `Runnable`.
+ config: The config to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The output of this `Runnable`.
+
+ Raises:
+ TypeError: If the `Runnable` is a coroutine function.
+
+ """
+ if hasattr(self, "func"):
+ return self._call_with_config(
+ self._invoke,
+ input,
+ ensure_config(config),
+ **kwargs,
+ )
+ msg = "Cannot invoke a coroutine function synchronously.Use `ainvoke` instead."
+ raise TypeError(msg)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Invoke this `Runnable` asynchronously.
+
+ Args:
+ input: The input to this `Runnable`.
+ config: The config to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The output of this `Runnable`.
+
+ """
+ return await self._acall_with_config(
+ self._ainvoke,
+ input,
+ ensure_config(config),
+ **kwargs,
+ )
+
+ def _transform(
+ self,
+ chunks: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ final: Input
+ got_first_val = False
+ for ichunk in chunks:
+ # By definitions, RunnableLambdas consume all input before emitting output.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ # So we'll iterate until we get to the last chunk!
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if inspect.isgeneratorfunction(self.func):
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ self.func, final, config, run_manager, **kwargs
+ ):
+ yield chunk
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk
+ except TypeError:
+ output = chunk
+ else:
+ output = call_func_with_variable_args(
+ self.func, final, config, run_manager, **kwargs
+ )
+
+ # If the output is a Runnable, use its stream output
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {final}."
+ )
+ raise RecursionError(msg)
+ for chunk in output.stream(
+ final,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ ):
+ yield chunk
+ elif not inspect.isgeneratorfunction(self.func):
+ # Otherwise, just yield it
+ yield cast("Output", output)
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ if hasattr(self, "func"):
+ yield from self._transform_stream_with_config(
+ input,
+ self._transform,
+ ensure_config(config),
+ **kwargs,
+ )
+ else:
+ msg = (
+ "Cannot stream a coroutine function synchronously."
+ "Use `astream` instead."
+ )
+ raise TypeError(msg)
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ async def _atransform(
+ self,
+ chunks: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ final: Input
+ got_first_val = False
+ async for ichunk in chunks:
+ # By definitions, RunnableLambdas consume all input before emitting output.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ # So we'll iterate until we get to the last chunk!
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if hasattr(self, "afunc"):
+ afunc = self.afunc
+ else:
+ if inspect.isgeneratorfunction(self.func):
+ msg = (
+ "Cannot stream from a generator function asynchronously."
+ "Use .stream() instead."
+ )
+ raise TypeError(msg)
+
+ def func(
+ input_: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ return call_func_with_variable_args(
+ self.func, input_, config, run_manager.get_sync(), **kwargs
+ )
+
+ @wraps(func)
+ async def f(*args: Any, **kwargs: Any) -> Any:
+ return await run_in_executor(config, func, *args, **kwargs)
+
+ afunc = f
+
+ if is_async_generator(afunc):
+ output: Output | None = None
+ async for chunk in cast(
+ "AsyncIterator[Output]",
+ acall_func_with_variable_args(
+ cast("Callable", afunc),
+ final,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ ):
+ yield chunk
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = await acall_func_with_variable_args(
+ cast("Callable", afunc),
+ final,
+ config,
+ run_manager,
+ **kwargs,
+ )
+
+ # If the output is a Runnable, use its astream output
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {final}."
+ )
+ raise RecursionError(msg)
+ async for chunk in output.astream(
+ final,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ ):
+ yield chunk
+ elif not is_async_generator(afunc):
+ # Otherwise, just yield it
+ yield cast("Output", output)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for output in self._atransform_stream_with_config(
+ input,
+ self._atransform,
+ ensure_config(config),
+ **kwargs,
+ ):
+ yield output
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
+ """RunnableEachBase class.
+
+ `Runnable` that calls another `Runnable` for each element of the input sequence.
+
+ Use only if creating a new `RunnableEach` subclass with different `__init__`
+ args.
+
+ See documentation for `RunnableEach` for more details.
+
+ """
+
+ bound: Runnable[Input, Output]
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ return list[self.bound.InputType] # type: ignore[name-defined]
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ return create_model_v2(
+ self.get_name("Input"),
+ root=(
+ list[self.bound.get_input_schema(config)], # type: ignore[misc]
+ None,
+ ),
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[list[Output]]:
+ return list[self.bound.OutputType] # type: ignore[name-defined]
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ schema = self.bound.get_output_schema(config)
+ return create_model_v2(
+ self.get_name("Output"),
+ root=list[schema], # type: ignore[valid-type]
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.bound.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ return self.bound.get_graph(config)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ def _invoke(
+ self,
+ inputs: list[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> list[Output]:
+ configs = [
+ patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
+ ]
+ return self.bound.batch(inputs, configs, **kwargs)
+
+ @override
+ def invoke(
+ self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
+ ) -> list[Output]:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ inputs: list[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> list[Output]:
+ configs = [
+ patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
+ ]
+ return await self.bound.abatch(inputs, configs, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
+ ) -> list[Output]:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ @override
+ def astream_events( # type: ignore[override]
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any | None,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ del input, config, kwargs
+ if version == "v3":
+ return self._astream_events_unsupported_v3()
+ return self._astream_events_unsupported_v1_v2()
+
+ async def _astream_events_unsupported_v3(self) -> Any:
+ msg = "RunnableEach does not support astream_events yet."
+ raise NotImplementedError(msg)
+
+ async def _astream_events_unsupported_v1_v2(self) -> AsyncIterator[StreamEvent]:
+ msg = "RunnableEach does not support astream_events yet."
+ raise NotImplementedError(msg)
+ yield # makes this an async generator (never reached)
+
+
+class RunnableEach(RunnableEachBase[Input, Output]):
+ """RunnableEach class.
+
+ `Runnable` that calls another `Runnable` for each element of the input sequence.
+
+ It allows you to call multiple inputs with the bounded `Runnable`.
+
+ `RunnableEach` makes it easy to run multiple inputs for the `Runnable`.
+ In the below example, we associate and run three inputs
+ with a `Runnable`:
+
+ ```python
+ from langchain_core.runnables.base import RunnableEach
+ from langchain_openai import ChatOpenAI
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.output_parsers import StrOutputParser
+ prompt = ChatPromptTemplate.from_template("Tell me a short joke about
+ {topic}")
+ model = ChatOpenAI()
+ output_parser = StrOutputParser()
+ runnable = prompt | model | output_parser
+ runnable_each = RunnableEach(bound=runnable)
+ output = runnable_each.invoke([{'topic':'Computer Science'},
+ {'topic':'Art'},
+ {'topic':'Biology'}])
+ print(output) # noqa: T201
+
+ ```
+ """
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = name or self.name or f"RunnableEach<{self.bound.get_name()}>"
+ return super().get_name(suffix, name=name)
+
+ @override
+ def bind(self, **kwargs: Any) -> RunnableEach[Input, Output]:
+ return RunnableEach(bound=self.bound.bind(**kwargs))
+
+ @override
+ def with_config(
+ self, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> RunnableEach[Input, Output]:
+ return RunnableEach(bound=self.bound.with_config(config, **kwargs))
+
+ @override
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> RunnableEach[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ """
+ return RunnableEach(
+ bound=self.bound.with_listeners(
+ on_start=on_start, on_end=on_end, on_error=on_error
+ )
+ )
+
+ def with_alisteners(
+ self,
+ *,
+ on_start: AsyncListener | None = None,
+ on_end: AsyncListener | None = None,
+ on_error: AsyncListener | None = None,
+ ) -> RunnableEach[Input, Output]:
+ """Bind async lifecycle listeners to a `Runnable`.
+
+ Returns a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called asynchronously before the `Runnable` starts running,
+ with the `Run` object.
+ on_end: Called asynchronously after the `Runnable` finishes running,
+ with the `Run` object.
+ on_error: Called asynchronously if the `Runnable` throws an error,
+ with the `Run` object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ """
+ return RunnableEach(
+ bound=self.bound.with_alisteners(
+ on_start=on_start, on_end=on_end, on_error=on_error
+ )
+ )
+
+
+class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[no-redef]
+ """`Runnable` that delegates calls to another `Runnable` with a set of `**kwargs`.
+
+ Use only if creating a new `RunnableBinding` subclass with different `__init__`
+ args.
+
+ See documentation for `RunnableBinding` for more details.
+
+ """
+
+ bound: Runnable[Input, Output]
+ """The underlying `Runnable` that this `Runnable` delegates to."""
+
+ kwargs: Mapping[str, Any] = Field(default_factory=dict)
+ """kwargs to pass to the underlying `Runnable` when running.
+
+ For example, when the `Runnable` binding is invoked the underlying
+ `Runnable` will be invoked with the same input but with these additional
+ kwargs.
+
+ """
+
+ config: RunnableConfig = Field(default_factory=RunnableConfig)
+ """The config to bind to the underlying `Runnable`."""
+
+ config_factories: list[Callable[[RunnableConfig], RunnableConfig]] = Field(
+ default_factory=list
+ )
+ """The config factories to bind to the underlying `Runnable`."""
+
+ # Union[Type[Input], BaseModel] + things like list[str]
+ custom_input_type: Any | None = None
+ """Override the input type of the underlying `Runnable` with a custom type.
+
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
+ """
+ # Union[Type[Output], BaseModel] + things like list[str]
+ custom_output_type: Any | None = None
+ """Override the output type of the underlying `Runnable` with a custom type.
+
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def __init__(
+ self,
+ *,
+ bound: Runnable[Input, Output],
+ kwargs: Mapping[str, Any] | None = None,
+ config: RunnableConfig | None = None,
+ config_factories: list[Callable[[RunnableConfig], RunnableConfig]]
+ | None = None,
+ custom_input_type: type[Input] | BaseModel | None = None,
+ custom_output_type: type[Output] | BaseModel | None = None,
+ **other_kwargs: Any,
+ ) -> None:
+ """Create a `RunnableBinding` from a `Runnable` and kwargs.
+
+ Args:
+ bound: The underlying `Runnable` that this `Runnable` delegates calls
+ to.
+ kwargs: optional kwargs to pass to the underlying `Runnable`, when running
+ the underlying `Runnable` (e.g., via `invoke`, `batch`,
+ `transform`, or `stream` or async variants)
+
+ config: optional config to bind to the underlying `Runnable`.
+
+ config_factories: optional list of config factories to apply to the
+ config before binding to the underlying `Runnable`.
+
+ custom_input_type: Specify to override the input type of the underlying
+ `Runnable` with a custom type.
+ custom_output_type: Specify to override the output type of the underlying
+ `Runnable` with a custom type.
+ **other_kwargs: Unpacked into the base class.
+ """
+ super().__init__(
+ bound=bound,
+ kwargs=kwargs or {},
+ config=config or {},
+ config_factories=config_factories or [],
+ custom_input_type=custom_input_type,
+ custom_output_type=custom_output_type,
+ **other_kwargs,
+ )
+ # if we don't explicitly set config to the TypedDict here,
+ # the pydantic init above will strip out any of the "extra"
+ # fields even though total=False on the typed dict.
+ self.config = config or {}
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ return self.bound.get_name(suffix, name=name)
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return (
+ cast("type[Input]", self.custom_input_type)
+ if self.custom_input_type is not None
+ else self.bound.InputType
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return (
+ cast("type[Output]", self.custom_output_type)
+ if self.custom_output_type is not None
+ else self.bound.OutputType
+ )
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ if self.custom_input_type is not None:
+ return super().get_input_schema(config)
+ return self.bound.get_input_schema(merge_configs(self.config, config))
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ if self.custom_output_type is not None:
+ return super().get_output_schema(config)
+ return self.bound.get_output_schema(merge_configs(self.config, config))
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.bound.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ return self.bound.get_graph(self._merge_configs(config))
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ def _merge_configs(self, *configs: RunnableConfig | None) -> RunnableConfig:
+ config = merge_configs(self.config, *configs)
+ return merge_configs(config, *(f(config) for f in self.config_factories))
+
+ @override
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ return self.bound.invoke(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ return await self.bound.ainvoke(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if isinstance(config, list):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ return self.bound.batch(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if isinstance(config, list):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ return await self.bound.abatch(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output]]: ...
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output | Exception]]: ...
+
+ @override
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> Iterator[tuple[int, Output | Exception]]:
+ if isinstance(config, Sequence):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ # lol mypy
+ if return_exceptions:
+ yield from self.bound.batch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+ else:
+ yield from self.bound.batch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output]]: ...
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]: ...
+
+ @override
+ async def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]:
+ if isinstance(config, Sequence):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ if return_exceptions:
+ async for item in self.bound.abatch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+ else:
+ async for item in self.bound.abatch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self.bound.stream(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for item in self.bound.astream(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+ @overload
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Any: ...
+
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | Any:
+ """Forward `stream_events` to the bound runnable with bound kwargs merged.
+
+ For `version="v3"`, the bound runnable's typed stream object (e.g.
+ `ChatModelStream`) is returned. For `version="v1"` / `"v2"`, dispatches
+ to the base `Runnable.stream_events`.
+
+ Without this override, `__getattr__` would drop `self.kwargs` — losing
+ tools bound via `bind_tools`, `stop` sequences, etc.
+ """
+ # Probe `version` from the merged view so `bind(version="v3")` routes
+ # correctly even when the caller doesn't repeat `version` at the call
+ # site, and strip it before forwarding so it isn't passed twice.
+ merged_kwargs = {**self.kwargs, **kwargs}
+ version = merged_kwargs.get("version", version)
+ merged_without_version = {
+ k: v for k, v in merged_kwargs.items() if k != "version"
+ }
+ if version == "v3":
+ return self.bound.stream_events(
+ input,
+ self._merge_configs(config),
+ version="v3",
+ **merged_without_version,
+ )
+ return super().stream_events(
+ input,
+ self._merge_configs(config),
+ version=version,
+ **merged_without_version,
+ )
+
+ async def _astream_events_v3(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Return the v3 async stream object from the bound runnable.
+
+ Returns an awaitable (an `async def` coroutine, not an async
+ generator) so callers can `await` it to obtain the typed stream
+ (e.g. `AsyncChatModelStream`) directly — Python does not allow
+ `return ` inside an async generator.
+
+ The caller is responsible for merging `self.kwargs` and stripping
+ `version`; this method passes `version="v3"` explicitly and would
+ raise on a duplicate keyword.
+ """
+ return await self.bound.astream_events(
+ input,
+ self._merge_configs(config),
+ version="v3",
+ **kwargs,
+ )
+
+ @overload
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ @override
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Forward `astream_events` to the bound runnable with bound kwargs merged.
+
+ For `version="v3"`, returns an awaitable that resolves to the
+ bound runnable's typed stream object (e.g. `AsyncChatModelStream`).
+ For `version="v1"` / `"v2"`, returns an async iterator over
+ `StreamEvent` items.
+
+ Without this override, `__getattr__` would drop `self.kwargs` — losing
+ tools bound via `bind_tools`, `stop` sequences, etc.
+ """
+ # Probe `version` from the merged view so `bind(version="v3")` routes
+ # correctly even when the caller doesn't repeat `version` at the call
+ # site.
+ merged_kwargs = {**self.kwargs, **kwargs}
+ version = merged_kwargs.get("version", "v2")
+ if version == "v3":
+ merged_without_version = {
+ k: v for k, v in merged_kwargs.items() if k != "version"
+ }
+ return self._astream_events_v3(input, config, **merged_without_version)
+ # v1/v2: bound.astream_events is a real async generator — iterate it
+ # directly without an extra wrapper layer.
+ return cast(
+ "AsyncIterator[StreamEvent]",
+ self.bound.astream_events(
+ input, self._merge_configs(config), **merged_kwargs
+ ),
+ )
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ yield from self.bound.transform(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ async for item in self.bound.atransform(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+
+class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
+ """Wrap a `Runnable` with additional functionality.
+
+ A `RunnableBinding` can be thought of as a "runnable decorator" that
+ preserves the essential features of `Runnable`; i.e., batching, streaming,
+ and async support, while adding additional functionality.
+
+ Any class that inherits from `Runnable` can be bound to a `RunnableBinding`.
+ Runnables expose a standard set of methods for creating `RunnableBindings`
+ or sub-classes of `RunnableBindings` (e.g., `RunnableRetry`,
+ `RunnableWithFallbacks`) that add additional functionality.
+
+ These methods include:
+
+ - `bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
+ - `with_config`: Bind config to pass to the underlying `Runnable` when running
+ it.
+ - `with_listeners`: Bind lifecycle listeners to the underlying `Runnable`.
+ - `with_types`: Override the input and output types of the underlying
+ `Runnable`.
+ - `with_retry`: Bind a retry policy to the underlying `Runnable`.
+ - `with_fallbacks`: Bind a fallback policy to the underlying `Runnable`.
+
+ Example:
+ `bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
+
+ ```python
+ # Create a Runnable binding that invokes the chat model with the
+ # additional kwarg `stop=['-']` when running it.
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI()
+ model.invoke('Say "Parrot-MAGIC"', stop=["-"]) # Should return `Parrot`
+ # Using it the easy way via `bind` method which returns a new
+ # RunnableBinding
+ runnable_binding = model.bind(stop=["-"])
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
+ ```
+ Can also be done by instantiating a `RunnableBinding` directly (not
+ recommended):
+
+ ```python
+ from langchain_core.runnables import RunnableBinding
+
+ runnable_binding = RunnableBinding(
+ bound=model,
+ kwargs={"stop": ["-"]}, # <-- Note the additional kwargs
+ )
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
+ ```
+ """
+
+ @override
+ def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
+ """Bind additional kwargs to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ **kwargs: The kwargs to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the same type and config as the original,
+ but with the additional kwargs bound.
+
+ """
+ return self.__class__(
+ bound=self.bound,
+ config=self.config,
+ config_factories=self.config_factories,
+ kwargs={**self.kwargs, **kwargs},
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=cast("RunnableConfig", {**self.config, **(config or {}), **kwargs}),
+ config_factories=self.config_factories,
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+ """
+
+ def listener_config_factory(config: RunnableConfig) -> RunnableConfig:
+ return {
+ "callbacks": [
+ RootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=[listener_config_factory, *self.config_factories],
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_types(
+ self,
+ input_type: type[Input] | BaseModel | None = None,
+ output_type: type[Output] | BaseModel | None = None,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=self.config_factories,
+ custom_input_type=(
+ input_type if input_type is not None else self.custom_input_type
+ ),
+ custom_output_type=(
+ output_type if output_type is not None else self.custom_output_type
+ ),
+ )
+
+ @override
+ def with_retry(self, **kwargs: Any) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound.with_retry(**kwargs),
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=self.config_factories,
+ )
+
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
+ attr = getattr(self.bound, name)
+
+ if callable(attr) and (
+ config_param := inspect.signature(attr).parameters.get("config")
+ ):
+ if config_param.kind == inspect.Parameter.KEYWORD_ONLY:
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ return attr(
+ *args,
+ config=merge_configs(self.config, kwargs.pop("config", None)),
+ **kwargs,
+ )
+
+ return wrapper
+ if config_param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
+ idx = list(inspect.signature(attr).parameters).index("config")
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ if len(args) >= idx + 1:
+ argsl = list(args)
+ argsl[idx] = merge_configs(self.config, argsl[idx])
+ return attr(*argsl, **kwargs)
+ return attr(
+ *args,
+ config=merge_configs(self.config, kwargs.pop("config", None)),
+ **kwargs,
+ )
+
+ return wrapper
+
+ return attr
+
+
+class _RunnableCallableSync(Protocol[Input, Output]):
+ def __call__(self, _in: Input, /, *, config: RunnableConfig) -> Output: ...
+
+
+class _RunnableCallableAsync(Protocol[Input, Output]):
+ def __call__(
+ self, _in: Input, /, *, config: RunnableConfig
+ ) -> Awaitable[Output]: ...
+
+
+class _RunnableCallableIterator(Protocol[Input, Output]):
+ def __call__(
+ self, _in: Iterator[Input], /, *, config: RunnableConfig
+ ) -> Iterator[Output]: ...
+
+
+class _RunnableCallableAsyncIterator(Protocol[Input, Output]):
+ def __call__(
+ self, _in: AsyncIterator[Input], /, *, config: RunnableConfig
+ ) -> AsyncIterator[Output]: ...
+
+
+RunnableLike = (
+ Runnable[Input, Output]
+ | Callable[[Input], Output]
+ | Callable[[Input], Awaitable[Output]]
+ | Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | _RunnableCallableSync[Input, Output]
+ | _RunnableCallableAsync[Input, Output]
+ | _RunnableCallableIterator[Input, Output]
+ | _RunnableCallableAsyncIterator[Input, Output]
+ | Mapping[str, Any]
+)
+
+
+def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]:
+ """Coerce a `Runnable`-like object into a `Runnable`.
+
+ Args:
+ thing: A `Runnable`-like object.
+
+ Returns:
+ A `Runnable`.
+
+ Raises:
+ TypeError: If the object is not `Runnable`-like.
+ """
+ if isinstance(thing, Runnable):
+ return thing
+ if is_async_generator(thing) or inspect.isgeneratorfunction(thing):
+ return RunnableGenerator(thing)
+ if callable(thing):
+ return RunnableLambda(cast("Callable[[Input], Output]", thing))
+ if isinstance(thing, dict):
+ return cast("Runnable[Input, Output]", RunnableParallel(thing))
+ msg = (
+ f"Expected a Runnable, callable or dict."
+ f"Instead got an unsupported type: {type(thing)}"
+ )
+ raise TypeError(msg)
+
+
+@overload
+def chain(
+ func: Callable[[Input], Coroutine[Any, Any, Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], Iterator[Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], AsyncIterator[Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], Output],
+) -> Runnable[Input, Output]: ...
+
+
+def chain(
+ func: Callable[[Input], Output]
+ | Callable[[Input], Iterator[Output]]
+ | Callable[[Input], Coroutine[Any, Any, Output]]
+ | Callable[[Input], AsyncIterator[Output]],
+) -> Runnable[Input, Output]:
+ """Decorate a function to make it a `Runnable`.
+
+ Sets the name of the `Runnable` to the name of the function.
+ Any runnables called by the function will be traced as dependencies.
+
+ Args:
+ func: A `Callable`.
+
+ Returns:
+ A `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import chain
+ from langchain_core.prompts import PromptTemplate
+ from langchain_openai import OpenAI
+
+
+ @chain
+ def my_func(fields):
+ prompt = PromptTemplate("Hello, {name}!")
+ model = OpenAI()
+ formatted = prompt.invoke(**fields)
+
+ for chunk in model.stream(formatted):
+ yield chunk
+ ```
+ """
+ return RunnableLambda(func)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/branch.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/branch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca3dfd99da6b983a243b45dd0c9844dc31a02755
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/branch.py
@@ -0,0 +1,461 @@
+"""Runnable that selects which branch to run based on a condition."""
+
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from typing import (
+ Any,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.runnables.base import (
+ Runnable,
+ RunnableLike,
+ RunnableSerializable,
+ coerce_to_runnable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ patch_config,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ get_unique_config_specs,
+)
+
+_MIN_BRANCHES = 2
+
+
+class RunnableBranch(RunnableSerializable[Input, Output]):
+ """`Runnable` that selects which branch to run based on a condition.
+
+ The `Runnable` is initialized with a list of `(condition, Runnable)` pairs and
+ a default branch.
+
+ When operating on an input, the first condition that evaluates to True is
+ selected, and the corresponding `Runnable` is run on the input.
+
+ If no condition evaluates to `True`, the default branch is run on the input.
+
+ Examples:
+ ```python
+ from langchain_core.runnables import RunnableBranch
+
+ branch = RunnableBranch(
+ (lambda x: isinstance(x, str), lambda x: x.upper()),
+ (lambda x: isinstance(x, int), lambda x: x + 1),
+ (lambda x: isinstance(x, float), lambda x: x * 2),
+ lambda x: "goodbye",
+ )
+
+ branch.invoke("hello") # "HELLO"
+ branch.invoke(None) # "goodbye"
+ ```
+ """
+
+ branches: Sequence[tuple[Runnable[Input, bool], Runnable[Input, Output]]]
+ """A list of `(condition, Runnable)` pairs."""
+ default: Runnable[Input, Output]
+ """A `Runnable` to run if no condition is met."""
+
+ def __init__(
+ self,
+ *branches: tuple[
+ Runnable[Input, bool]
+ | Callable[[Input], bool]
+ | Callable[[Input], Awaitable[bool]],
+ RunnableLike,
+ ]
+ | RunnableLike,
+ ) -> None:
+ """A `Runnable` that runs one of two branches based on a condition.
+
+ Args:
+ *branches: A list of `(condition, Runnable)` pairs.
+ Defaults a `Runnable` to run if no condition is met.
+
+ Raises:
+ ValueError: If the number of branches is less than `2`.
+ TypeError: If the default branch is not `Runnable`, `Callable` or `Mapping`.
+ TypeError: If a branch is not a `tuple` or `list`.
+ ValueError: If a branch is not of length `2`.
+ """
+ if len(branches) < _MIN_BRANCHES:
+ msg = "RunnableBranch requires at least two branches"
+ raise ValueError(msg)
+
+ default = branches[-1]
+
+ if not isinstance(
+ default,
+ (Runnable, Callable, Mapping), # type: ignore[arg-type]
+ ):
+ msg = "RunnableBranch default must be Runnable, callable or mapping."
+ raise TypeError(msg)
+
+ default_ = cast(
+ "Runnable[Input, Output]", coerce_to_runnable(cast("RunnableLike", default))
+ )
+
+ branches_ = []
+
+ for branch in branches[:-1]:
+ if not isinstance(branch, (tuple, list)):
+ msg = (
+ f"RunnableBranch branches must be "
+ f"tuples or lists, not {type(branch)}"
+ )
+ raise TypeError(msg)
+
+ if len(branch) != _MIN_BRANCHES:
+ msg = (
+ f"RunnableBranch branches must be "
+ f"tuples or lists of length 2, not {len(branch)}"
+ )
+ raise ValueError(msg)
+ condition, runnable = branch
+ condition = cast("Runnable[Input, bool]", coerce_to_runnable(condition))
+ runnable = coerce_to_runnable(runnable)
+ branches_.append((condition, runnable))
+
+ super().__init__(
+ branches=branches_,
+ default=default_,
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ runnables = (
+ [self.default]
+ + [r for _, r in self.branches]
+ + [r for r, _ in self.branches]
+ )
+
+ for runnable in runnables:
+ if (
+ runnable.get_input_schema(config).model_json_schema().get("type")
+ is not None
+ ):
+ return runnable.get_input_schema(config)
+
+ return super().get_input_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec
+ for step in (
+ [self.default]
+ + [r for _, r in self.branches]
+ + [r for r, _ in self.branches]
+ )
+ for spec in step.config_specs
+ )
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = condition.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ output = runnable.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ )
+ break
+ else:
+ output = self.default.invoke(
+ input,
+ config=patch_config(
+ config, callbacks=run_manager.get_child(tag="branch:default")
+ ),
+ **kwargs,
+ )
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(output)
+ return output
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = await condition.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ output = await runnable.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ )
+ break
+ else:
+ output = await self.default.ainvoke(
+ input,
+ config=patch_config(
+ config, callbacks=run_manager.get_child(tag="branch:default")
+ ),
+ **kwargs,
+ )
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(output)
+ return output
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ final_output: Output | None = None
+ final_output_supported = True
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = condition.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ for chunk in runnable.stream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ break
+ else:
+ for chunk in self.default.stream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag="branch:default"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(final_output)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ final_output: Output | None = None
+ final_output_supported = True
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = await condition.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ async for chunk in runnable.astream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ break
+ else:
+ async for chunk in self.default.astream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag="branch:default"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(final_output)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/config.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..d94d049fc5207280fccf561b497e6056d72cebfc
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/config.py
@@ -0,0 +1,672 @@
+"""Configuration utilities for `Runnable` objects."""
+
+from __future__ import annotations
+
+import asyncio
+
+# Cannot move uuid to TYPE_CHECKING as RunnableConfig is used in Pydantic models
+import uuid # noqa: TC003
+import warnings
+from collections.abc import Awaitable, Callable, Generator, Iterable, Iterator, Sequence
+from concurrent.futures import Executor, Future, ThreadPoolExecutor
+from contextlib import contextmanager
+from contextvars import Context, ContextVar, Token, copy_context
+from functools import partial
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ParamSpec,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import TypedDict
+
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.runnables.utils import (
+ Input,
+ Output,
+ accepts_config,
+ accepts_run_manager,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.base import BaseCallbackManager, Callbacks
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+else:
+ # Pydantic validates through typed dicts, but
+ # the callbacks need forward refs updated
+ Callbacks = list | Any | None
+
+
+class EmptyDict(TypedDict, total=False):
+ """Empty dict type."""
+
+
+class RunnableConfig(TypedDict, total=False):
+ """Configuration for a `Runnable`.
+
+ !!! note Custom values
+
+ The `TypedDict` has `total=False` set intentionally to:
+
+ - Allow partial configs to be created and merged together via `merge_configs`
+ - Support config propagation from parent to child runnables via
+ `var_child_runnable_config` (a `ContextVar` that automatically passes
+ config down the call stack without explicit parameter passing), where
+ configs are merged rather than replaced
+
+ !!! example
+
+ ```python
+ # Parent sets tags
+ chain.invoke(input, config={"tags": ["parent"]})
+ # Child automatically inherits and can add:
+ # ensure_config({"tags": ["child"]}) -> {"tags": ["parent", "child"]}
+ ```
+ """
+
+ tags: list[str]
+ """Tags for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ You can use these to filter calls.
+ """
+
+ metadata: dict[str, Any]
+ """Metadata for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ Keys should be strings, values should be JSON-serializable.
+ """
+
+ callbacks: Callbacks
+ """Callbacks for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
+ """
+
+ run_name: str
+ """Name for the tracer run for this call.
+
+ Defaults to the name of the class."""
+
+ max_concurrency: int | None
+ """Maximum number of parallel calls to make.
+
+ If not provided, defaults to `ThreadPoolExecutor`'s default.
+ """
+
+ recursion_limit: int
+ """Maximum number of times a call can recurse.
+
+ If not provided, defaults to `25`.
+ """
+
+ configurable: dict[str, Any]
+ """Runtime values for attributes previously made configurable on this `Runnable`,
+ or sub-`Runnable` objects, through `configurable_fields` or
+ `configurable_alternatives`.
+
+ Check `output_schema` for a description of the attributes that have been made
+ configurable.
+ """
+
+ run_id: uuid.UUID | None
+ """Unique identifier for the tracer run for this call.
+
+ If not provided, a new UUID will be generated.
+ """
+
+
+CONFIG_KEYS = [
+ "tags",
+ "metadata",
+ "callbacks",
+ "run_name",
+ "max_concurrency",
+ "recursion_limit",
+ "configurable",
+ "run_id",
+]
+
+COPIABLE_KEYS = [
+ "tags",
+ "metadata",
+ "callbacks",
+ "configurable",
+]
+
+
+# Users are expected to use the `context` API with a context object
+# (which does not get traced)
+CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS = frozenset(("api_key",))
+
+
+def _get_langsmith_inheritable_metadata_from_config(
+ config: RunnableConfig,
+) -> dict[str, Any] | None:
+ """Get LangSmith-only inheritable metadata defaults derived from config."""
+ configurable = config.get("configurable") or {}
+ metadata = {
+ key: value
+ for key, value in configurable.items()
+ if not key.startswith("__")
+ and isinstance(value, (str, int, float, bool))
+ and key not in config.get("metadata", {})
+ and key not in CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS
+ }
+ return metadata or None
+
+
+DEFAULT_RECURSION_LIMIT = 25
+
+
+var_child_runnable_config: ContextVar[RunnableConfig | None] = ContextVar(
+ "child_runnable_config", default=None
+)
+
+
+# This is imported and used in langgraph, so don't break.
+def _set_config_context(
+ config: RunnableConfig,
+) -> tuple[Token[RunnableConfig | None], dict[str, Any] | None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+
+ Returns:
+ The token to reset the config and the previous tracing context.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import ( # noqa: PLC0415
+ _set_tracing_context,
+ get_tracing_context,
+ )
+
+ from langchain_core.tracers.langchain import LangChainTracer # noqa: PLC0415
+
+ config_token = var_child_runnable_config.set(config)
+ current_context = None
+ if (
+ (callbacks := config.get("callbacks"))
+ and (
+ parent_run_id := getattr(callbacks, "parent_run_id", None)
+ ) # Is callback manager
+ and (
+ tracer := next(
+ (
+ handler
+ for handler in getattr(callbacks, "handlers", [])
+ if isinstance(handler, LangChainTracer)
+ ),
+ None,
+ )
+ )
+ and (run := tracer.run_map.get(str(parent_run_id)))
+ ):
+ current_context = get_tracing_context()
+ _set_tracing_context({"parent": run})
+ return config_token, current_context
+
+
+@contextmanager
+def set_config_context(config: RunnableConfig) -> Generator[Context, None, None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+
+ Yields:
+ The config context.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import _set_tracing_context # noqa: PLC0415
+
+ ctx = copy_context()
+ config_token, _ = ctx.run(_set_config_context, config)
+ try:
+ yield ctx
+ finally:
+ ctx.run(var_child_runnable_config.reset, config_token)
+ ctx.run(
+ _set_tracing_context,
+ {
+ "parent": None,
+ "project_name": None,
+ "tags": None,
+ "metadata": None,
+ "enabled": None,
+ "client": None,
+ },
+ )
+
+
+def ensure_config(config: RunnableConfig | None = None) -> RunnableConfig:
+ """Ensure that a config is a dict with all keys present.
+
+ Args:
+ config: The config to ensure.
+
+ Returns:
+ The ensured config.
+ """
+ empty = RunnableConfig(
+ tags=[],
+ metadata={},
+ callbacks=None,
+ recursion_limit=DEFAULT_RECURSION_LIMIT,
+ configurable={},
+ )
+ if var_config := var_child_runnable_config.get():
+ empty.update(
+ cast(
+ "RunnableConfig",
+ {
+ k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
+ for k, v in var_config.items()
+ if v is not None
+ },
+ )
+ )
+ if config is not None:
+ empty.update(
+ cast(
+ "RunnableConfig",
+ {
+ k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
+ for k, v in config.items()
+ if v is not None and k in CONFIG_KEYS
+ },
+ )
+ )
+ if config is not None:
+ for k, v in config.items():
+ if k not in CONFIG_KEYS and v is not None:
+ empty["configurable"][k] = v
+ for configurable_key in ("model", "checkpoint_ns"):
+ if (
+ isinstance(
+ configurable_value := empty.get("configurable", {}).get(
+ configurable_key
+ ),
+ str,
+ )
+ and configurable_key not in empty["metadata"]
+ ):
+ empty["metadata"][configurable_key] = configurable_value
+ return empty
+
+
+def get_config_list(
+ config: RunnableConfig | Sequence[RunnableConfig] | None, length: int
+) -> list[RunnableConfig]:
+ """Get a list of configs from a single config or a list of configs.
+
+ It is useful for subclasses overriding batch() or abatch().
+
+ Args:
+ config: The config or list of configs.
+ length: The length of the list.
+
+ Returns:
+ The list of configs.
+
+ Raises:
+ ValueError: If the length of the list is not equal to the length of the inputs.
+
+ """
+ if length < 0:
+ msg = f"length must be >= 0, but got {length}"
+ raise ValueError(msg)
+ if isinstance(config, Sequence) and len(config) != length:
+ msg = (
+ f"config must be a list of the same length as inputs, "
+ f"but got {len(config)} configs for {length} inputs"
+ )
+ raise ValueError(msg)
+
+ if isinstance(config, Sequence):
+ return list(map(ensure_config, config))
+ if length > 1 and isinstance(config, dict) and config.get("run_id") is not None:
+ warnings.warn(
+ "Provided run_id be used only for the first element of the batch.",
+ category=RuntimeWarning,
+ stacklevel=3,
+ )
+ subsequent = cast(
+ "RunnableConfig", {k: v for k, v in config.items() if k != "run_id"}
+ )
+ return [
+ ensure_config(subsequent) if i else ensure_config(config)
+ for i in range(length)
+ ]
+ return [ensure_config(config) for i in range(length)]
+
+
+def patch_config(
+ config: RunnableConfig | None,
+ *,
+ callbacks: BaseCallbackManager | None = None,
+ recursion_limit: int | None = None,
+ max_concurrency: int | None = None,
+ run_name: str | None = None,
+ configurable: dict[str, Any] | None = None,
+) -> RunnableConfig:
+ """Patch a config with new values.
+
+ Args:
+ config: The config to patch.
+ callbacks: The callbacks to set.
+ recursion_limit: The recursion limit to set.
+ max_concurrency: The max concurrency to set.
+ run_name: The run name to set.
+ configurable: The configurable to set.
+
+ Returns:
+ The patched config.
+ """
+ config = ensure_config(config)
+ if callbacks is not None:
+ # If we're replacing callbacks, we need to unset run_name
+ # As that should apply only to the same run as the original callbacks
+ config["callbacks"] = callbacks
+ if "run_name" in config:
+ del config["run_name"]
+ if "run_id" in config:
+ del config["run_id"]
+ if recursion_limit is not None:
+ config["recursion_limit"] = recursion_limit
+ if max_concurrency is not None:
+ config["max_concurrency"] = max_concurrency
+ if run_name is not None:
+ config["run_name"] = run_name
+ if configurable is not None:
+ config["configurable"] = {**config.get("configurable", {}), **configurable}
+ return config
+
+
+def merge_configs(*configs: RunnableConfig | None) -> RunnableConfig:
+ """Merge multiple configs into one.
+
+ Args:
+ *configs: The configs to merge.
+
+ Returns:
+ The merged config.
+ """
+ base: RunnableConfig = {}
+ # Even though the keys aren't literals, this is correct
+ # because both dicts are the same type
+ for config in (ensure_config(c) for c in configs if c is not None):
+ for key in config:
+ if key == "metadata":
+ base["metadata"] = {
+ **base.get("metadata", {}),
+ **(config.get("metadata") or {}),
+ }
+ elif key == "tags":
+ base["tags"] = sorted(
+ set(base.get("tags", []) + (config.get("tags") or [])),
+ )
+ elif key == "configurable":
+ base["configurable"] = {
+ **base.get("configurable", {}),
+ **(config.get("configurable") or {}),
+ }
+ elif key == "callbacks":
+ base_callbacks = base.get("callbacks")
+ these_callbacks = config["callbacks"]
+ # callbacks can be either None, list[handler] or manager
+ # so merging two callbacks values has 6 cases
+ if isinstance(these_callbacks, list):
+ if base_callbacks is None:
+ base["callbacks"] = these_callbacks.copy()
+ elif isinstance(base_callbacks, list):
+ base["callbacks"] = base_callbacks + these_callbacks
+ else:
+ # base_callbacks is a manager
+ mngr = base_callbacks.copy()
+ for callback in these_callbacks:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ elif these_callbacks is not None:
+ # these_callbacks is a manager
+ if base_callbacks is None:
+ base["callbacks"] = these_callbacks.copy()
+ elif isinstance(base_callbacks, list):
+ mngr = these_callbacks.copy()
+ for callback in base_callbacks:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ else:
+ # base_callbacks is also a manager
+ base["callbacks"] = base_callbacks.merge(these_callbacks)
+ elif key == "recursion_limit":
+ if config["recursion_limit"] != DEFAULT_RECURSION_LIMIT:
+ base["recursion_limit"] = config["recursion_limit"]
+ elif key in COPIABLE_KEYS and config[key] is not None: # type: ignore[literal-required]
+ base[key] = config[key].copy() # type: ignore[literal-required]
+ else:
+ base[key] = config[key] or base.get(key) # type: ignore[literal-required]
+ return base
+
+
+def call_func_with_variable_args(
+ func: Callable[[Input], Output]
+ | Callable[[Input, RunnableConfig], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ input: Input,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForChainRun | None = None,
+ **kwargs: Any,
+) -> Output:
+ """Call function that may optionally accept a run_manager and/or config.
+
+ Args:
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function.
+ **kwargs: The keyword arguments to pass to the function.
+
+ Returns:
+ The output of the function.
+ """
+ if accepts_config(func):
+ if run_manager is not None:
+ kwargs["config"] = patch_config(config, callbacks=run_manager.get_child())
+ else:
+ kwargs["config"] = config
+ if run_manager is not None and accepts_run_manager(func):
+ kwargs["run_manager"] = run_manager
+ return func(input, **kwargs) # type: ignore[call-arg]
+
+
+def acall_func_with_variable_args(
+ func: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ input: Input,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForChainRun | None = None,
+ **kwargs: Any,
+) -> Awaitable[Output]:
+ """Async call function that may optionally accept a run_manager and/or config.
+
+ Args:
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function.
+ **kwargs: The keyword arguments to pass to the function.
+
+ Returns:
+ The output of the function.
+ """
+ if accepts_config(func):
+ if run_manager is not None:
+ kwargs["config"] = patch_config(config, callbacks=run_manager.get_child())
+ else:
+ kwargs["config"] = config
+ if run_manager is not None and accepts_run_manager(func):
+ kwargs["run_manager"] = run_manager
+ return func(input, **kwargs) # type: ignore[call-arg]
+
+
+def get_callback_manager_for_config(config: RunnableConfig) -> CallbackManager:
+ """Get a callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ The callback manager.
+ """
+ return CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_langsmith_inheritable_metadata_from_config(
+ config
+ ),
+ )
+
+
+def get_async_callback_manager_for_config(
+ config: RunnableConfig,
+) -> AsyncCallbackManager:
+ """Get an async callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ The async callback manager.
+ """
+ return AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_langsmith_inheritable_metadata_from_config(
+ config
+ ),
+ )
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+class ContextThreadPoolExecutor(ThreadPoolExecutor):
+ """ThreadPoolExecutor that copies the context to the child thread."""
+
+ def submit( # type: ignore[override]
+ self,
+ func: Callable[P, T],
+ *args: P.args,
+ **kwargs: P.kwargs,
+ ) -> Future[T]:
+ """Submit a function to the executor.
+
+ Args:
+ func: The function to submit.
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The future for the function.
+ """
+ return super().submit(
+ cast("Callable[..., T]", partial(copy_context().run, func, *args, **kwargs))
+ )
+
+ def map(
+ self,
+ fn: Callable[..., T],
+ *iterables: Iterable[Any],
+ **kwargs: Any,
+ ) -> Iterator[T]:
+ """Map a function to multiple iterables.
+
+ Args:
+ fn: The function to map.
+ *iterables: The iterables to map over.
+ timeout: The timeout for the map.
+ chunksize: The chunksize for the map.
+
+ Returns:
+ The iterator for the mapped function.
+ """
+ contexts = [copy_context() for _ in range(len(iterables[0]))] # type: ignore[arg-type]
+
+ def _wrapped_fn(*args: Any) -> T:
+ return contexts.pop().run(fn, *args)
+
+ return super().map(
+ _wrapped_fn,
+ *iterables,
+ **kwargs,
+ )
+
+
+@contextmanager
+def get_executor_for_config(
+ config: RunnableConfig | None,
+) -> Generator[Executor, None, None]:
+ """Get an executor for a config.
+
+ Args:
+ config: The config.
+
+ Yields:
+ The executor.
+ """
+ config = config or {}
+ with ContextThreadPoolExecutor(
+ max_workers=config.get("max_concurrency")
+ ) as executor:
+ yield executor
+
+
+async def run_in_executor(
+ executor_or_config: Executor | RunnableConfig | None,
+ func: Callable[P, T],
+ *args: P.args,
+ **kwargs: P.kwargs,
+) -> T:
+ """Run a function in an executor.
+
+ Args:
+ executor_or_config: The executor or config to run in.
+ func: The function.
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The output of the function.
+ """
+
+ def wrapper() -> T:
+ try:
+ return func(*args, **kwargs)
+ except StopIteration as exc:
+ # StopIteration can't be set on an asyncio.Future
+ # it raises a TypeError and leaves the Future pending forever
+ # so we need to convert it to a RuntimeError
+ raise RuntimeError from exc
+
+ if executor_or_config is None or isinstance(executor_or_config, dict):
+ # Use default executor with context copied from current context
+ return await asyncio.get_running_loop().run_in_executor(
+ None,
+ cast("Callable[..., T]", partial(copy_context().run, wrapper)),
+ )
+
+ return await asyncio.get_running_loop().run_in_executor(executor_or_config, wrapper)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/configurable.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/configurable.py
new file mode 100644
index 0000000000000000000000000000000000000000..a03108850fa98e00f03c7036f9b39a331ed1eb7c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/configurable.py
@@ -0,0 +1,716 @@
+"""`Runnable` objects that can be dynamically configured."""
+
+from __future__ import annotations
+
+import enum
+import threading
+from abc import abstractmethod
+from collections.abc import (
+ AsyncIterator,
+ Callable,
+ Iterator,
+ Sequence,
+)
+from functools import wraps
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+from weakref import WeakValueDictionary
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_config_list,
+ get_executor_for_config,
+ merge_configs,
+)
+from langchain_core.runnables.utils import (
+ AnyConfigurableField,
+ ConfigurableField,
+ ConfigurableFieldMultiOption,
+ ConfigurableFieldSingleOption,
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ gather_with_concurrency,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.graph import Graph
+
+
+class DynamicRunnable(RunnableSerializable[Input, Output]):
+ """Serializable `Runnable` that can be dynamically configured.
+
+ A `DynamicRunnable` should be initiated using the `configurable_fields` or
+ `configurable_alternatives` method of a `Runnable`.
+ """
+
+ default: RunnableSerializable[Input, Output]
+ """The default `Runnable` to use."""
+
+ config: RunnableConfig | None = None
+ """The configuration to use."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return self.default.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self.default.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ runnable, config = self.prepare(config)
+ return runnable.get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ runnable, config = self.prepare(config)
+ return runnable.get_output_schema(config)
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ runnable, config = self.prepare(config)
+ return runnable.get_graph(config)
+
+ @override
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ **{**self.__dict__, "config": ensure_config(merge_configs(config, kwargs))} # type: ignore[arg-type]
+ )
+
+ def prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ """Prepare the `Runnable` for invocation.
+
+ Args:
+ config: The configuration to use.
+
+ Returns:
+ The prepared `Runnable` and configuration.
+ """
+ runnable: Runnable[Input, Output] = self
+ while isinstance(runnable, DynamicRunnable):
+ runnable, config = runnable._prepare(merge_configs(runnable.config, config)) # noqa: SLF001
+ return runnable, cast("RunnableConfig", config)
+
+ @abstractmethod
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]: ...
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ runnable, config = self.prepare(config)
+ return runnable.invoke(input, config, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ runnable, config = self.prepare(config)
+ return await runnable.ainvoke(input, config, **kwargs)
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ configs = get_config_list(config, len(inputs))
+ prepared = [self.prepare(c) for c in configs]
+
+ if all(p is self.default for p, _ in prepared):
+ return self.default.batch(
+ inputs,
+ [c for _, c in prepared],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+
+ if not inputs:
+ return []
+
+ def invoke(
+ prepared: tuple[Runnable[Input, Output], RunnableConfig],
+ input_: Input,
+ ) -> Output | Exception:
+ bound, config = prepared
+ if return_exceptions:
+ try:
+ return bound.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return bound.invoke(input_, config, **kwargs)
+
+ # If there's only one input, don't bother with the executor
+ if len(inputs) == 1:
+ return cast("list[Output]", [invoke(prepared[0], inputs[0])])
+
+ with get_executor_for_config(configs[0]) as executor:
+ return cast("list[Output]", list(executor.map(invoke, prepared, inputs)))
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ configs = get_config_list(config, len(inputs))
+ prepared = [self.prepare(c) for c in configs]
+
+ if all(p is self.default for p, _ in prepared):
+ return await self.default.abatch(
+ inputs,
+ [c for _, c in prepared],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+
+ if not inputs:
+ return []
+
+ async def ainvoke(
+ prepared: tuple[Runnable[Input, Output], RunnableConfig],
+ input_: Input,
+ ) -> Output | Exception:
+ bound, config = prepared
+ if return_exceptions:
+ try:
+ return await bound.ainvoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await bound.ainvoke(input_, config, **kwargs)
+
+ coros = map(ainvoke, prepared, inputs)
+ return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros)
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ runnable, config = self.prepare(config)
+ return runnable.stream(input, config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ runnable, config = self.prepare(config)
+ async for chunk in runnable.astream(input, config, **kwargs):
+ yield chunk
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ runnable, config = self.prepare(config)
+ return runnable.transform(input, config, **kwargs)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ runnable, config = self.prepare(config)
+ async for chunk in runnable.atransform(input, config, **kwargs):
+ yield chunk
+
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
+ attr = getattr(self.default, name)
+ if callable(attr):
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ for key, arg in kwargs.items():
+ if key == "config" and (
+ isinstance(arg, dict)
+ and "configurable" in arg
+ and isinstance(arg["configurable"], dict)
+ ):
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
+ kwargs = {**kwargs, "config": config}
+ return getattr(runnable, name)(*args, **kwargs)
+
+ for idx, arg in enumerate(args):
+ if (
+ isinstance(arg, dict)
+ and "configurable" in arg
+ and isinstance(arg["configurable"], dict)
+ ):
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
+ argsl = list(args)
+ argsl[idx] = config
+ return getattr(runnable, name)(*argsl, **kwargs)
+
+ if self.config:
+ runnable, config = self.prepare()
+ return getattr(runnable, name)(*args, **kwargs)
+
+ return attr(*args, **kwargs)
+
+ return wrapper
+
+ return attr
+
+
+class RunnableConfigurableFields(DynamicRunnable[Input, Output]):
+ """`Runnable` that can be dynamically configured.
+
+ A `RunnableConfigurableFields` should be initiated using the
+ `configurable_fields` method of a `Runnable`.
+
+ Here is an example of using a `RunnableConfigurableFields` with LLMs:
+
+ ```python
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(temperature=0).configurable_fields(
+ temperature=ConfigurableField(
+ id="temperature",
+ name="LLM Temperature",
+ description="The temperature of the LLM",
+ )
+ )
+ # This creates a RunnableConfigurableFields for a chat model.
+
+ # When invoking the created RunnableSequence, you can pass in the
+ # value for your ConfigurableField's id which in this case
+ # will be change in temperature
+
+ prompt = PromptTemplate.from_template("Pick a random number above {x}")
+ chain = prompt | model
+
+ chain.invoke({"x": 0})
+ chain.invoke({"x": 0}, config={"configurable": {"temperature": 0.9}})
+ ```
+
+ Here is an example of using a `RunnableConfigurableFields` with `HubRunnables`:
+
+ ```python
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+ from langchain.runnables.hub import HubRunnable
+
+ prompt = HubRunnable("rlm/rag-prompt").configurable_fields(
+ owner_repo_commit=ConfigurableField(
+ id="hub_commit",
+ name="Hub Commit",
+ description="The Hub commit to pull from",
+ )
+ )
+
+ prompt.invoke({"question": "foo", "context": "bar"})
+
+ # Invoking prompt with `with_config` method
+
+ prompt.invoke(
+ {"question": "foo", "context": "bar"},
+ config={"configurable": {"hub_commit": "rlm/rag-prompt-llama"}},
+ )
+ ```
+ """
+
+ fields: dict[str, AnyConfigurableField]
+ """The configurable fields to use."""
+
+ @property
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the configuration specs for the `RunnableConfigurableFields`.
+
+ Returns:
+ The configuration specs.
+ """
+ config_specs = []
+
+ default_fields = type(self.default).model_fields
+ for field_name, spec in self.fields.items():
+ if isinstance(spec, ConfigurableField):
+ config_specs.append(
+ ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description
+ or default_fields[field_name].description,
+ annotation=spec.annotation
+ or default_fields[field_name].annotation,
+ default=getattr(self.default, field_name),
+ is_shared=spec.is_shared,
+ )
+ )
+ else:
+ config_specs.append(
+ make_options_spec(spec, default_fields[field_name].description)
+ )
+
+ config_specs.extend(self.default.config_specs)
+
+ return get_unique_config_specs(config_specs)
+
+ @override
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ return self.default.configurable_fields(**{**self.fields, **kwargs})
+
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ config = ensure_config(config)
+ specs_by_id = {spec.id: (key, spec) for key, spec in self.fields.items()}
+ configurable_fields = {
+ specs_by_id[k][0]: v
+ for k, v in config.get("configurable", {}).items()
+ if k in specs_by_id and isinstance(specs_by_id[k][1], ConfigurableField)
+ }
+ configurable_single_options = {
+ k: v.options[(config.get("configurable", {}).get(v.id) or v.default)]
+ for k, v in self.fields.items()
+ if isinstance(v, ConfigurableFieldSingleOption)
+ }
+ configurable_multi_options = {
+ k: [
+ v.options[o]
+ for o in config.get("configurable", {}).get(v.id, v.default)
+ ]
+ for k, v in self.fields.items()
+ if isinstance(v, ConfigurableFieldMultiOption)
+ }
+ configurable = {
+ **configurable_fields,
+ **configurable_single_options,
+ **configurable_multi_options,
+ }
+
+ if configurable:
+ init_params = {
+ k: v
+ for k, v in self.default.__dict__.items()
+ if k in type(self.default).model_fields
+ }
+ return (
+ self.default.__class__(**{**init_params, **configurable}),
+ config,
+ )
+ return (self.default, config)
+
+
+# Before Python 3.11 native StrEnum is not available
+class StrEnum(str, enum.Enum):
+ """String enum."""
+
+
+_enums_for_spec: WeakValueDictionary[
+ ConfigurableFieldSingleOption | ConfigurableFieldMultiOption | ConfigurableField,
+ type[StrEnum],
+] = WeakValueDictionary()
+
+_enums_for_spec_lock = threading.Lock()
+
+
+class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
+ """`Runnable` that can be dynamically configured.
+
+ A `RunnableConfigurableAlternatives` should be initiated using the
+ `configurable_alternatives` method of a `Runnable` or can be
+ initiated directly as well.
+
+ Here is an example of using a `RunnableConfigurableAlternatives` that uses
+ alternative prompts to illustrate its functionality:
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ # This creates a RunnableConfigurableAlternatives for Prompt Runnable
+ # with two alternatives.
+ prompt = PromptTemplate.from_template(
+ "Tell me a joke about {topic}"
+ ).configurable_alternatives(
+ ConfigurableField(id="prompt"),
+ default_key="joke",
+ poem=PromptTemplate.from_template("Write a short poem about {topic}"),
+ )
+
+ # When invoking the created RunnableSequence, you can pass in the
+ # value for your ConfigurableField's id which in this case will either be
+ # `joke` or `poem`.
+ chain = prompt | ChatOpenAI(model="gpt-5.4-mini")
+
+ # The `with_config` method brings in the desired Prompt Runnable in your
+ # Runnable Sequence.
+ chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"})
+ ```
+
+ Equivalently, you can initialize `RunnableConfigurableAlternatives` directly
+ and use in LCEL in the same way:
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_core.runnables.configurable import (
+ RunnableConfigurableAlternatives,
+ )
+ from langchain_openai import ChatOpenAI
+
+ prompt = RunnableConfigurableAlternatives(
+ which=ConfigurableField(id="prompt"),
+ default=PromptTemplate.from_template("Tell me a joke about {topic}"),
+ default_key="joke",
+ prefix_keys=False,
+ alternatives={
+ "poem": PromptTemplate.from_template("Write a short poem about {topic}")
+ },
+ )
+ chain = prompt | ChatOpenAI(model="gpt-5.4-mini")
+ chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"})
+ ```
+ """
+
+ which: ConfigurableField
+ """The `ConfigurableField` to use to choose between alternatives."""
+
+ alternatives: dict[
+ str,
+ Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
+ ]
+ """The alternatives to choose from."""
+
+ default_key: str = "default"
+ """The enum value to use for the default option."""
+
+ prefix_keys: bool
+ """Whether to prefix configurable fields of each alternative with a namespace
+ of the form ==, e.g. a key named "temperature" used by
+ the alternative named "gpt3" becomes "model==gpt3/temperature".
+ """
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ with _enums_for_spec_lock:
+ if which_enum := _enums_for_spec.get(self.which):
+ pass
+ else:
+ which_enum = StrEnum( # type: ignore[call-overload]
+ self.which.name or self.which.id,
+ (
+ (v, v)
+ for v in [*list(self.alternatives.keys()), self.default_key]
+ ),
+ )
+ _enums_for_spec[self.which] = cast("type[StrEnum]", which_enum)
+ return get_unique_config_specs(
+ # which alternative
+ [
+ ConfigurableFieldSpec(
+ id=self.which.id,
+ name=self.which.name,
+ description=self.which.description,
+ annotation=which_enum,
+ default=self.default_key,
+ is_shared=self.which.is_shared,
+ ),
+ ]
+ # config specs of the default option
+ + (
+ [
+ prefix_config_spec(s, f"{self.which.id}=={self.default_key}")
+ for s in self.default.config_specs
+ ]
+ if self.prefix_keys
+ else self.default.config_specs
+ )
+ # config specs of the alternatives
+ + [
+ (
+ prefix_config_spec(s, f"{self.which.id}=={alt_key}")
+ if self.prefix_keys
+ else s
+ )
+ for alt_key, alt in self.alternatives.items()
+ if isinstance(alt, RunnableSerializable)
+ for s in alt.config_specs
+ ]
+ )
+
+ @override
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ return self.__class__(
+ which=self.which,
+ default=self.default.configurable_fields(**kwargs),
+ alternatives=self.alternatives,
+ default_key=self.default_key,
+ prefix_keys=self.prefix_keys,
+ )
+
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ config = ensure_config(config)
+ which = config.get("configurable", {}).get(self.which.id, self.default_key)
+ # remap configurable keys for the chosen alternative
+ if self.prefix_keys:
+ config = cast(
+ "RunnableConfig",
+ {
+ **config,
+ "configurable": {
+ _strremoveprefix(k, f"{self.which.id}=={which}/"): v
+ for k, v in config.get("configurable", {}).items()
+ },
+ },
+ )
+ # return the chosen alternative
+ if which == self.default_key:
+ return (self.default, config)
+ if which in self.alternatives:
+ alt = self.alternatives[which]
+ if isinstance(alt, Runnable):
+ return (alt, config)
+ return (alt(), config)
+ msg = f"Unknown alternative: {which}"
+ raise ValueError(msg)
+
+
+def _strremoveprefix(s: str, prefix: str) -> str:
+ """`str.removeprefix()` is only available in Python 3.9+."""
+ return s.replace(prefix, "", 1) if s.startswith(prefix) else s
+
+
+def prefix_config_spec(
+ spec: ConfigurableFieldSpec, prefix: str
+) -> ConfigurableFieldSpec:
+ """Prefix the id of a `ConfigurableFieldSpec`.
+
+ This is useful when a `RunnableConfigurableAlternatives` is used as a
+ `ConfigurableField` of another `RunnableConfigurableAlternatives`.
+
+ Args:
+ spec: The `ConfigurableFieldSpec` to prefix.
+ prefix: The prefix to add.
+
+ Returns:
+ The prefixed `ConfigurableFieldSpec`.
+ """
+ return (
+ ConfigurableFieldSpec(
+ id=f"{prefix}/{spec.id}",
+ name=spec.name,
+ description=spec.description,
+ annotation=spec.annotation,
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
+ if not spec.is_shared
+ else spec
+ )
+
+
+def make_options_spec(
+ spec: ConfigurableFieldSingleOption | ConfigurableFieldMultiOption,
+ description: str | None,
+) -> ConfigurableFieldSpec:
+ """Make options spec.
+
+ Make a `ConfigurableFieldSpec` for a `ConfigurableFieldSingleOption` or
+ `ConfigurableFieldMultiOption`.
+
+ Args:
+ spec: The `ConfigurableFieldSingleOption` or `ConfigurableFieldMultiOption`.
+ description: The description to use if the spec does not have one.
+
+ Returns:
+ The `ConfigurableFieldSpec`.
+ """
+ with _enums_for_spec_lock:
+ if enum := _enums_for_spec.get(spec):
+ pass
+ else:
+ enum = StrEnum( # type: ignore[call-overload]
+ spec.name or spec.id,
+ ((v, v) for v in list(spec.options.keys())),
+ )
+ _enums_for_spec[spec] = cast("type[StrEnum]", enum)
+ if isinstance(spec, ConfigurableFieldSingleOption):
+ return ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description or description,
+ annotation=enum,
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
+ return ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description or description,
+ annotation=Sequence[enum], # type: ignore[valid-type]
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/fallbacks.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/fallbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..72fb6b4f693f5c642074ac85f0f5224628bf4ebb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/fallbacks.py
@@ -0,0 +1,664 @@
+"""`Runnable` that can fallback to other `Runnable` objects if it fails."""
+
+import asyncio
+import inspect
+import typing
+from collections.abc import AsyncIterator, Iterator, Sequence
+from functools import wraps
+from typing import TYPE_CHECKING, Any, cast
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ get_config_list,
+ patch_config,
+ set_config_context,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ coro_with_context,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import AsyncCallbackManagerForChainRun
+
+
+class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
+ """`Runnable` that can fallback to other `Runnable` objects if it fails.
+
+ External APIs (e.g., APIs for a language model) may at times experience
+ degraded performance or even downtime.
+
+ In these cases, it can be useful to have a fallback `Runnable` that can be
+ used in place of the original `Runnable` (e.g., fallback to another LLM provider).
+
+ Fallbacks can be defined at the level of a single `Runnable`, or at the level
+ of a chain of `Runnable`s. Fallbacks are tried in order until one succeeds or
+ all fail.
+
+ While you can instantiate a `RunnableWithFallbacks` directly, it is usually
+ more convenient to use the `with_fallbacks` method on a `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.chat_models.openai import ChatOpenAI
+ from langchain_core.chat_models.anthropic import ChatAnthropic
+
+ model = ChatAnthropic(model="claude-sonnet-4-6").with_fallbacks(
+ [ChatOpenAI(model="gpt-5.4-mini")]
+ )
+ # Will usually use ChatAnthropic, but fallback to ChatOpenAI
+ # if ChatAnthropic fails.
+ model.invoke("hello")
+
+ # And you can also use fallbacks at the level of a chain.
+ # Here if both LLM providers fail, we'll fallback to a good hardcoded
+ # response.
+
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.output_parser import StrOutputParser
+ from langchain_core.runnables import RunnableLambda
+
+
+ def when_all_is_lost(inputs):
+ return (
+ "Looks like our LLM providers are down. "
+ "Here's a nice 🦜️ emoji for you instead."
+ )
+
+
+ chain_with_fallback = (
+ PromptTemplate.from_template("Tell me a joke about {topic}")
+ | model
+ | StrOutputParser()
+ ).with_fallbacks([RunnableLambda(when_all_is_lost)])
+ ```
+ """
+
+ runnable: Runnable[Input, Output]
+ """The `Runnable` to run first."""
+ fallbacks: Sequence[Runnable[Input, Output]]
+ """A sequence of fallbacks to try."""
+ exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,)
+ """The exceptions on which fallbacks should be tried.
+
+ Any exception that is not a subclass of these exceptions will be raised immediately.
+ """
+ exception_key: str | None = None
+ """If `string` is specified then handled exceptions will be passed to fallbacks as
+ part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a dictionary as input.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return self.runnable.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self.runnable.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ return self.runnable.get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ return self.runnable.get_output_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec
+ for step in [self.runnable, *self.fallbacks]
+ for spec in step.config_specs
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ def runnables(self) -> Iterator[Runnable[Input, Output]]:
+ """Iterator over the `Runnable` and its fallbacks.
+
+ Yields:
+ The `Runnable` then its fallbacks.
+ """
+ yield self.runnable
+ yield from self.fallbacks
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ output = context.run(
+ runnable.invoke,
+ input,
+ config,
+ **kwargs,
+ )
+ except self.exceptions_to_handle as e:
+ if first_error is None:
+ first_error = e
+ last_error = e
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+ if first_error is None:
+ msg = "No error stored at end of fallbacks."
+ raise ValueError(msg)
+ run_manager.on_chain_error(first_error)
+ raise first_error
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ coro = context.run(runnable.ainvoke, input, config, **kwargs)
+ output = await coro_with_context(coro, context)
+ except self.exceptions_to_handle as e:
+ if first_error is None:
+ first_error = e
+ last_error = e
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+ if first_error is None:
+ msg = "No error stored at end of fallbacks."
+ raise ValueError(msg)
+ await run_manager.on_chain_error(first_error)
+ raise first_error
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if self.exception_key is not None and not all(
+ isinstance(input_, dict) for input_ in inputs
+ ):
+ msg = (
+ "If 'exception_key' is specified then inputs must be dictionaries."
+ f"However found a type of {type(inputs[0])} for input"
+ )
+ raise ValueError(msg)
+
+ if not inputs:
+ return []
+
+ # setup callbacks
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers = [
+ cm.on_chain_start(
+ None,
+ input_ if isinstance(input_, dict) else {"input": input_},
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+
+ to_return: dict[int, Any] = {}
+ run_again = dict(enumerate(inputs))
+ handled_exceptions: dict[int, BaseException] = {}
+ first_to_raise = None
+ for runnable in self.runnables:
+ outputs = runnable.batch(
+ [input_ for _, input_ in sorted(run_again.items())],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(configs[i], callbacks=run_managers[i].get_child())
+ for i in sorted(run_again)
+ ],
+ return_exceptions=True,
+ **kwargs,
+ )
+ for (i, input_), output in zip(
+ sorted(run_again.copy().items()), outputs, strict=False
+ ):
+ if isinstance(output, BaseException) and not isinstance(
+ output, self.exceptions_to_handle
+ ):
+ if not return_exceptions:
+ first_to_raise = first_to_raise or output
+ else:
+ handled_exceptions[i] = output
+ run_again.pop(i)
+ elif isinstance(output, self.exceptions_to_handle):
+ if self.exception_key:
+ input_[self.exception_key] = output # type: ignore[index]
+ handled_exceptions[i] = output
+ else:
+ run_managers[i].on_chain_end(output)
+ to_return[i] = output
+ run_again.pop(i)
+ handled_exceptions.pop(i, None)
+ if first_to_raise:
+ raise first_to_raise
+ if not run_again:
+ break
+
+ sorted_handled_exceptions = sorted(handled_exceptions.items())
+ for i, error in sorted_handled_exceptions:
+ run_managers[i].on_chain_error(error)
+ if not return_exceptions and sorted_handled_exceptions:
+ raise sorted_handled_exceptions[0][1]
+ to_return.update(handled_exceptions)
+ return [output for _, output in sorted(to_return.items())]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if self.exception_key is not None and not all(
+ isinstance(input_, dict) for input_ in inputs
+ ):
+ msg = (
+ "If 'exception_key' is specified then inputs must be dictionaries."
+ f"However found a type of {type(inputs[0])} for input"
+ )
+ raise ValueError(msg)
+
+ if not inputs:
+ return []
+
+ # setup callbacks
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+
+ to_return: dict[int, Output | BaseException] = {}
+ run_again = dict(enumerate(inputs))
+ handled_exceptions: dict[int, BaseException] = {}
+ first_to_raise = None
+ for runnable in self.runnables:
+ outputs = await runnable.abatch(
+ [input_ for _, input_ in sorted(run_again.items())],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(configs[i], callbacks=run_managers[i].get_child())
+ for i in sorted(run_again)
+ ],
+ return_exceptions=True,
+ **kwargs,
+ )
+
+ for (i, input_), output in zip(
+ sorted(run_again.copy().items()), outputs, strict=False
+ ):
+ if isinstance(output, BaseException) and not isinstance(
+ output, self.exceptions_to_handle
+ ):
+ if not return_exceptions:
+ first_to_raise = first_to_raise or output
+ else:
+ handled_exceptions[i] = output
+ run_again.pop(i)
+ elif isinstance(output, self.exceptions_to_handle):
+ if self.exception_key:
+ input_[self.exception_key] = output # type: ignore[index]
+ handled_exceptions[i] = output
+ else:
+ to_return[i] = output
+ await run_managers[i].on_chain_end(output)
+ run_again.pop(i)
+ handled_exceptions.pop(i, None)
+
+ if first_to_raise:
+ raise first_to_raise
+ if not run_again:
+ break
+
+ sorted_handled_exceptions = sorted(handled_exceptions.items())
+ await asyncio.gather(
+ *(
+ run_managers[i].on_chain_error(error)
+ for i, error in sorted_handled_exceptions
+ )
+ )
+ if not return_exceptions and sorted_handled_exceptions:
+ raise sorted_handled_exceptions[0][1]
+ to_return.update(handled_exceptions)
+ return [cast("Output", output) for _, output in sorted(to_return.items())]
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ stream = context.run(
+ runnable.stream,
+ input,
+ **kwargs,
+ )
+ chunk: Output = context.run(next, stream)
+ except self.exceptions_to_handle as e:
+ first_error = e if first_error is None else first_error
+ last_error = e
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ first_error = None
+ break
+ if first_error:
+ run_manager.on_chain_error(first_error)
+ raise first_error
+
+ yield chunk
+ output: Output | None = chunk
+ try:
+ for chunk in stream:
+ yield chunk
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = None
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(output)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ stream = runnable.astream(
+ input,
+ child_config,
+ **kwargs,
+ )
+ chunk = await coro_with_context(anext(stream), context)
+ except self.exceptions_to_handle as e:
+ first_error = e if first_error is None else first_error
+ last_error = e
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ first_error = None
+ break
+ if first_error:
+ await run_manager.on_chain_error(first_error)
+ raise first_error
+
+ yield chunk
+ output: Output | None = chunk
+ try:
+ async for chunk in stream:
+ yield chunk
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = None
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(output)
+
+ def __getattr__(self, name: str) -> Any:
+ """Get an attribute from the wrapped `Runnable` and its fallbacks.
+
+ Returns:
+ If the attribute is anything other than a method that outputs a `Runnable`,
+ returns `getattr(self.runnable, name)`. If the attribute is a method that
+ does return a new `Runnable` (e.g. `model.bind_tools([...])` outputs a new
+ `RunnableBinding`) then `self.runnable` and each of the runnables in
+ `self.fallbacks` is replaced with `getattr(x, name)`.
+
+ Example:
+ ```python
+ from langchain_openai import ChatOpenAI
+ from langchain_anthropic import ChatAnthropic
+
+ gpt_4o = ChatOpenAI(model="gpt-4o")
+ claude_3_sonnet = ChatAnthropic(model="claude-sonnet-4-5-20250929")
+ model = gpt_4o.with_fallbacks([claude_3_sonnet])
+
+ model.model_name
+ # -> "gpt-4o"
+
+ # .bind_tools() is called on both ChatOpenAI and ChatAnthropic
+ # Equivalent to:
+ # gpt_4o.bind_tools([...]).with_fallbacks([claude_3_sonnet.bind_tools([...])])
+ model.bind_tools([...])
+ # -> RunnableWithFallbacks(
+ runnable=RunnableBinding(bound=ChatOpenAI(...), kwargs={"tools": [...]}),
+ fallbacks=[RunnableBinding(bound=ChatAnthropic(...), kwargs={"tools": [...]})],
+ )
+ ```
+ """ # noqa: E501
+ attr = getattr(self.runnable, name)
+ if _returns_runnable(attr):
+
+ @wraps(attr)
+ def wrapped(*args: Any, **kwargs: Any) -> Any:
+ new_runnable = attr(*args, **kwargs)
+ new_fallbacks = []
+ for fallback in self.fallbacks:
+ fallback_attr = getattr(fallback, name)
+ new_fallbacks.append(fallback_attr(*args, **kwargs))
+
+ return self.__class__(
+ **{
+ **self.model_dump(),
+ "runnable": new_runnable,
+ "fallbacks": new_fallbacks,
+ }
+ )
+
+ return wrapped
+
+ return attr
+
+
+def _returns_runnable(attr: Any) -> bool:
+ if not callable(attr):
+ return False
+ return_type = typing.get_type_hints(attr).get("return")
+ return bool(return_type and _is_runnable_type(return_type))
+
+
+def _is_runnable_type(type_: Any) -> bool:
+ if inspect.isclass(type_):
+ return issubclass(type_, Runnable)
+ origin = getattr(type_, "__origin__", None)
+ if inspect.isclass(origin):
+ return issubclass(origin, Runnable)
+ if origin is typing.Union:
+ return all(_is_runnable_type(t) for t in type_.__args__)
+ return False
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/graph.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdab7d48846b63511229cf0723785deb489529d5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph.py
@@ -0,0 +1,739 @@
+"""Graph used in `Runnable` objects."""
+
+from __future__ import annotations
+
+import inspect
+from collections import defaultdict
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ NamedTuple,
+ Protocol,
+ TypedDict,
+ overload,
+)
+from uuid import UUID, uuid4
+
+from langchain_core.load.serializable import to_json_not_implemented
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.utils.pydantic import _IgnoreUnserializable, is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Sequence
+
+ from pydantic import BaseModel
+
+ from langchain_core.runnables.base import Runnable as RunnableType
+
+
+class Stringifiable(Protocol):
+ """Protocol for objects that can be converted to a string."""
+
+ def __str__(self) -> str:
+ """Convert the object to a string."""
+
+
+class LabelsDict(TypedDict):
+ """Dictionary of labels for nodes and edges in a graph."""
+
+ nodes: dict[str, str]
+ """Labels for nodes."""
+ edges: dict[str, str]
+ """Labels for edges."""
+
+
+def is_uuid(value: str) -> bool:
+ """Check if a string is a valid UUID.
+
+ Args:
+ value: The string to check.
+
+ Returns:
+ `True` if the string is a valid UUID, `False` otherwise.
+ """
+ try:
+ UUID(value)
+ except ValueError:
+ return False
+ return True
+
+
+class Edge(NamedTuple):
+ """Edge in a graph."""
+
+ source: str
+ """The source node id."""
+ target: str
+ """The target node id."""
+ data: Stringifiable | None = None
+ """Optional data associated with the edge. """
+ conditional: bool = False
+ """Whether the edge is conditional."""
+
+ def copy(self, *, source: str | None = None, target: str | None = None) -> Edge:
+ """Return a copy of the edge with optional new source and target nodes.
+
+ Args:
+ source: The new source node id.
+ target: The new target node id.
+
+ Returns:
+ A copy of the edge with the new source and target nodes.
+ """
+ return Edge(
+ source=source or self.source,
+ target=target or self.target,
+ data=self.data,
+ conditional=self.conditional,
+ )
+
+
+class Node(NamedTuple):
+ """Node in a graph."""
+
+ id: str
+ """The unique identifier of the node."""
+ name: str
+ """The name of the node."""
+ data: type[BaseModel] | RunnableType | None
+ """The data of the node."""
+ metadata: dict[str, Any] | None
+ """Optional metadata for the node. """
+
+ def copy(
+ self,
+ *,
+ id: str | None = None,
+ name: str | None = None,
+ ) -> Node:
+ """Return a copy of the node with optional new id and name.
+
+ Args:
+ id: The new node id.
+ name: The new node name.
+
+ Returns:
+ A copy of the node with the new id and name.
+ """
+ return Node(
+ id=id or self.id,
+ name=name or self.name,
+ data=self.data,
+ metadata=self.metadata,
+ )
+
+
+class Branch(NamedTuple):
+ """Branch in a graph."""
+
+ condition: Callable[..., str]
+ """A callable that returns a string representation of the condition."""
+ ends: dict[str, str] | None
+ """Optional dictionary of end node IDs for the branches. """
+
+
+class CurveStyle(Enum):
+ """Enum for different curve styles supported by Mermaid."""
+
+ BASIS = "basis"
+ BUMP_X = "bumpX"
+ BUMP_Y = "bumpY"
+ CARDINAL = "cardinal"
+ CATMULL_ROM = "catmullRom"
+ LINEAR = "linear"
+ MONOTONE_X = "monotoneX"
+ MONOTONE_Y = "monotoneY"
+ NATURAL = "natural"
+ STEP = "step"
+ STEP_AFTER = "stepAfter"
+ STEP_BEFORE = "stepBefore"
+
+
+@dataclass
+class NodeStyles:
+ """Schema for Hexadecimal color codes for different node types.
+
+ Args:
+ default: The default color code.
+ first: The color code for the first node.
+ last: The color code for the last node.
+ """
+
+ default: str = "fill:#f2f0ff,line-height:1.2"
+ first: str = "fill-opacity:0"
+ last: str = "fill:#bfb6fc"
+
+
+class MermaidDrawMethod(Enum):
+ """Enum for different draw methods supported by Mermaid."""
+
+ PYPPETEER = "pyppeteer"
+ """Uses Pyppeteer to render the graph"""
+ API = "api"
+ """Uses Mermaid.INK API to render the graph"""
+
+
+def node_data_str(
+ id: str,
+ data: type[BaseModel] | RunnableType | None,
+) -> str:
+ """Convert the data of a node to a string.
+
+ Args:
+ id: The node id.
+ data: The node data.
+
+ Returns:
+ A string representation of the data.
+ """
+ if not is_uuid(id) or data is None:
+ return id
+ data_str = data.get_name() if isinstance(data, Runnable) else data.__name__
+ return data_str if not data_str.startswith("Runnable") else data_str[8:]
+
+
+def node_data_json(
+ node: Node, *, with_schemas: bool = False
+) -> dict[str, str | dict[str, Any]]:
+ """Convert the data of a node to a JSON-serializable format.
+
+ Args:
+ node: The `Node` to convert.
+ with_schemas: Whether to include the schema of the data if it is a Pydantic
+ model.
+
+ Returns:
+ A dictionary with the type of the data and the data itself.
+ """
+ if node.data is None:
+ json: dict[str, Any] = {}
+ elif isinstance(node.data, RunnableSerializable):
+ json = {
+ "type": "runnable",
+ "data": {
+ "id": node.data.lc_id(),
+ "name": node_data_str(node.id, node.data),
+ },
+ }
+ elif isinstance(node.data, Runnable):
+ json = {
+ "type": "runnable",
+ "data": {
+ "id": to_json_not_implemented(node.data)["id"],
+ "name": node_data_str(node.id, node.data),
+ },
+ }
+ elif inspect.isclass(node.data) and is_basemodel_subclass(node.data):
+ json = (
+ {
+ "type": "schema",
+ "data": node.data.model_json_schema(
+ schema_generator=_IgnoreUnserializable
+ ),
+ }
+ if with_schemas
+ else {
+ "type": "schema",
+ "data": node_data_str(node.id, node.data),
+ }
+ )
+ else:
+ json = {
+ "type": "unknown",
+ "data": node_data_str(node.id, node.data),
+ }
+ if node.metadata is not None:
+ json["metadata"] = node.metadata
+ return json
+
+
+@dataclass
+class Graph:
+ """Graph of nodes and edges.
+
+ Args:
+ nodes: Dictionary of nodes in the graph. Defaults to an empty dictionary.
+ edges: List of edges in the graph. Defaults to an empty list.
+ """
+
+ nodes: dict[str, Node] = field(default_factory=dict)
+ edges: list[Edge] = field(default_factory=list)
+
+ def to_json(self, *, with_schemas: bool = False) -> dict[str, list[dict[str, Any]]]:
+ """Convert the graph to a JSON-serializable format.
+
+ Args:
+ with_schemas: Whether to include the schemas of the nodes if they are
+ Pydantic models.
+
+ Returns:
+ A dictionary with the nodes and edges of the graph.
+ """
+ stable_node_ids = {
+ node.id: i if is_uuid(node.id) else node.id
+ for i, node in enumerate(self.nodes.values())
+ }
+ edges: list[dict[str, Any]] = []
+ for edge in self.edges:
+ edge_dict = {
+ "source": stable_node_ids[edge.source],
+ "target": stable_node_ids[edge.target],
+ }
+ if edge.data is not None:
+ edge_dict["data"] = edge.data # type: ignore[assignment]
+ if edge.conditional:
+ edge_dict["conditional"] = True
+ edges.append(edge_dict)
+
+ return {
+ "nodes": [
+ {
+ "id": stable_node_ids[node.id],
+ **node_data_json(node, with_schemas=with_schemas),
+ }
+ for node in self.nodes.values()
+ ],
+ "edges": edges,
+ }
+
+ def __bool__(self) -> bool:
+ """Return whether the graph has any nodes."""
+ return bool(self.nodes)
+
+ def next_id(self) -> str:
+ """Return a new unique node identifier.
+
+ It that can be used to add a node to the graph.
+ """
+ return uuid4().hex
+
+ def add_node(
+ self,
+ data: type[BaseModel] | RunnableType | None,
+ id: str | None = None,
+ *,
+ metadata: dict[str, Any] | None = None,
+ ) -> Node:
+ """Add a node to the graph and return it.
+
+ Args:
+ data: The data of the node.
+ id: The id of the node.
+ metadata: Optional metadata for the node.
+
+ Returns:
+ The node that was added to the graph.
+
+ Raises:
+ ValueError: If a node with the same id already exists.
+ """
+ if id is not None and id in self.nodes:
+ msg = f"Node with id {id} already exists"
+ raise ValueError(msg)
+ id_ = id or self.next_id()
+ node = Node(id=id_, data=data, metadata=metadata, name=node_data_str(id_, data))
+ self.nodes[node.id] = node
+ return node
+
+ def remove_node(self, node: Node) -> None:
+ """Remove a node from the graph and all edges connected to it.
+
+ Args:
+ node: The node to remove.
+ """
+ self.nodes.pop(node.id)
+ self.edges = [
+ edge for edge in self.edges if node.id not in {edge.source, edge.target}
+ ]
+
+ def add_edge(
+ self,
+ source: Node,
+ target: Node,
+ data: Stringifiable | None = None,
+ conditional: bool = False, # noqa: FBT001,FBT002
+ ) -> Edge:
+ """Add an edge to the graph and return it.
+
+ Args:
+ source: The source node of the edge.
+ target: The target node of the edge.
+ data: Optional data associated with the edge.
+ conditional: Whether the edge is conditional.
+
+ Returns:
+ The edge that was added to the graph.
+
+ Raises:
+ ValueError: If the source or target node is not in the graph.
+ """
+ if source.id not in self.nodes:
+ msg = f"Source node {source.id} not in graph"
+ raise ValueError(msg)
+ if target.id not in self.nodes:
+ msg = f"Target node {target.id} not in graph"
+ raise ValueError(msg)
+ edge = Edge(
+ source=source.id, target=target.id, data=data, conditional=conditional
+ )
+ self.edges.append(edge)
+ return edge
+
+ def extend(
+ self, graph: Graph, *, prefix: str = ""
+ ) -> tuple[Node | None, Node | None]:
+ """Add all nodes and edges from another graph.
+
+ Note this doesn't check for duplicates, nor does it connect the graphs.
+
+ Args:
+ graph: The graph to add.
+ prefix: The prefix to add to the node ids.
+
+ Returns:
+ A tuple of the first and last nodes of the subgraph.
+ """
+ if all(is_uuid(node.id) for node in graph.nodes.values()):
+ prefix = ""
+
+ def prefixed(id_: str) -> str:
+ return f"{prefix}:{id_}" if prefix else id_
+
+ # prefix each node
+ self.nodes.update(
+ {prefixed(k): v.copy(id=prefixed(k)) for k, v in graph.nodes.items()}
+ )
+ # prefix each edge's source and target
+ self.edges.extend(
+ [
+ edge.copy(source=prefixed(edge.source), target=prefixed(edge.target))
+ for edge in graph.edges
+ ]
+ )
+ # return (prefixed) first and last nodes of the subgraph
+ first, last = graph.first_node(), graph.last_node()
+ return (
+ first.copy(id=prefixed(first.id)) if first else None,
+ last.copy(id=prefixed(last.id)) if last else None,
+ )
+
+ def reid(self) -> Graph:
+ """Return a new graph with all nodes re-identified.
+
+ Uses their unique, readable names where possible.
+ """
+ node_name_to_ids = defaultdict(list)
+ for node in self.nodes.values():
+ node_name_to_ids[node.name].append(node.id)
+
+ unique_labels = {
+ node_id: node_name if len(node_ids) == 1 else f"{node_name}_{i + 1}"
+ for node_name, node_ids in node_name_to_ids.items()
+ for i, node_id in enumerate(node_ids)
+ }
+
+ def _get_node_id(node_id: str) -> str:
+ label = unique_labels[node_id]
+ if is_uuid(node_id):
+ return label
+ return node_id
+
+ return Graph(
+ nodes={
+ _get_node_id(id_): node.copy(id=_get_node_id(id_))
+ for id_, node in self.nodes.items()
+ },
+ edges=[
+ edge.copy(
+ source=_get_node_id(edge.source),
+ target=_get_node_id(edge.target),
+ )
+ for edge in self.edges
+ ],
+ )
+
+ def first_node(self) -> Node | None:
+ """Find the single node that is not a target of any edge.
+
+ If there is no such node, or there are multiple, return `None`.
+ When drawing the graph, this node would be the origin.
+
+ Returns:
+ The first node, or None if there is no such node or multiple
+ candidates.
+ """
+ return _first_node(self)
+
+ def last_node(self) -> Node | None:
+ """Find the single node that is not a source of any edge.
+
+ If there is no such node, or there are multiple, return `None`.
+ When drawing the graph, this node would be the destination.
+
+ Returns:
+ The last node, or None if there is no such node or multiple
+ candidates.
+ """
+ return _last_node(self)
+
+ def trim_first_node(self) -> None:
+ """Remove the first node if it exists and has a single outgoing edge.
+
+ i.e., if removing it would not leave the graph without a "first" node.
+ """
+ first_node = self.first_node()
+ if (
+ first_node
+ and _first_node(self, exclude=[first_node.id])
+ and len({e for e in self.edges if e.source == first_node.id}) == 1
+ ):
+ self.remove_node(first_node)
+
+ def trim_last_node(self) -> None:
+ """Remove the last node if it exists and has a single incoming edge.
+
+ i.e., if removing it would not leave the graph without a "last" node.
+ """
+ last_node = self.last_node()
+ if (
+ last_node
+ and _last_node(self, exclude=[last_node.id])
+ and len({e for e in self.edges if e.target == last_node.id}) == 1
+ ):
+ self.remove_node(last_node)
+
+ def draw_ascii(self) -> str:
+ """Draw the graph as an ASCII art string.
+
+ Returns:
+ The ASCII art string.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_ascii import draw_ascii # noqa: PLC0415
+
+ return draw_ascii(
+ {node.id: node.name for node in self.nodes.values()},
+ self.edges,
+ )
+
+ def print_ascii(self) -> None:
+ """Print the graph as an ASCII art string."""
+ print(self.draw_ascii()) # noqa: T201
+
+ @overload
+ def draw_png(
+ self,
+ output_file_path: str,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> None: ...
+
+ @overload
+ def draw_png(
+ self,
+ output_file_path: None,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> bytes: ...
+
+ def draw_png(
+ self,
+ output_file_path: str | None = None,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> bytes | None:
+ """Draw the graph as a PNG image.
+
+ Args:
+ output_file_path: The path to save the image to. If `None`, the image
+ is not saved.
+ fontname: The name of the font to use.
+ labels: Optional labels for nodes and edges in the graph. Defaults to
+ `None`.
+
+ Returns:
+ The PNG image as bytes if output_file_path is None, None otherwise.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_png import PngDrawer # noqa: PLC0415
+
+ default_node_labels = {node.id: node.name for node in self.nodes.values()}
+
+ return PngDrawer(
+ fontname,
+ LabelsDict(
+ nodes={
+ **default_node_labels,
+ **(labels["nodes"] if labels is not None else {}),
+ },
+ edges=labels["edges"] if labels is not None else {},
+ ),
+ ).draw(self, output_file_path)
+
+ def draw_mermaid(
+ self,
+ *,
+ with_styles: bool = True,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_colors: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ frontmatter_config: dict[str, Any] | None = None,
+ ) -> str:
+ """Draw the graph as a Mermaid syntax string.
+
+ Args:
+ with_styles: Whether to include styles in the syntax.
+ curve_style: The style of the edges.
+ node_colors: The colors of the nodes.
+ wrap_label_n_words: The number of words to wrap the node labels at.
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+ Returns:
+ The Mermaid syntax string.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_mermaid import draw_mermaid # noqa: PLC0415
+
+ graph = self.reid()
+ first_node = graph.first_node()
+ last_node = graph.last_node()
+
+ return draw_mermaid(
+ nodes=graph.nodes,
+ edges=graph.edges,
+ first_node=first_node.id if first_node else None,
+ last_node=last_node.id if last_node else None,
+ with_styles=with_styles,
+ curve_style=curve_style,
+ node_styles=node_colors,
+ wrap_label_n_words=wrap_label_n_words,
+ frontmatter_config=frontmatter_config,
+ )
+
+ def draw_mermaid_png(
+ self,
+ *,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_colors: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ output_file_path: str | None = None,
+ draw_method: MermaidDrawMethod = MermaidDrawMethod.API,
+ background_color: str = "white",
+ padding: int = 10,
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ frontmatter_config: dict[str, Any] | None = None,
+ base_url: str | None = None,
+ proxies: dict[str, str] | None = None,
+ ) -> bytes:
+ """Draw the graph as a PNG image using Mermaid.
+
+ Args:
+ curve_style: The style of the edges.
+ node_colors: The colors of the nodes.
+ wrap_label_n_words: The number of words to wrap the node labels at.
+ output_file_path: The path to save the image to. If `None`, the image
+ is not saved.
+ draw_method: The method to use to draw the graph.
+ background_color: The color of the background.
+ padding: The padding around the graph.
+ max_retries: The maximum number of retries (`MermaidDrawMethod.API`).
+ retry_delay: The delay between retries (`MermaidDrawMethod.API`).
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+ base_url: The base URL of the Mermaid server for rendering via API.
+ proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`).
+
+ Returns:
+ The PNG image as bytes.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_mermaid import ( # noqa: PLC0415
+ draw_mermaid_png,
+ )
+
+ mermaid_syntax = self.draw_mermaid(
+ curve_style=curve_style,
+ node_colors=node_colors,
+ wrap_label_n_words=wrap_label_n_words,
+ frontmatter_config=frontmatter_config,
+ )
+ return draw_mermaid_png(
+ mermaid_syntax=mermaid_syntax,
+ output_file_path=output_file_path,
+ draw_method=draw_method,
+ background_color=background_color,
+ padding=padding,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
+ proxies=proxies,
+ base_url=base_url,
+ )
+
+
+def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
+ """Find the single node that is not a target of any edge.
+
+ Exclude nodes/sources with IDs in the exclude list.
+
+ If there is no such node, or there are multiple, return `None`.
+
+ When drawing the graph, this node would be the origin.
+ """
+ targets = {edge.target for edge in graph.edges if edge.source not in exclude}
+ found: list[Node] = [
+ node
+ for node in graph.nodes.values()
+ if node.id not in exclude and node.id not in targets
+ ]
+ return found[0] if len(found) == 1 else None
+
+
+def _last_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
+ """Find the single node that is not a source of any edge.
+
+ Exclude nodes/targets with IDs in the exclude list.
+
+ If there is no such node, or there are multiple, return `None`.
+
+ When drawing the graph, this node would be the destination.
+ """
+ sources = {edge.source for edge in graph.edges if edge.target not in exclude}
+ found: list[Node] = [
+ node
+ for node in graph.nodes.values()
+ if node.id not in exclude and node.id not in sources
+ ]
+ return found[0] if len(found) == 1 else None
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_ascii.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_ascii.py
new file mode 100644
index 0000000000000000000000000000000000000000..14d29a837d6341d538f64a96713cd81afbbc5e5e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_ascii.py
@@ -0,0 +1,366 @@
+"""Draws DAG in ASCII.
+
+Adapted from https://github.com/iterative/dvc/blob/main/dvc/dagascii.py.
+"""
+
+from __future__ import annotations
+
+import math
+import os
+from typing import TYPE_CHECKING, Any
+
+try:
+ from grandalf.graphs import Edge, Graph, Vertex # type: ignore[import-untyped]
+ from grandalf.layouts import SugiyamaLayout # type: ignore[import-untyped]
+ from grandalf.routing import route_with_lines # type: ignore[import-untyped]
+
+ _HAS_GRANDALF = True
+except ImportError:
+ _HAS_GRANDALF = False
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping, Sequence
+
+ from langchain_core.runnables.graph import Edge as LangEdge
+
+
+class VertexViewer:
+ """VertexViewer class.
+
+ Class to define vertex box boundaries that will be accounted for during
+ graph building by grandalf.
+ """
+
+ HEIGHT = 3 # top and bottom box edges + text
+ """Height of the box."""
+
+ def __init__(self, name: str) -> None:
+ """Create a VertexViewer.
+
+ Args:
+ name: name of the vertex.
+ """
+ self._h = self.HEIGHT # top and bottom box edges + text
+ self._w = len(name) + 2 # right and left bottom edges + text
+
+ @property
+ def h(self) -> int:
+ """Height of the box."""
+ return self._h
+
+ @property
+ def w(self) -> int:
+ """Width of the box."""
+ return self._w
+
+
+class AsciiCanvas:
+ """Class for drawing in ASCII."""
+
+ TIMEOUT = 10
+
+ def __init__(self, cols: int, lines: int) -> None:
+ """Create an ASCII canvas.
+
+ Args:
+ cols: number of columns in the canvas. Should be `> 1`.
+ lines: number of lines in the canvas. Should be `> 1`.
+
+ Raises:
+ ValueError: if canvas dimensions are invalid.
+ """
+ if cols <= 1 or lines <= 1:
+ msg = "Canvas dimensions should be > 1"
+ raise ValueError(msg)
+
+ self.cols = cols
+ self.lines = lines
+
+ self.canvas = [[" "] * cols for line in range(lines)]
+
+ def draw(self) -> str:
+ """Draws ASCII canvas on the screen.
+
+ Returns:
+ The ASCII canvas string.
+ """
+ lines = map("".join, self.canvas)
+ return os.linesep.join(lines)
+
+ def point(self, x: int, y: int, char: str) -> None:
+ """Create a point on ASCII canvas.
+
+ Args:
+ x: x coordinate. Should be `>= 0` and `<` number of columns in
+ the canvas.
+ y: y coordinate. Should be `>= 0` an `<` number of lines in the
+ canvas.
+ char: character to place in the specified point on the
+ canvas.
+
+ Raises:
+ ValueError: if char is not a single character or if
+ coordinates are out of bounds.
+ """
+ if len(char) != 1:
+ msg = "char should be a single character"
+ raise ValueError(msg)
+ if x >= self.cols or x < 0:
+ msg = "x should be >= 0 and < number of columns"
+ raise ValueError(msg)
+ if y >= self.lines or y < 0:
+ msg = "y should be >= 0 and < number of lines"
+ raise ValueError(msg)
+
+ self.canvas[y][x] = char
+
+ def line(self, x0: int, y0: int, x1: int, y1: int, char: str) -> None:
+ """Create a line on ASCII canvas.
+
+ Args:
+ x0: x coordinate where the line should start.
+ y0: y coordinate where the line should start.
+ x1: x coordinate where the line should end.
+ y1: y coordinate where the line should end.
+ char: character to draw the line with.
+ """
+ if x0 > x1:
+ x1, x0 = x0, x1
+ y1, y0 = y0, y1
+
+ dx = x1 - x0
+ dy = y1 - y0
+
+ if dx == 0 and dy == 0:
+ self.point(x0, y0, char)
+ elif abs(dx) >= abs(dy):
+ for x in range(x0, x1 + 1):
+ y = y0 if dx == 0 else y0 + round((x - x0) * dy / float(dx))
+ self.point(x, y, char)
+ elif y0 < y1:
+ for y in range(y0, y1 + 1):
+ x = x0 if dy == 0 else x0 + round((y - y0) * dx / float(dy))
+ self.point(x, y, char)
+ else:
+ for y in range(y1, y0 + 1):
+ x = x0 if dy == 0 else x1 + round((y - y1) * dx / float(dy))
+ self.point(x, y, char)
+
+ def text(self, x: int, y: int, text: str) -> None:
+ """Print a text on ASCII canvas.
+
+ Args:
+ x: x coordinate where the text should start.
+ y: y coordinate where the text should start.
+ text: string that should be printed.
+ """
+ for i, char in enumerate(text):
+ self.point(x + i, y, char)
+
+ def box(self, x0: int, y0: int, width: int, height: int) -> None:
+ """Create a box on ASCII canvas.
+
+ Args:
+ x0: x coordinate of the box corner.
+ y0: y coordinate of the box corner.
+ width: box width.
+ height: box height.
+
+ Raises:
+ ValueError: if box dimensions are invalid.
+ """
+ if width <= 1 or height <= 1:
+ msg = "Box dimensions should be > 1"
+ raise ValueError(msg)
+
+ width -= 1
+ height -= 1
+
+ for x in range(x0, x0 + width):
+ self.point(x, y0, "-")
+ self.point(x, y0 + height, "-")
+
+ for y in range(y0, y0 + height):
+ self.point(x0, y, "|")
+ self.point(x0 + width, y, "|")
+
+ self.point(x0, y0, "+")
+ self.point(x0 + width, y0, "+")
+ self.point(x0, y0 + height, "+")
+ self.point(x0 + width, y0 + height, "+")
+
+
+class _EdgeViewer:
+ def __init__(self) -> None:
+ self.pts: list[tuple[float]] = []
+
+ def setpath(self, pts: list[tuple[float]]) -> None:
+ self.pts = pts
+
+
+def _build_sugiyama_layout(
+ vertices: Mapping[str, str], edges: Sequence[LangEdge]
+) -> Any:
+ if not _HAS_GRANDALF:
+ msg = "Install grandalf to draw graphs: `pip install grandalf`."
+ raise ImportError(msg)
+
+ #
+ # Just a reminder about naming conventions:
+ # +------------X
+ # |
+ # |
+ # |
+ # |
+ # Y
+ #
+
+ vertices_ = {id_: Vertex(f" {data} ") for id_, data in vertices.items()}
+ edges_ = [Edge(vertices_[s], vertices_[e], data=cond) for s, e, _, cond in edges]
+ vertices_list = vertices_.values()
+ graph = Graph(vertices_list, edges_)
+
+ for vertex in vertices_list:
+ vertex.view = VertexViewer(vertex.data)
+
+ # NOTE: determine min box length to create the best layout
+ minw = min(v.view.w for v in vertices_list)
+
+ for edge in edges_:
+ edge.view = _EdgeViewer()
+
+ sug = SugiyamaLayout(graph.C[0])
+ graph = graph.C[0]
+ roots = list(filter(lambda x: len(x.e_in()) == 0, graph.sV))
+
+ sug.init_all(roots=roots, optimize=True)
+
+ sug.yspace = VertexViewer.HEIGHT
+ sug.xspace = minw
+ sug.route_edge = route_with_lines
+
+ sug.draw()
+
+ return sug
+
+
+def draw_ascii(vertices: Mapping[str, str], edges: Sequence[LangEdge]) -> str:
+ """Build a DAG and draw it in ASCII.
+
+ Args:
+ vertices: list of graph vertices.
+ edges: list of graph edges.
+
+ Raises:
+ ValueError: if the canvas dimensions are invalid or if
+ edge coordinates are invalid.
+
+ Returns:
+ ASCII representation
+
+ Example:
+ ```python
+ from langchain_core.runnables.graph_ascii import draw_ascii
+
+ vertices = {1: "1", 2: "2", 3: "3", 4: "4"}
+ edges = [
+ (source, target, None, None)
+ for source, target in [(1, 2), (2, 3), (2, 4), (1, 4)]
+ ]
+
+
+ print(draw_ascii(vertices, edges))
+ ```
+
+ ```txt
+
+ +---+
+ | 1 |
+ +---+
+ * *
+ * *
+ * *
+ +---+ *
+ | 2 | *
+ +---+** *
+ * ** *
+ * ** *
+ * **
+ +---+ +---+
+ | 3 | | 4 |
+ +---+ +---+
+ ```
+ """
+ # NOTE: coordinates might me negative, so we need to shift
+ # everything to the positive plane before we actually draw it.
+ xlist: list[float] = []
+ ylist: list[float] = []
+
+ sug = _build_sugiyama_layout(vertices, edges)
+
+ for vertex in sug.g.sV:
+ # NOTE: moving boxes w/2 to the left
+ xlist.extend(
+ (
+ vertex.view.xy[0] - vertex.view.w / 2.0,
+ vertex.view.xy[0] + vertex.view.w / 2.0,
+ )
+ )
+ ylist.extend((vertex.view.xy[1], vertex.view.xy[1] + vertex.view.h))
+
+ for edge in sug.g.sE:
+ for x, y in edge.view.pts:
+ xlist.append(x)
+ ylist.append(y)
+
+ minx = min(xlist)
+ miny = min(ylist)
+ maxx = max(xlist)
+ maxy = max(ylist)
+
+ canvas_cols = math.ceil(math.ceil(maxx) - math.floor(minx)) + 1
+ canvas_lines = round(maxy - miny)
+
+ canvas = AsciiCanvas(canvas_cols, canvas_lines)
+
+ # NOTE: first draw edges so that node boxes could overwrite them
+ for edge in sug.g.sE:
+ if len(edge.view.pts) <= 1:
+ msg = "Not enough points to draw an edge"
+ raise ValueError(msg)
+ for index in range(1, len(edge.view.pts)):
+ start = edge.view.pts[index - 1]
+ end = edge.view.pts[index]
+
+ start_x = round(start[0] - minx)
+ start_y = round(start[1] - miny)
+ end_x = round(end[0] - minx)
+ end_y = round(end[1] - miny)
+
+ if start_x < 0 or start_y < 0 or end_x < 0 or end_y < 0:
+ msg = (
+ "Invalid edge coordinates: "
+ f"start_x={start_x}, "
+ f"start_y={start_y}, "
+ f"end_x={end_x}, "
+ f"end_y={end_y}"
+ )
+ raise ValueError(msg)
+
+ canvas.line(start_x, start_y, end_x, end_y, "." if edge.data else "*")
+
+ for vertex in sug.g.sV:
+ # NOTE: moving boxes w/2 to the left
+ x = vertex.view.xy[0] - vertex.view.w / 2.0
+ y = vertex.view.xy[1]
+
+ canvas.box(
+ round(x - minx),
+ round(y - miny),
+ vertex.view.w,
+ vertex.view.h,
+ )
+
+ canvas.text(round(x - minx) + 1, round(y - miny) + 1, vertex.data)
+
+ return canvas.draw()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_mermaid.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_mermaid.py
new file mode 100644
index 0000000000000000000000000000000000000000..1499d6d1fab419681fa60a9639631bbb9837d8d6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_mermaid.py
@@ -0,0 +1,503 @@
+"""Mermaid graph drawing utilities."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import random
+import re
+import string
+import time
+import urllib.parse
+from dataclasses import asdict
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+import yaml
+
+from langchain_core.runnables.graph import (
+ CurveStyle,
+ MermaidDrawMethod,
+ NodeStyles,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.graph import Edge, Node
+
+
+try:
+ import requests
+
+ _HAS_REQUESTS = True
+except ImportError:
+ _HAS_REQUESTS = False
+
+try:
+ from pyppeteer import launch # type: ignore[import-not-found]
+
+ _HAS_PYPPETEER = True
+except ImportError:
+ _HAS_PYPPETEER = False
+
+MARKDOWN_SPECIAL_CHARS = "*_`"
+
+
+def draw_mermaid(
+ nodes: dict[str, Node],
+ edges: list[Edge],
+ *,
+ first_node: str | None = None,
+ last_node: str | None = None,
+ with_styles: bool = True,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_styles: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ frontmatter_config: dict[str, Any] | None = None,
+) -> str:
+ """Draws a Mermaid graph using the provided graph data.
+
+ Args:
+ nodes: List of node ids.
+ edges: List of edges, object with a source, target and data.
+ first_node: Id of the first node.
+ last_node: Id of the last node.
+ with_styles: Whether to include styles in the graph.
+ curve_style: Curve style for the edges.
+ node_styles: Node colors for different types.
+ wrap_label_n_words: Words to wrap the edge labels.
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+
+ Returns:
+ Mermaid graph syntax.
+
+ """
+ # Initialize Mermaid graph configuration
+ original_frontmatter_config = frontmatter_config or {}
+ original_flowchart_config = original_frontmatter_config.get("config", {}).get(
+ "flowchart", {}
+ )
+ frontmatter_config = {
+ **original_frontmatter_config,
+ "config": {
+ **original_frontmatter_config.get("config", {}),
+ "flowchart": {**original_flowchart_config, "curve": curve_style.value},
+ },
+ }
+
+ mermaid_graph = (
+ (
+ "---\n"
+ + yaml.dump(frontmatter_config, default_flow_style=False)
+ + "---\ngraph TD;\n"
+ )
+ if with_styles
+ else "graph TD;\n"
+ )
+ # Group nodes by subgraph
+ subgraph_nodes: dict[str, dict[str, Node]] = {}
+ regular_nodes: dict[str, Node] = {}
+
+ for key, node in nodes.items():
+ if ":" in key:
+ # For nodes with colons, add them only to their deepest subgraph level
+ prefix = ":".join(key.split(":")[:-1])
+ subgraph_nodes.setdefault(prefix, {})[key] = node
+ else:
+ regular_nodes[key] = node
+
+ # Node formatting templates
+ default_class_label = "default"
+ format_dict = {default_class_label: "{0}({1})"}
+ if first_node is not None:
+ format_dict[first_node] = "{0}([{1}]):::first"
+ if last_node is not None:
+ format_dict[last_node] = "{0}([{1}]):::last"
+
+ def render_node(key: str, node: Node, indent: str = "\t") -> str:
+ """Helper function to render a node with consistent formatting."""
+ node_name = node.name.split(":")[-1]
+ label = (
+ f"{node_name}
"
+ if node_name.startswith(tuple(MARKDOWN_SPECIAL_CHARS))
+ and node_name.endswith(tuple(MARKDOWN_SPECIAL_CHARS))
+ else node_name
+ )
+ if node.metadata:
+ label = (
+ f"{label}
"
+ + "\n".join(f"{k} = {value}" for k, value in node.metadata.items())
+ + ""
+ )
+ node_label = format_dict.get(key, format_dict[default_class_label]).format(
+ _to_safe_id(key), label
+ )
+ return f"{indent}{node_label}\n"
+
+ # Add non-subgraph nodes to the graph
+ if with_styles:
+ for key, node in regular_nodes.items():
+ mermaid_graph += render_node(key, node)
+
+ # Group edges by their common prefixes
+ edge_groups: dict[str, list[Edge]] = {}
+ for edge in edges:
+ src_parts = edge.source.split(":")
+ tgt_parts = edge.target.split(":")
+ common_prefix = ":".join(
+ src for src, tgt in zip(src_parts, tgt_parts, strict=False) if src == tgt
+ )
+ edge_groups.setdefault(common_prefix, []).append(edge)
+
+ seen_subgraphs = set()
+
+ def add_subgraph(edges: list[Edge], prefix: str) -> None:
+ nonlocal mermaid_graph
+ self_loop = len(edges) == 1 and edges[0].source == edges[0].target
+ if prefix and not self_loop:
+ subgraph = prefix.rsplit(":", maxsplit=1)[-1]
+ if subgraph in seen_subgraphs:
+ msg = (
+ f"Found duplicate subgraph '{subgraph}' -- this likely means that "
+ "you're reusing a subgraph node with the same name. "
+ "Please adjust your graph to have subgraph nodes with unique names."
+ )
+ raise ValueError(msg)
+
+ seen_subgraphs.add(subgraph)
+ mermaid_graph += f"\tsubgraph {subgraph}\n"
+
+ # Add nodes that belong to this subgraph
+ if with_styles and prefix in subgraph_nodes:
+ for key, node in subgraph_nodes[prefix].items():
+ mermaid_graph += render_node(key, node)
+
+ for edge in edges:
+ source, target = edge.source, edge.target
+
+ # Add BR every wrap_label_n_words words
+ if edge.data is not None:
+ edge_data = edge.data
+ words = str(edge_data).split() # Split the string into words
+ # Group words into chunks of wrap_label_n_words size
+ if len(words) > wrap_label_n_words:
+ edge_data = " 
 ".join(
+ " ".join(words[i : i + wrap_label_n_words])
+ for i in range(0, len(words), wrap_label_n_words)
+ )
+ if edge.conditional:
+ edge_label = f" -. {edge_data} .-> "
+ else:
+ edge_label = f" -- {edge_data} --> "
+ else:
+ edge_label = " -.-> " if edge.conditional else " --> "
+
+ mermaid_graph += (
+ f"\t{_to_safe_id(source)}{edge_label}{_to_safe_id(target)};\n"
+ )
+
+ # Recursively add nested subgraphs
+ for nested_prefix, edges_ in edge_groups.items():
+ if not nested_prefix.startswith(prefix + ":") or nested_prefix == prefix:
+ continue
+ # only go to first level subgraphs
+ if ":" in nested_prefix[len(prefix) + 1 :]:
+ continue
+ add_subgraph(edges_, nested_prefix)
+
+ if prefix and not self_loop:
+ mermaid_graph += "\tend\n"
+
+ # Start with the top-level edges (no common prefix)
+ add_subgraph(edge_groups.get("", []), "")
+
+ # Add remaining subgraphs with edges
+ for prefix, edges_ in edge_groups.items():
+ if not prefix or ":" in prefix:
+ continue
+ add_subgraph(edges_, prefix)
+ seen_subgraphs.add(prefix)
+
+ # Add empty subgraphs (subgraphs with no internal edges)
+ if with_styles:
+ for prefix, subgraph_node in subgraph_nodes.items():
+ if ":" not in prefix and prefix not in seen_subgraphs:
+ mermaid_graph += f"\tsubgraph {prefix}\n"
+
+ # Add nodes that belong to this subgraph
+ for key, node in subgraph_node.items():
+ mermaid_graph += render_node(key, node)
+
+ mermaid_graph += "\tend\n"
+ seen_subgraphs.add(prefix)
+
+ # Add custom styles for nodes
+ if with_styles:
+ mermaid_graph += _generate_mermaid_graph_styles(node_styles or NodeStyles())
+ return mermaid_graph
+
+
+def _to_safe_id(label: str) -> str:
+ """Convert a string into a Mermaid-compatible node id.
+
+ Keep [a-zA-Z0-9_-] characters unchanged.
+ Map every other character -> backslash + lowercase hex codepoint.
+
+ Result is guaranteed to be unique and Mermaid-compatible,
+ so nodes with special characters always render correctly.
+ """
+ allowed = string.ascii_letters + string.digits + "_-"
+ out = [ch if ch in allowed else "\\" + format(ord(ch), "x") for ch in label]
+ return "".join(out)
+
+
+def _generate_mermaid_graph_styles(node_colors: NodeStyles) -> str:
+ """Generates Mermaid graph styles for different node types."""
+ styles = ""
+ for class_name, style in asdict(node_colors).items():
+ styles += f"\tclassDef {class_name} {style}\n"
+ return styles
+
+
+def draw_mermaid_png(
+ mermaid_syntax: str,
+ output_file_path: str | None = None,
+ draw_method: MermaidDrawMethod = MermaidDrawMethod.API,
+ background_color: str | None = "white",
+ padding: int = 10,
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ base_url: str | None = None,
+ proxies: dict[str, str] | None = None,
+) -> bytes:
+ """Draws a Mermaid graph as PNG using provided syntax.
+
+ Args:
+ mermaid_syntax: Mermaid graph syntax.
+ output_file_path: Path to save the PNG image.
+ draw_method: Method to draw the graph.
+ background_color: Background color of the image.
+ padding: Padding around the image.
+ max_retries: Maximum number of retries (MermaidDrawMethod.API).
+ retry_delay: Delay between retries (MermaidDrawMethod.API).
+ base_url: Base URL for the Mermaid.ink API.
+ proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`).
+
+ Returns:
+ PNG image bytes.
+
+ Raises:
+ ValueError: If an invalid draw method is provided.
+ """
+ if draw_method == MermaidDrawMethod.PYPPETEER:
+ img_bytes = asyncio.run(
+ _render_mermaid_using_pyppeteer(
+ mermaid_syntax, output_file_path, background_color, padding
+ )
+ )
+ elif draw_method == MermaidDrawMethod.API:
+ img_bytes = _render_mermaid_using_api(
+ mermaid_syntax,
+ output_file_path=output_file_path,
+ background_color=background_color,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
+ base_url=base_url,
+ proxies=proxies,
+ )
+ else:
+ supported_methods = ", ".join([m.value for m in MermaidDrawMethod])
+ msg = (
+ f"Invalid draw method: {draw_method}. "
+ f"Supported draw methods are: {supported_methods}"
+ )
+ raise ValueError(msg)
+
+ return img_bytes
+
+
+async def _render_mermaid_using_pyppeteer(
+ mermaid_syntax: str,
+ output_file_path: str | None = None,
+ background_color: str | None = "white",
+ padding: int = 10,
+ device_scale_factor: int = 3,
+) -> bytes:
+ """Renders Mermaid graph using Pyppeteer."""
+ if not _HAS_PYPPETEER:
+ msg = "Install Pyppeteer to use the Pyppeteer method: `pip install pyppeteer`."
+ raise ImportError(msg)
+
+ browser = await launch()
+ page = await browser.newPage()
+
+ # Setup Mermaid JS
+ await page.goto("about:blank")
+ await page.addScriptTag(
+ {"url": "https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"}
+ )
+ await page.evaluate(
+ """() => {
+ mermaid.initialize({startOnLoad:true});
+ }"""
+ )
+
+ # Render SVG
+ svg_code = await page.evaluate(
+ """(mermaidGraph) => {
+ return mermaid.mermaidAPI.render('mermaid', mermaidGraph);
+ }""",
+ mermaid_syntax,
+ )
+
+ # Set the page background to white
+ await page.evaluate(
+ """(svg, background_color) => {
+ document.body.innerHTML = svg;
+ document.body.style.background = background_color;
+ }""",
+ svg_code["svg"],
+ background_color,
+ )
+
+ # Take a screenshot
+ dimensions = await page.evaluate(
+ """() => {
+ const svgElement = document.querySelector('svg');
+ const rect = svgElement.getBoundingClientRect();
+ return { width: rect.width, height: rect.height };
+ }"""
+ )
+ await page.setViewport(
+ {
+ "width": int(dimensions["width"] + padding),
+ "height": int(dimensions["height"] + padding),
+ "deviceScaleFactor": device_scale_factor,
+ }
+ )
+
+ img_bytes = cast("bytes", await page.screenshot({"fullPage": False}))
+ await browser.close()
+
+ if output_file_path is not None:
+ await asyncio.get_event_loop().run_in_executor(
+ None, Path(output_file_path).write_bytes, img_bytes
+ )
+
+ return img_bytes
+
+
+def _render_mermaid_using_api(
+ mermaid_syntax: str,
+ *,
+ output_file_path: str | None = None,
+ background_color: str | None = "white",
+ file_type: Literal["jpeg", "png", "webp"] | None = "png",
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ proxies: dict[str, str] | None = None,
+ base_url: str | None = None,
+) -> bytes:
+ """Renders Mermaid graph using the Mermaid.INK API."""
+ # Automated scanners: please do not open security advisories about `base_url`
+ # here. This parameter is only ever explicitly controlled by developers, and it
+ # is not exposed by default over the network by the framework, so this is not
+ # an SSRF sink unless an application explicitly wires untrusted input into it.
+ # It exists to support user-managed Mermaid API deployments.
+ # Defaults to using the public mermaid.ink server.
+ base_url = base_url if base_url is not None else "https://mermaid.ink"
+
+ if not _HAS_REQUESTS:
+ msg = (
+ "Install the `requests` module to use the Mermaid.INK API: "
+ "`pip install requests`."
+ )
+ raise ImportError(msg)
+
+ # Use Mermaid API to render the image
+ mermaid_syntax_encoded = base64.b64encode(mermaid_syntax.encode("utf8")).decode(
+ "ascii"
+ )
+
+ # Check if the background color is a hexadecimal color code using regex
+ if background_color is not None:
+ hex_color_pattern = re.compile(r"^#(?:[0-9a-fA-F]{3}){1,2}$")
+ if not hex_color_pattern.match(background_color):
+ background_color = f"!{background_color}"
+
+ # URL-encode the background_color to handle special characters like '!'
+ encoded_bg_color = urllib.parse.quote(str(background_color), safe="")
+ image_url = (
+ f"{base_url}/img/{mermaid_syntax_encoded}"
+ f"?type={file_type}&bgColor={encoded_bg_color}"
+ )
+
+ error_msg_suffix = (
+ "To resolve this issue:\n"
+ "1. Check your internet connection and try again\n"
+ "2. Try with higher retry settings: "
+ "`draw_mermaid_png(..., max_retries=5, retry_delay=2.0)`\n"
+ "3. Use the Pyppeteer rendering method which will render your graph locally "
+ "in a browser: `draw_mermaid_png(..., draw_method=MermaidDrawMethod.PYPPETEER)`"
+ )
+
+ for attempt in range(max_retries + 1):
+ try:
+ response = requests.get(image_url, timeout=10, proxies=proxies)
+ if response.status_code == requests.codes.ok:
+ img_bytes = response.content
+ if output_file_path is not None:
+ Path(output_file_path).write_bytes(response.content)
+
+ return img_bytes
+
+ # If we get a server error (5xx), retry
+ if (
+ requests.codes.internal_server_error <= response.status_code
+ and attempt < max_retries
+ ):
+ # Exponential backoff with jitter
+ sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto
+ time.sleep(sleep_time)
+ continue
+
+ # For other status codes, fail immediately
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph. Status code: {response.status_code}.\n\n"
+ ) + error_msg_suffix
+ raise ValueError(msg)
+
+ except (requests.RequestException, requests.Timeout) as e:
+ if attempt < max_retries:
+ # Exponential backoff with jitter
+ sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto
+ time.sleep(sleep_time)
+ else:
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph after {max_retries} retries. "
+ ) + error_msg_suffix
+ raise ValueError(msg) from e
+
+ # This should not be reached, but just in case
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph after {max_retries} retries. "
+ ) + error_msg_suffix
+ raise ValueError(msg)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py
new file mode 100644
index 0000000000000000000000000000000000000000..97b6b1f21f2b5f4ab33d216e2084556aadec7b82
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py
@@ -0,0 +1,215 @@
+"""Helper class to draw a state graph into a PNG file."""
+
+from itertools import groupby
+from typing import Any, cast
+
+from langchain_core.runnables.graph import Graph, LabelsDict
+
+try:
+ import pygraphviz as pgv # type: ignore[import-not-found]
+
+ _HAS_PYGRAPHVIZ = True
+except ImportError:
+ _HAS_PYGRAPHVIZ = False
+
+
+class PngDrawer:
+ """Helper class to draw a state graph into a PNG file.
+
+ It requires `graphviz` and `pygraphviz` to be installed.
+
+ Example:
+ ```python
+ drawer = PngDrawer()
+ drawer.draw(state_graph, "graph.png")
+ ```
+ """
+
+ def __init__(
+ self, fontname: str | None = None, labels: LabelsDict | None = None
+ ) -> None:
+ """Initializes the PNG drawer.
+
+ Args:
+ fontname: The font to use for the labels. Defaults to "arial".
+ labels: A dictionary of label overrides. The dictionary
+ should have the following format:
+ {
+ "nodes": {
+ "node1": "CustomLabel1",
+ "node2": "CustomLabel2",
+ "__end__": "End Node"
+ },
+ "edges": {
+ "continue": "ContinueLabel",
+ "end": "EndLabel"
+ }
+ }
+ The keys are the original labels, and the values are the new labels.
+
+ """
+ self.fontname = fontname or "arial"
+ self.labels = labels or LabelsDict(nodes={}, edges={})
+
+ def get_node_label(self, label: str) -> str:
+ """Returns the label to use for a node.
+
+ Args:
+ label: The original label.
+
+ Returns:
+ The new label.
+ """
+ label = self.labels.get("nodes", {}).get(label, label)
+ return f"<{label}>"
+
+ def get_edge_label(self, label: str) -> str:
+ """Returns the label to use for an edge.
+
+ Args:
+ label: The original label.
+
+ Returns:
+ The new label.
+ """
+ label = self.labels.get("edges", {}).get(label, label)
+ return f"<{label}>"
+
+ def add_node(self, viz: Any, node: str) -> None:
+ """Adds a node to the graph.
+
+ Args:
+ viz: The graphviz object.
+ node: The node to add.
+ """
+ viz.add_node(
+ node,
+ label=self.get_node_label(node),
+ style="filled",
+ fillcolor="yellow",
+ fontsize=15,
+ fontname=self.fontname,
+ )
+
+ def add_edge(
+ self,
+ viz: Any,
+ source: str,
+ target: str,
+ label: str | None = None,
+ conditional: bool = False, # noqa: FBT001,FBT002
+ ) -> None:
+ """Adds an edge to the graph.
+
+ Args:
+ viz: The graphviz object.
+ source: The source node.
+ target: The target node.
+ label: The label for the edge.
+ conditional: Whether the edge is conditional.
+ """
+ viz.add_edge(
+ source,
+ target,
+ label=self.get_edge_label(label) if label else "",
+ fontsize=12,
+ fontname=self.fontname,
+ style="dotted" if conditional else "solid",
+ )
+
+ def draw(self, graph: Graph, output_path: str | None = None) -> bytes | None:
+ """Draw the given state graph into a PNG file.
+
+ Requires `graphviz` and `pygraphviz` to be installed.
+
+ Args:
+ graph: The graph to draw
+ output_path: The path to save the PNG. If `None`, PNG bytes are returned.
+
+ Raises:
+ ImportError: If `pygraphviz` is not installed.
+
+ Returns:
+ The PNG bytes if `output_path` is None, else None.
+ """
+ if not _HAS_PYGRAPHVIZ:
+ msg = "Install pygraphviz to draw graphs: `pip install pygraphviz`."
+ raise ImportError(msg)
+
+ # Create a directed graph
+ viz = pgv.AGraph(directed=True, nodesep=0.9, ranksep=1.0)
+
+ # Add nodes, conditional edges, and edges to the graph
+ self.add_nodes(viz, graph)
+ self.add_edges(viz, graph)
+ self.add_subgraph(viz, [node.split(":") for node in graph.nodes])
+
+ # Update entrypoint and END styles
+ self.update_styles(viz, graph)
+
+ # Save the graph as PNG
+ try:
+ return cast("bytes | None", viz.draw(output_path, format="png", prog="dot"))
+ finally:
+ viz.close()
+
+ def add_nodes(self, viz: Any, graph: Graph) -> None:
+ """Add nodes to the graph.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ for node in graph.nodes:
+ self.add_node(viz, node)
+
+ def add_subgraph(
+ self,
+ viz: Any,
+ nodes: list[list[str]],
+ parent_prefix: list[str] | None = None,
+ ) -> None:
+ """Add subgraphs to the graph.
+
+ Args:
+ viz: The graphviz object.
+ nodes: The nodes to add.
+ parent_prefix: The prefix of the parent subgraph.
+ """
+ for prefix, grouped in groupby(
+ [node[:] for node in sorted(nodes)],
+ key=lambda x: x.pop(0),
+ ):
+ current_prefix = (parent_prefix or []) + [prefix]
+ grouped_nodes = list(grouped)
+ if len(grouped_nodes) > 1:
+ subgraph = viz.add_subgraph(
+ [":".join(current_prefix + node) for node in grouped_nodes],
+ name="cluster_" + ":".join(current_prefix),
+ )
+ self.add_subgraph(subgraph, grouped_nodes, current_prefix)
+
+ def add_edges(self, viz: Any, graph: Graph) -> None:
+ """Add edges to the graph.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ for start, end, data, cond in graph.edges:
+ self.add_edge(
+ viz, start, end, str(data) if data is not None else None, cond
+ )
+
+ @staticmethod
+ def update_styles(viz: Any, graph: Graph) -> None:
+ """Update the styles of the entrypoint and END nodes.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ if first := graph.first_node():
+ viz.get_node(first.id).attr.update(fillcolor="lightblue")
+ if last := graph.last_node():
+ viz.get_node(last.id).attr.update(fillcolor="orange")
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85386735cd202b02ac0b503a414a2ecbb72960b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py
@@ -0,0 +1,631 @@
+"""`Runnable` that manages chat message history for another `Runnable`."""
+
+from __future__ import annotations
+
+import inspect
+from collections.abc import Callable, Sequence
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from pydantic import BaseModel
+from typing_extensions import override
+
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.load.load import load
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+from langchain_core.runnables.base import Runnable, RunnableBindingBase, RunnableLambda
+from langchain_core.runnables.passthrough import RunnablePassthrough
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Output,
+ get_unique_config_specs,
+)
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from langchain_core.language_models.base import LanguageModelLike
+ from langchain_core.runnables.config import RunnableConfig
+ from langchain_core.tracers.schemas import Run
+
+
+MessagesOrDictWithMessages = Sequence["BaseMessage"] | dict[str, Any]
+GetSessionHistoryCallable = Callable[..., BaseChatMessageHistory]
+
+
+class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
+ """`Runnable` that manages chat message history for another `Runnable`.
+
+ A chat message history is a sequence of messages that represent a conversation.
+
+ `RunnableWithMessageHistory` wraps another `Runnable` and manages the chat message
+ history for it; it is responsible for reading and updating the chat message
+ history.
+
+ The formats supported for the inputs and outputs of the wrapped `Runnable`
+ are described below.
+
+ `RunnableWithMessageHistory` must always be called with a config that contains
+ the appropriate parameters for the chat message history factory.
+
+ By default, the `Runnable` is expected to take a single configuration parameter
+ called `session_id` which is a string. This parameter is used to create a new
+ or look up an existing chat message history that matches the given `session_id`.
+
+ In this case, the invocation would look like this:
+
+ `with_history.invoke(..., config={"configurable": {"session_id": "bar"}})`
+ ; e.g., `{"configurable": {"session_id": ""}}`.
+
+ The configuration can be customized by passing in a list of
+ `ConfigurableFieldSpec` objects to the `history_factory_config` parameter (see
+ example below).
+
+ In the examples, we will use a chat message history with an in-memory
+ implementation to make it easy to experiment and see the results.
+
+ For production use cases, you will want to use a persistent implementation
+ of chat message history, such as `RedisChatMessageHistory`.
+
+ Example: Chat message history with an in-memory implementation for testing.
+
+ ```python
+ from operator import itemgetter
+
+ from langchain_openai.chat_models import ChatOpenAI
+
+ from langchain_core.chat_history import BaseChatMessageHistory
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage, AIMessage
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+ from pydantic import BaseModel, Field
+ from langchain_core.runnables import (
+ RunnableLambda,
+ ConfigurableFieldSpec,
+ RunnablePassthrough,
+ )
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+
+
+ class InMemoryHistory(BaseChatMessageHistory, BaseModel):
+ \"\"\"In memory implementation of chat message history.\"\"\"
+
+ messages: list[BaseMessage] = Field(default_factory=list)
+
+ def add_messages(self, messages: list[BaseMessage]) -> None:
+ \"\"\"Add a list of messages to the store\"\"\"
+ self.messages.extend(messages)
+
+ def clear(self) -> None:
+ self.messages = []
+
+ # Here we use a global variable to store the chat message history.
+ # This will make it easier to inspect it to see the underlying results.
+ store = {}
+
+ def get_by_session_id(session_id: str) -> BaseChatMessageHistory:
+ if session_id not in store:
+ store[session_id] = InMemoryHistory()
+ return store[session_id]
+
+
+ history = get_by_session_id("1")
+ history.add_message(AIMessage(content="hello"))
+ print(store) # noqa: T201
+
+ ```
+
+ Example where the wrapped `Runnable` takes a dictionary input:
+
+ ```python
+ from typing import Optional
+
+ from langchain_anthropic import ChatAnthropic
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You're an assistant who's good at {ability}"),
+ MessagesPlaceholder(variable_name="history"),
+ ("human", "{question}"),
+ ]
+ )
+
+ chain = prompt | ChatAnthropic(model="claude-2")
+
+ chain_with_history = RunnableWithMessageHistory(
+ chain,
+ # Uses the get_by_session_id function defined in the example
+ # above.
+ get_by_session_id,
+ input_messages_key="question",
+ history_messages_key="history",
+ )
+
+ print(
+ chain_with_history.invoke( # noqa: T201
+ {"ability": "math", "question": "What does cosine mean?"},
+ config={"configurable": {"session_id": "foo"}},
+ )
+ )
+
+ # Uses the store defined in the example above.
+ print(store) # noqa: T201
+
+ print(
+ chain_with_history.invoke( # noqa: T201
+ {"ability": "math", "question": "What's its inverse"},
+ config={"configurable": {"session_id": "foo"}},
+ )
+ )
+
+ print(store) # noqa: T201
+ ```
+
+ Example where the session factory takes two keys (`user_id` and `conversation_id`):
+
+ ```python
+ store = {}
+
+
+ def get_session_history(
+ user_id: str, conversation_id: str
+ ) -> BaseChatMessageHistory:
+ if (user_id, conversation_id) not in store:
+ store[(user_id, conversation_id)] = InMemoryHistory()
+ return store[(user_id, conversation_id)]
+
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You're an assistant who's good at {ability}"),
+ MessagesPlaceholder(variable_name="history"),
+ ("human", "{question}"),
+ ]
+ )
+
+ chain = prompt | ChatAnthropic(model="claude-2")
+
+ with_message_history = RunnableWithMessageHistory(
+ chain,
+ get_session_history=get_session_history,
+ input_messages_key="question",
+ history_messages_key="history",
+ history_factory_config=[
+ ConfigurableFieldSpec(
+ id="user_id",
+ annotation=str,
+ name="User ID",
+ description="Unique identifier for the user.",
+ default="",
+ is_shared=True,
+ ),
+ ConfigurableFieldSpec(
+ id="conversation_id",
+ annotation=str,
+ name="Conversation ID",
+ description="Unique identifier for the conversation.",
+ default="",
+ is_shared=True,
+ ),
+ ],
+ )
+
+ with_message_history.invoke(
+ {"ability": "math", "question": "What does cosine mean?"},
+ config={"configurable": {"user_id": "123", "conversation_id": "1"}},
+ )
+ ```
+ """
+
+ get_session_history: GetSessionHistoryCallable
+ """Function that returns a new `BaseChatMessageHistory`.
+
+ This function should either take a single positional argument `session_id` of type
+ string and return a corresponding chat message history instance
+ """
+ input_messages_key: str | None = None
+ """Must be specified if the base `Runnable` accepts a `dict` as input.
+ The key in the input `dict` that contains the messages.
+ """
+ output_messages_key: str | None = None
+ """Must be specified if the base `Runnable` returns a `dict` as output.
+ The key in the output `dict` that contains the messages.
+ """
+ history_messages_key: str | None = None
+ """Must be specified if the base `Runnable` accepts a `dict` as input and expects a
+ separate key for historical messages.
+ """
+ history_factory_config: Sequence[ConfigurableFieldSpec]
+ """Configure fields that should be passed to the chat history factory.
+
+ See `ConfigurableFieldSpec` for more details.
+ """
+
+ def __init__(
+ self,
+ runnable: Runnable[
+ list[BaseMessage], str | BaseMessage | MessagesOrDictWithMessages
+ ]
+ | Runnable[dict[str, Any], str | BaseMessage | MessagesOrDictWithMessages]
+ | LanguageModelLike,
+ get_session_history: GetSessionHistoryCallable,
+ *,
+ input_messages_key: str | None = None,
+ output_messages_key: str | None = None,
+ history_messages_key: str | None = None,
+ history_factory_config: Sequence[ConfigurableFieldSpec] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize `RunnableWithMessageHistory`.
+
+ Args:
+ runnable: The base `Runnable` to be wrapped.
+
+ Must take as input one of:
+
+ 1. A list of `BaseMessage`
+ 2. A `dict` with one key for all messages
+ 3. A `dict` with one key for the current input string/message(s) and
+ a separate key for historical messages. If the input key points
+ to a string, it will be treated as a `HumanMessage` in history.
+
+ Must return as output one of:
+
+ 1. A string which can be treated as an `AIMessage`
+ 2. A `BaseMessage` or sequence of `BaseMessage`
+ 3. A `dict` with a key for a `BaseMessage` or sequence of
+ `BaseMessage`
+
+ get_session_history: Function that returns a new `BaseChatMessageHistory`.
+
+ This function should either take a single positional argument
+ `session_id` of type string and return a corresponding
+ chat message history instance.
+
+ ```python
+ def get_session_history(
+ session_id: str, *, user_id: str | None = None
+ ) -> BaseChatMessageHistory: ...
+ ```
+
+ Or it should take keyword arguments that match the keys of
+ `session_history_config_specs` and return a corresponding
+ chat message history instance.
+
+ ```python
+ def get_session_history(
+ *,
+ user_id: str,
+ thread_id: str,
+ ) -> BaseChatMessageHistory: ...
+ ```
+
+ input_messages_key: Must be specified if the base runnable accepts a `dict`
+ as input.
+ output_messages_key: Must be specified if the base runnable returns a `dict`
+ as output.
+ history_messages_key: Must be specified if the base runnable accepts a
+ `dict` as input and expects a separate key for historical messages.
+ history_factory_config: Configure fields that should be passed to the
+ chat history factory. See `ConfigurableFieldSpec` for more details.
+
+ Specifying these allows you to pass multiple config keys into the
+ `get_session_history` factory.
+ **kwargs: Arbitrary additional kwargs to pass to parent class
+ `RunnableBindingBase` init.
+
+ """
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "RunnableWithMessageHistory is deprecated. "
+ "Use LangGraph's built-in persistence instead."
+ ),
+ removal="2.0.0",
+ )
+ history_chain: Runnable[Any, Any] = RunnableLambda(
+ self._enter_history, self._aenter_history
+ ).with_config(run_name="load_history")
+ messages_key = history_messages_key or input_messages_key
+ if messages_key:
+ history_chain = RunnablePassthrough.assign(
+ **{messages_key: history_chain}
+ ).with_config(run_name="insert_history")
+
+ runnable_sync = runnable.with_listeners(on_end=self._exit_history)
+ runnable_async = runnable.with_alisteners(on_end=self._aexit_history)
+
+ def _call_runnable_sync(_input: Any) -> Runnable[Any, Any]:
+ return runnable_sync
+
+ async def _call_runnable_async(_input: Any) -> Runnable[Any, Any]:
+ return runnable_async
+
+ bound = (
+ history_chain
+ | RunnableLambda(
+ _call_runnable_sync,
+ _call_runnable_async,
+ ).with_config(run_name="check_sync_or_async")
+ ).with_config(run_name="RunnableWithMessageHistory")
+
+ if history_factory_config:
+ config_specs = history_factory_config
+ else:
+ # If not provided, then we'll use the default session_id field
+ config_specs = [
+ ConfigurableFieldSpec(
+ id="session_id",
+ annotation=str,
+ name="Session ID",
+ description="Unique identifier for a session.",
+ default="",
+ is_shared=True,
+ ),
+ ]
+
+ super().__init__(
+ get_session_history=get_session_history,
+ input_messages_key=input_messages_key,
+ output_messages_key=output_messages_key,
+ bound=bound,
+ history_messages_key=history_messages_key,
+ history_factory_config=config_specs,
+ **kwargs,
+ )
+ self._history_chain = history_chain
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the configuration specs for the `RunnableWithMessageHistory`."""
+ return get_unique_config_specs(
+ super().config_specs + list(self.history_factory_config)
+ )
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ fields: dict = {}
+ if self.input_messages_key and self.history_messages_key:
+ fields[self.input_messages_key] = (
+ str | BaseMessage | Sequence[BaseMessage],
+ ...,
+ )
+ elif self.input_messages_key:
+ fields[self.input_messages_key] = (Sequence[BaseMessage], ...)
+ else:
+ return create_model_v2(
+ "RunnableWithChatHistoryInput",
+ module_name=self.__class__.__module__,
+ root=(Sequence[BaseMessage], ...),
+ )
+ return create_model_v2(
+ "RunnableWithChatHistoryInput",
+ field_definitions=fields,
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self._history_chain.OutputType
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate output to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic output schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an output schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate output.
+ """
+ root_type = self.OutputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ "RunnableWithChatHistoryOutput",
+ root=root_type,
+ module_name=self.__class__.__module__,
+ )
+
+ def _get_input_messages(
+ self, input_val: str | BaseMessage | Sequence[BaseMessage] | dict
+ ) -> list[BaseMessage]:
+ # If dictionary, try to pluck the single key representing messages
+ if isinstance(input_val, dict):
+ if self.input_messages_key:
+ key = self.input_messages_key
+ elif len(input_val) == 1:
+ key = next(iter(input_val.keys()))
+ else:
+ key = "input"
+ input_val = input_val[key]
+
+ # If value is a string, convert to a human message
+ if isinstance(input_val, str):
+ return [HumanMessage(content=input_val)]
+ # If value is a single message, convert to a list
+ if isinstance(input_val, BaseMessage):
+ return [input_val]
+ # If value is a list or tuple...
+ if isinstance(input_val, (list, tuple)):
+ # Handle empty case
+ if len(input_val) == 0:
+ return list(input_val)
+ # If is a list of list, then return the first value
+ # This occurs for chat models - since we batch inputs
+ if isinstance(input_val[0], list):
+ if len(input_val) != 1:
+ msg = f"Expected a single list of messages. Got {input_val}."
+ raise ValueError(msg)
+ return input_val[0]
+ return list(input_val)
+ msg = (
+ f"Expected str, BaseMessage, list[BaseMessage], or tuple[BaseMessage]. "
+ f"Got {input_val}."
+ )
+ raise ValueError(msg)
+
+ def _get_output_messages(
+ self, output_val: str | BaseMessage | Sequence[BaseMessage] | dict
+ ) -> list[BaseMessage]:
+ # If dictionary, try to pluck the single key representing messages
+ if isinstance(output_val, dict):
+ if self.output_messages_key:
+ key = self.output_messages_key
+ elif len(output_val) == 1:
+ key = next(iter(output_val.keys()))
+ else:
+ key = "output"
+ # If you are wrapping a chat model directly
+ # The output is actually this weird generations object
+ if key not in output_val and "generations" in output_val:
+ output_val = output_val["generations"][0][0]["message"]
+ else:
+ output_val = output_val[key]
+
+ if isinstance(output_val, str):
+ return [AIMessage(content=output_val)]
+ # If value is a single message, convert to a list
+ if isinstance(output_val, BaseMessage):
+ return [output_val]
+ if isinstance(output_val, (list, tuple)):
+ return list(output_val)
+ msg = (
+ f"Expected str, BaseMessage, list[BaseMessage], or tuple[BaseMessage]. "
+ f"Got {output_val}."
+ )
+ raise ValueError(msg)
+
+ def _enter_history(self, value: Any, config: RunnableConfig) -> list[BaseMessage]:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+ messages = hist.messages.copy()
+
+ if not self.history_messages_key:
+ # return all messages
+ input_val = (
+ value if not self.input_messages_key else value[self.input_messages_key]
+ )
+ messages += self._get_input_messages(input_val)
+ return messages
+
+ async def _aenter_history(
+ self, value: dict[str, Any], config: RunnableConfig
+ ) -> list[BaseMessage]:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+ messages = (await hist.aget_messages()).copy()
+
+ if not self.history_messages_key:
+ # return all messages
+ input_val = (
+ value if not self.input_messages_key else value[self.input_messages_key]
+ )
+ messages += self._get_input_messages(input_val)
+ return messages
+
+ def _exit_history(self, run: Run, config: RunnableConfig) -> None:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+
+ # Get the input messages
+ inputs = load(run.inputs, allowed_objects="messages")
+ input_messages = self._get_input_messages(inputs)
+ # If historic messages were prepended to the input messages, remove them to
+ # avoid adding duplicate messages to history.
+ if not self.history_messages_key:
+ historic_messages = config["configurable"]["message_history"].messages
+ input_messages = input_messages[len(historic_messages) :]
+
+ # Get the output messages
+ output_val = load(run.outputs, allowed_objects="messages")
+ output_messages = self._get_output_messages(output_val)
+ hist.add_messages(input_messages + output_messages)
+
+ async def _aexit_history(self, run: Run, config: RunnableConfig) -> None:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+
+ # Get the input messages
+ inputs = load(run.inputs, allowed_objects="messages")
+ input_messages = self._get_input_messages(inputs)
+ # If historic messages were prepended to the input messages, remove them to
+ # avoid adding duplicate messages to history.
+ if not self.history_messages_key:
+ historic_messages = await hist.aget_messages()
+ input_messages = input_messages[len(historic_messages) :]
+
+ # Get the output messages
+ output_val = load(run.outputs, allowed_objects="messages")
+ output_messages = self._get_output_messages(output_val)
+ await hist.aadd_messages(input_messages + output_messages)
+
+ def _merge_configs(self, *configs: RunnableConfig | None) -> RunnableConfig:
+ config = super()._merge_configs(*configs)
+ expected_keys = [field_spec.id for field_spec in self.history_factory_config]
+
+ configurable = config.get("configurable", {})
+
+ missing_keys = set(expected_keys) - set(configurable.keys())
+ parameter_names = _get_parameter_names(self.get_session_history)
+
+ if missing_keys and parameter_names:
+ example_input = {self.input_messages_key: "foo"}
+ example_configurable = dict.fromkeys(missing_keys, "[your-value-here]")
+ example_config = {"configurable": example_configurable}
+ msg = (
+ f"Missing keys {sorted(missing_keys)} in config['configurable'] "
+ f"Expected keys are {sorted(expected_keys)}."
+ f"When using via .invoke() or .stream(), pass in a config; "
+ f"e.g., chain.invoke({example_input}, {example_config})"
+ )
+ raise ValueError(msg)
+
+ if len(expected_keys) == 1:
+ if parameter_names:
+ # If arity = 1, then invoke function by positional arguments
+ message_history = self.get_session_history(
+ configurable[expected_keys[0]]
+ )
+ else:
+ if not config:
+ config["configurable"] = {}
+ message_history = self.get_session_history()
+ else:
+ # otherwise verify that names of keys patch and invoke by named arguments
+ if set(expected_keys) != set(parameter_names):
+ msg = (
+ f"Expected keys {sorted(expected_keys)} do not match parameter "
+ f"names {sorted(parameter_names)} of get_session_history."
+ )
+ raise ValueError(msg)
+
+ message_history = self.get_session_history(
+ **{key: configurable[key] for key in expected_keys}
+ )
+ config["configurable"]["message_history"] = message_history
+ return config
+
+
+def _get_parameter_names(callable_: GetSessionHistoryCallable) -> list[str]:
+ """Get the parameter names of the `Callable`."""
+ sig = inspect.signature(callable_)
+ return list(sig.parameters.keys())
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/passthrough.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/passthrough.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5e01cfe20fd8a273a1e64cf42ba22f98f5f8f27
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/passthrough.py
@@ -0,0 +1,841 @@
+"""Implementation of the `RunnablePassthrough`."""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import threading
+from collections.abc import Awaitable, Callable
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+from pydantic import BaseModel, RootModel
+from typing_extensions import override
+
+from langchain_core.runnables.base import (
+ Other,
+ Runnable,
+ RunnableParallel,
+ RunnableSerializable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+ ensure_config,
+ get_executor_for_config,
+ patch_config,
+)
+from langchain_core.runnables.utils import (
+ AddableDict,
+ ConfigurableFieldSpec,
+)
+from langchain_core.utils.aiter import atee
+from langchain_core.utils.iter import safetee
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Mapping
+
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+ from langchain_core.runnables.graph import Graph
+
+
+def identity(x: Other) -> Other:
+ """Identity function.
+
+ Args:
+ x: Input.
+
+ Returns:
+ Output.
+ """
+ return x
+
+
+async def aidentity(x: Other) -> Other:
+ """Async identity function.
+
+ Args:
+ x: Input.
+
+ Returns:
+ Output.
+ """
+ return x
+
+
+class RunnablePassthrough(RunnableSerializable[Other, Other]):
+ """Runnable to passthrough inputs unchanged or with additional keys.
+
+ This `Runnable` behaves almost like the identity function, except that it
+ can be configured to add additional keys to the output, if the input is a
+ dict.
+
+ The examples below demonstrate this `Runnable` works using a few simple
+ chains. The chains rely on simple lambdas to make the examples easy to execute
+ and experiment with.
+
+ Examples:
+ ```python
+ from langchain_core.runnables import (
+ RunnableLambda,
+ RunnableParallel,
+ RunnablePassthrough,
+ )
+
+ runnable = RunnableParallel(
+ origin=RunnablePassthrough(), modified=lambda x: x + 1
+ )
+
+ runnable.invoke(1) # {'origin': 1, 'modified': 2}
+
+
+ def fake_llm(prompt: str) -> str: # Fake LLM for the example
+ return "completion"
+
+
+ chain = RunnableLambda(fake_llm) | {
+ "original": RunnablePassthrough(), # Original LLM output
+ "parsed": lambda text: text[::-1], # Parsing logic
+ }
+
+ chain.invoke("hello") # {'original': 'completion', 'parsed': 'noitelpmoc'}
+ ```
+
+ In some cases, it may be useful to pass the input through while adding some
+ keys to the output. In this case, you can use the `assign` method:
+
+ ```python
+ from langchain_core.runnables import RunnablePassthrough
+
+
+ def fake_llm(prompt: str) -> str: # Fake LLM for the example
+ return "completion"
+
+
+ runnable = {
+ "llm1": fake_llm,
+ "llm2": fake_llm,
+ } | RunnablePassthrough.assign(
+ total_chars=lambda inputs: len(inputs["llm1"] + inputs["llm2"])
+ )
+
+ runnable.invoke("hello")
+ # {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}
+ ```
+ """
+
+ input_type: type[Other] | None = None
+
+ func: Callable[[Other], None] | Callable[[Other, RunnableConfig], None] | None = (
+ None
+ )
+
+ afunc: (
+ Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None
+ ) = None
+
+ @override
+ def __repr_args__(self) -> Any:
+ # Without this repr(self) raises a RecursionError
+ # See https://github.com/pydantic/pydantic/issues/7327
+ return []
+
+ def __init__(
+ self,
+ func: Callable[[Other], None]
+ | Callable[[Other, RunnableConfig], None]
+ | Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None = None,
+ afunc: Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None = None,
+ *,
+ input_type: type[Other] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Create a `RunnablePassthrough`.
+
+ Args:
+ func: Function to be called with the input.
+ afunc: Async function to be called with the input.
+ input_type: Type of the input.
+ """
+ if inspect.iscoroutinefunction(func):
+ afunc = func
+ func = None
+
+ super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ return self.input_type or Any
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ return self.input_type or Any
+
+ @classmethod
+ @override
+ def assign(
+ cls,
+ **kwargs: Runnable[dict[str, Any], Any]
+ | Callable[[dict[str, Any]], Any]
+ | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]],
+ ) -> RunnableAssign:
+ """Merge the Dict input with the output produced by the mapping argument.
+
+ Args:
+ **kwargs: `Runnable`, `Callable` or a `Mapping` from keys to `Runnable`
+ objects or `Callable`s.
+
+ Returns:
+ A `Runnable` that merges the `dict` input with the output produced by the
+ mapping argument.
+ """
+ return RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
+
+ @override
+ def invoke(
+ self, input: Other, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Other:
+ if self.func is not None:
+ call_func_with_variable_args(
+ self.func, input, ensure_config(config), **kwargs
+ )
+ return self._call_with_config(identity, input, config)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Other:
+ if self.afunc is not None:
+ await acall_func_with_variable_args(
+ self.afunc, input, ensure_config(config), **kwargs
+ )
+ elif self.func is not None:
+ call_func_with_variable_args(
+ self.func, input, ensure_config(config), **kwargs
+ )
+ return await self._acall_with_config(aidentity, input, config)
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Other],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Other]:
+ if self.func is None:
+ for chunk in self._transform_stream_with_config(input, identity, config):
+ yield chunk
+ else:
+ final: Other
+ got_first_chunk = False
+
+ for chunk in self._transform_stream_with_config(input, identity, config):
+ yield chunk
+
+ if not got_first_chunk:
+ final = chunk
+ got_first_chunk = True
+ else:
+ try:
+ final = final + chunk # type: ignore[operator]
+ except TypeError:
+ final = chunk
+
+ if got_first_chunk:
+ call_func_with_variable_args(
+ self.func, final, ensure_config(config), **kwargs
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Other],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Other]:
+ if self.afunc is None and self.func is None:
+ async for chunk in self._atransform_stream_with_config(
+ input, identity, config
+ ):
+ yield chunk
+ else:
+ got_first_chunk = False
+
+ async for chunk in self._atransform_stream_with_config(
+ input, identity, config
+ ):
+ yield chunk
+
+ # By definitions, a function will operate on the aggregated
+ # input. So we'll aggregate the input until we get to the last
+ # chunk.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ if not got_first_chunk:
+ final = chunk
+ got_first_chunk = True
+ else:
+ try:
+ final = final + chunk # type: ignore[operator]
+ except TypeError:
+ final = chunk
+
+ if got_first_chunk:
+ config = ensure_config(config)
+ if self.afunc is not None:
+ await acall_func_with_variable_args(
+ self.afunc, final, config, **kwargs
+ )
+ elif self.func is not None:
+ call_func_with_variable_args(self.func, final, config, **kwargs)
+
+ @override
+ def stream(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Other]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Other]:
+ async def input_aiter() -> AsyncIterator[Other]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+_graph_passthrough: RunnablePassthrough = RunnablePassthrough()
+
+
+class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
+ """Runnable that assigns key-value pairs to `dict[str, Any]` inputs.
+
+ The `RunnableAssign` class takes input dictionaries and, through a
+ `RunnableParallel` instance, applies transformations, then combines
+ these with the original data, introducing new key-value pairs based
+ on the mapper's logic.
+
+ Examples:
+ ```python
+ # This is a RunnableAssign
+ from langchain_core.runnables.passthrough import (
+ RunnableAssign,
+ RunnableParallel,
+ )
+ from langchain_core.runnables.base import RunnableLambda
+
+
+ def add_ten(x: dict[str, int]) -> dict[str, int]:
+ return {"added": x["input"] + 10}
+
+
+ mapper = RunnableParallel(
+ {
+ "add_step": RunnableLambda(add_ten),
+ }
+ )
+
+ runnable_assign = RunnableAssign(mapper)
+
+ # Synchronous example
+ runnable_assign.invoke({"input": 5})
+ # returns {'input': 5, 'add_step': {'added': 15}}
+
+ # Asynchronous example
+ await runnable_assign.ainvoke({"input": 5})
+ # returns {'input': 5, 'add_step': {'added': 15}}
+ ```
+ """
+
+ mapper: RunnableParallel
+
+ def __init__(self, mapper: RunnableParallel[dict[str, Any]], **kwargs: Any) -> None:
+ """Create a `RunnableAssign`.
+
+ Args:
+ mapper: A `RunnableParallel` instance that will be used to transform the
+ input dictionary.
+ """
+ super().__init__(mapper=mapper, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = (
+ name
+ or self.name
+ or f"RunnableAssign<{','.join(self.mapper.steps__.keys())}>"
+ )
+ return super().get_name(suffix, name=name)
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ map_input_schema = self.mapper.get_input_schema(config)
+ if not issubclass(map_input_schema, RootModel):
+ # ie. it's a dict
+ return map_input_schema
+
+ return super().get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ map_input_schema = self.mapper.get_input_schema(config)
+ map_output_schema = self.mapper.get_output_schema(config)
+ if not issubclass(map_input_schema, RootModel) and not issubclass(
+ map_output_schema, RootModel
+ ):
+ fields = {}
+
+ for name, field_info in map_input_schema.model_fields.items():
+ fields[name] = (field_info.annotation, field_info.default)
+
+ for name, field_info in map_output_schema.model_fields.items():
+ fields[name] = (field_info.annotation, field_info.default)
+
+ return create_model_v2("RunnableAssignOutput", field_definitions=fields)
+ if not issubclass(map_output_schema, RootModel):
+ # ie. only map output is a dict
+ # ie. input type is either unknown or inferred incorrectly
+ return map_output_schema
+
+ return super().get_output_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.mapper.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ # get graph from mapper
+ graph = self.mapper.get_graph(config)
+ # add passthrough node and edges
+ input_node = graph.first_node()
+ output_node = graph.last_node()
+ if input_node is not None and output_node is not None:
+ passthrough_node = graph.add_node(_graph_passthrough)
+ graph.add_edge(input_node, passthrough_node)
+ graph.add_edge(passthrough_node, output_node)
+ return graph
+
+ def _invoke(
+ self,
+ value: dict[str, Any],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ return {
+ **value,
+ **self.mapper.invoke(
+ value,
+ patch_config(config, callbacks=run_manager.get_child()),
+ **kwargs,
+ ),
+ }
+
+ @override
+ def invoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ value: dict[str, Any],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ return {
+ **value,
+ **await self.mapper.ainvoke(
+ value,
+ patch_config(config, callbacks=run_manager.get_child()),
+ **kwargs,
+ ),
+ }
+
+ @override
+ async def ainvoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _transform(
+ self,
+ values: Iterator[dict[str, Any]],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ # collect mapper keys
+ mapper_keys = set(self.mapper.steps__.keys())
+ # create two streams, one for the map and one for the passthrough
+ for_passthrough, for_map = safetee(values, 2, lock=threading.Lock())
+
+ # create map output stream
+ map_output = self.mapper.transform(
+ for_map,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ ),
+ **kwargs,
+ )
+
+ # get executor to start map output stream in background
+ with get_executor_for_config(config) as executor:
+ # start map output stream
+ first_map_chunk_future = executor.submit(
+ next,
+ map_output,
+ None,
+ )
+ # consume passthrough stream
+ for chunk in for_passthrough:
+ if not isinstance(chunk, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+ # remove mapper keys from passthrough chunk, to be overwritten by map
+ filtered = AddableDict(
+ {k: v for k, v in chunk.items() if k not in mapper_keys}
+ )
+ if filtered:
+ yield filtered
+ # yield map output
+ yield cast("dict[str, Any]", first_map_chunk_future.result())
+ for chunk in map_output:
+ yield chunk
+
+ @override
+ def transform(
+ self,
+ input: Iterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ async def _atransform(
+ self,
+ values: AsyncIterator[dict[str, Any]],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ # collect mapper keys
+ mapper_keys = set(self.mapper.steps__.keys())
+ # create two streams, one for the map and one for the passthrough
+ for_passthrough, for_map = atee(values, 2, lock=asyncio.Lock())
+ # create map output stream
+ map_output = self.mapper.atransform(
+ for_map,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ ),
+ **kwargs,
+ )
+ # start map output stream
+ first_map_chunk_task: asyncio.Task = asyncio.create_task(
+ anext(map_output, None),
+ )
+ # consume passthrough stream
+ async for chunk in for_passthrough:
+ if not isinstance(chunk, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ # remove mapper keys from passthrough chunk, to be overwritten by map output
+ filtered = AddableDict(
+ {k: v for k, v in chunk.items() if k not in mapper_keys}
+ )
+ if filtered:
+ yield filtered
+ # yield map output
+ yield await first_map_chunk_task
+ async for chunk in map_output:
+ yield chunk
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ def stream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async def input_aiter() -> AsyncIterator[dict[str, Any]]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnablePick(RunnableSerializable[dict[str, Any], Any]):
+ """`Runnable` that picks keys from `dict[str, Any]` inputs.
+
+ `RunnablePick` class represents a `Runnable` that selectively picks keys from a
+ dictionary input. It allows you to specify one or more keys to extract
+ from the input dictionary.
+
+ !!! note "Return Type Behavior"
+ The return type depends on the `keys` parameter:
+
+ - When `keys` is a `str`: Returns the single value associated with that key
+ - When `keys` is a `list`: Returns a dictionary containing only the selected
+ keys
+
+ Example:
+ ```python
+ from langchain_core.runnables.passthrough import RunnablePick
+
+ input_data = {
+ "name": "John",
+ "age": 30,
+ "city": "New York",
+ "country": "USA",
+ }
+
+ # Single key - returns the value directly
+ runnable_single = RunnablePick(keys="name")
+ result_single = runnable_single.invoke(input_data)
+ print(result_single) # Output: "John"
+
+ # Multiple keys - returns a dictionary
+ runnable_multiple = RunnablePick(keys=["name", "age"])
+ result_multiple = runnable_multiple.invoke(input_data)
+ print(result_multiple) # Output: {'name': 'John', 'age': 30}
+ ```
+ """
+
+ keys: str | list[str]
+
+ def __init__(self, keys: str | list[str], **kwargs: Any) -> None:
+ """Create a `RunnablePick`.
+
+ Args:
+ keys: A single key or a list of keys to pick from the input dictionary.
+ """
+ super().__init__(keys=keys, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = (
+ name
+ or self.name
+ or "RunnablePick"
+ f"<{','.join([self.keys] if isinstance(self.keys, str) else self.keys)}>"
+ )
+ return super().get_name(suffix, name=name)
+
+ def _pick(self, value: dict[str, Any]) -> Any:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ if isinstance(self.keys, str):
+ return value.get(self.keys)
+ picked = {k: value.get(k) for k in self.keys if k in value}
+ if picked:
+ return AddableDict(picked)
+ return None
+
+ @override
+ def invoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ return self._call_with_config(self._pick, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ value: dict[str, Any],
+ ) -> Any:
+ return self._pick(value)
+
+ @override
+ async def ainvoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _transform(
+ self,
+ chunks: Iterator[dict[str, Any]],
+ ) -> Iterator[Any]:
+ for chunk in chunks:
+ picked = self._pick(chunk)
+ if picked is not None:
+ yield picked
+
+ @override
+ def transform(
+ self,
+ input: Iterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Any]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ async def _atransform(
+ self,
+ chunks: AsyncIterator[dict[str, Any]],
+ ) -> AsyncIterator[Any]:
+ async for chunk in chunks:
+ picked = self._pick(chunk)
+ if picked is not None:
+ yield picked
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Any]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ def stream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Any]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Any]:
+ async def input_aiter() -> AsyncIterator[dict[str, Any]]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/retry.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b9f5fef2de7d38ab51205f902edf22859c0d951
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/retry.py
@@ -0,0 +1,379 @@
+"""`Runnable` that retries a `Runnable` if it fails."""
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypeVar,
+ cast,
+)
+
+from tenacity import (
+ AsyncRetrying,
+ RetryCallState,
+ RetryError,
+ Retrying,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential_jitter,
+)
+from typing_extensions import TypedDict, override
+
+from langchain_core.runnables.base import RunnableBindingBase
+from langchain_core.runnables.config import RunnableConfig, patch_config
+from langchain_core.runnables.utils import Input, Output
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+
+ T = TypeVar("T", CallbackManagerForChainRun, AsyncCallbackManagerForChainRun)
+U = TypeVar("U")
+
+
+class ExponentialJitterParams(TypedDict, total=False):
+ """Parameters for `tenacity.wait_exponential_jitter`."""
+
+ initial: float
+ """Initial wait."""
+ max: float
+ """Maximum wait."""
+ exp_base: float
+ """Base for exponential backoff."""
+ jitter: float
+ """Random additional wait sampled from random.uniform(0, jitter)."""
+
+
+class RunnableRetry(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
+ """Retry a Runnable if it fails.
+
+ RunnableRetry can be used to add retry logic to any object
+ that subclasses the base Runnable.
+
+ Such retries are especially useful for network calls that may fail
+ due to transient errors.
+
+ The RunnableRetry is implemented as a RunnableBinding. The easiest
+ way to use it is through the `.with_retry()` method on all Runnables.
+
+ Example:
+ Here's an example that uses a RunnableLambda to raise an exception
+
+ ```python
+ import time
+
+
+ def foo(input) -> None:
+ '''Fake function that raises an exception.'''
+ raise ValueError(f"Invoking foo failed. At time {time.time()}")
+
+
+ runnable = RunnableLambda(foo)
+
+ runnable_with_retries = runnable.with_retry(
+ retry_if_exception_type=(ValueError,), # Retry only on ValueError
+ wait_exponential_jitter=True, # Add jitter to the exponential backoff
+ stop_after_attempt=2, # Try twice
+ exponential_jitter_params={"initial": 2}, # if desired, customize backoff
+ )
+
+ # The method invocation above is equivalent to the longer form below:
+
+ runnable_with_retries = RunnableRetry(
+ bound=runnable,
+ retry_exception_types=(ValueError,),
+ max_attempt_number=2,
+ wait_exponential_jitter=True,
+ exponential_jitter_params={"initial": 2},
+ )
+ ```
+
+ This logic can be used to retry any Runnable, including a chain of Runnables,
+ but in general it's best practice to keep the scope of the retry as small as
+ possible. For example, if you have a chain of Runnables, you should only retry
+ the Runnable that is likely to fail, not the entire chain.
+
+ Example:
+ ```python
+ from langchain_core.chat_models import ChatOpenAI
+ from langchain_core.prompts import PromptTemplate
+
+ template = PromptTemplate.from_template("tell me a joke about {topic}.")
+ model = ChatOpenAI(temperature=0.5)
+
+ # Good
+ chain = template | model.with_retry()
+
+ # Bad
+ chain = template | model
+ retryable_chain = chain.with_retry()
+ ```
+ """
+
+ retry_exception_types: tuple[type[BaseException], ...] = (Exception,)
+ """The exception types to retry on. By default all exceptions are retried.
+
+ In general you should only retry on exceptions that are likely to be
+ transient, such as network errors.
+
+ Good exceptions to retry are all server errors (5xx) and selected client
+ errors (4xx) such as 429 Too Many Requests.
+ """
+
+ wait_exponential_jitter: bool = True
+ """Whether to add jitter to the exponential backoff."""
+
+ exponential_jitter_params: ExponentialJitterParams | None = None
+ """Parameters for `tenacity.wait_exponential_jitter`. Namely: `initial`,
+ `max`, `exp_base`, and `jitter` (all `float` values).
+ """
+
+ max_attempt_number: int = 3
+ """The maximum number of attempts to retry the Runnable."""
+
+ @property
+ def _kwargs_retrying(self) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {}
+
+ if self.max_attempt_number:
+ kwargs["stop"] = stop_after_attempt(self.max_attempt_number)
+
+ if self.wait_exponential_jitter:
+ kwargs["wait"] = wait_exponential_jitter(
+ **(self.exponential_jitter_params or {})
+ )
+
+ if self.retry_exception_types:
+ kwargs["retry"] = retry_if_exception_type(self.retry_exception_types)
+
+ return kwargs
+
+ def _sync_retrying(self, **kwargs: Any) -> Retrying:
+ return Retrying(**self._kwargs_retrying, **kwargs)
+
+ def _async_retrying(self, **kwargs: Any) -> AsyncRetrying:
+ return AsyncRetrying(**self._kwargs_retrying, **kwargs)
+
+ @staticmethod
+ def _patch_config(
+ config: RunnableConfig,
+ run_manager: "T",
+ retry_state: RetryCallState,
+ ) -> RunnableConfig:
+ attempt = retry_state.attempt_number
+ tag = f"retry:attempt:{attempt}" if attempt > 1 else None
+ return patch_config(config, callbacks=run_manager.get_child(tag))
+
+ def _patch_config_list(
+ self,
+ config: list[RunnableConfig],
+ run_manager: list["T"],
+ retry_state: RetryCallState,
+ ) -> list[RunnableConfig]:
+ return [
+ self._patch_config(c, rm, retry_state)
+ for c, rm in zip(config, run_manager, strict=False)
+ ]
+
+ def _invoke(
+ self,
+ input_: Input,
+ run_manager: "CallbackManagerForChainRun",
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ for attempt in self._sync_retrying(reraise=True):
+ with attempt:
+ result = super().invoke(
+ input_,
+ self._patch_config(config, run_manager, attempt.retry_state),
+ **kwargs,
+ )
+ if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:
+ attempt.retry_state.set_result(result)
+ return result
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ input_: Input,
+ run_manager: "AsyncCallbackManagerForChainRun",
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ async for attempt in self._async_retrying(reraise=True):
+ with attempt:
+ result = await super().ainvoke(
+ input_,
+ self._patch_config(config, run_manager, attempt.retry_state),
+ **kwargs,
+ )
+ if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:
+ attempt.retry_state.set_result(result)
+ return result
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _batch(
+ self,
+ inputs: list[Input],
+ run_manager: list["CallbackManagerForChainRun"],
+ config: list[RunnableConfig],
+ **kwargs: Any,
+ ) -> list[Output | Exception]:
+ results_map: dict[int, Output] = {}
+
+ not_set: list[Output] = []
+ result = not_set
+ try:
+ for attempt in self._sync_retrying():
+ with attempt:
+ # Retry for inputs that have not yet succeeded
+ # Determine which original indices remain.
+ remaining_indices = [
+ i for i in range(len(inputs)) if i not in results_map
+ ]
+ if not remaining_indices:
+ break
+ pending_inputs = [inputs[i] for i in remaining_indices]
+ pending_configs = [config[i] for i in remaining_indices]
+ pending_run_managers = [run_manager[i] for i in remaining_indices]
+ # Invoke underlying batch only on remaining elements.
+ result = super().batch(
+ pending_inputs,
+ self._patch_config_list(
+ pending_configs, pending_run_managers, attempt.retry_state
+ ),
+ return_exceptions=True,
+ **kwargs,
+ )
+ # Register the results of the inputs that have succeeded, mapping
+ # back to their original indices.
+ first_exception = None
+ for offset, r in enumerate(result):
+ if isinstance(r, Exception):
+ if not first_exception:
+ first_exception = r
+ continue
+ orig_idx = remaining_indices[offset]
+ results_map[orig_idx] = r
+ # If any exception occurred, raise it, to retry the failed ones
+ if first_exception:
+ raise first_exception
+ if (
+ attempt.retry_state.outcome
+ and not attempt.retry_state.outcome.failed
+ ):
+ attempt.retry_state.set_result(result)
+ except RetryError as e:
+ if result is not_set:
+ result = cast("list[Output]", [e] * len(inputs))
+
+ outputs: list[Output | Exception] = []
+ for idx in range(len(inputs)):
+ if idx in results_map:
+ outputs.append(results_map[idx])
+ else:
+ outputs.append(result.pop(0))
+ return outputs
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[Output]:
+ return self._batch_with_config(
+ self._batch, inputs, config, return_exceptions=return_exceptions, **kwargs
+ )
+
+ async def _abatch(
+ self,
+ inputs: list[Input],
+ run_manager: list["AsyncCallbackManagerForChainRun"],
+ config: list[RunnableConfig],
+ **kwargs: Any,
+ ) -> list[Output | Exception]:
+ results_map: dict[int, Output] = {}
+
+ not_set: list[Output] = []
+ result = not_set
+ try:
+ async for attempt in self._async_retrying():
+ with attempt:
+ # Retry for inputs that have not yet succeeded
+ # Determine which original indices remain.
+ remaining_indices = [
+ i for i in range(len(inputs)) if i not in results_map
+ ]
+ if not remaining_indices:
+ break
+ pending_inputs = [inputs[i] for i in remaining_indices]
+ pending_configs = [config[i] for i in remaining_indices]
+ pending_run_managers = [run_manager[i] for i in remaining_indices]
+ result = await super().abatch(
+ pending_inputs,
+ self._patch_config_list(
+ pending_configs, pending_run_managers, attempt.retry_state
+ ),
+ return_exceptions=True,
+ **kwargs,
+ )
+ # Register the results of the inputs that have succeeded, mapping
+ # back to their original indices.
+ first_exception = None
+ for offset, r in enumerate(result):
+ if isinstance(r, Exception):
+ if not first_exception:
+ first_exception = r
+ continue
+ orig_idx = remaining_indices[offset]
+ results_map[orig_idx] = r
+ # If any exception occurred, raise it, to retry the failed ones
+ if first_exception:
+ raise first_exception
+ if (
+ attempt.retry_state.outcome
+ and not attempt.retry_state.outcome.failed
+ ):
+ attempt.retry_state.set_result(result)
+ except RetryError as e:
+ if result is not_set:
+ result = cast("list[Output]", [e] * len(inputs))
+
+ outputs: list[Output | Exception] = []
+ for idx in range(len(inputs)):
+ if idx in results_map:
+ outputs.append(results_map[idx])
+ else:
+ outputs.append(result.pop(0))
+ return outputs
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[Output]:
+ return await self._abatch_with_config(
+ self._abatch, inputs, config, return_exceptions=return_exceptions, **kwargs
+ )
+
+ # stream() and transform() are not retried because retrying a stream
+ # is not very intuitive.
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/router.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/router.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6341da1c1617c3e9d481ec95f251d8dab5c472b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/router.py
@@ -0,0 +1,239 @@
+"""`Runnable` that routes to a set of `Runnable` objects."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+from pydantic import ConfigDict
+from typing_extensions import TypedDict, override
+
+from langchain_core.runnables.base import (
+ Runnable,
+ RunnableSerializable,
+ coerce_to_runnable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ get_config_list,
+ get_executor_for_config,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ gather_with_concurrency,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Callable, Iterator
+
+
+class RouterInput(TypedDict):
+ """Router input."""
+
+ key: str
+ """The key to route on."""
+ input: Any
+ """The input to pass to the selected `Runnable`."""
+
+
+class RouterRunnable(RunnableSerializable[RouterInput, Output]):
+ """`Runnable` that routes to a set of `Runnable` based on `Input['key']`.
+
+ Returns the output of the selected Runnable.
+
+ Example:
+ ```python
+ from langchain_core.runnables.router import RouterRunnable
+ from langchain_core.runnables import RunnableLambda
+
+ add = RunnableLambda(func=lambda x: x + 1)
+ square = RunnableLambda(func=lambda x: x**2)
+
+ router = RouterRunnable(runnables={"add": add, "square": square})
+ router.invoke({"key": "square", "input": 3})
+ ```
+ """
+
+ runnables: Mapping[str, Runnable[Any, Output]]
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec for step in self.runnables.values() for spec in step.config_specs
+ )
+
+ def __init__(
+ self,
+ runnables: Mapping[str, Runnable[Any, Output] | Callable[[Any], Output]],
+ ) -> None:
+ """Create a `RouterRunnable`.
+
+ Args:
+ runnables: A mapping of keys to `Runnable` objects.
+ """
+ super().__init__(
+ runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def invoke(
+ self, input: RouterInput, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ return runnable.invoke(actual_input, config)
+
+ @override
+ async def ainvoke(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ return await runnable.ainvoke(actual_input, config)
+
+ @override
+ def batch(
+ self,
+ inputs: list[RouterInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ keys = [input_["key"] for input_ in inputs]
+ actual_inputs = [input_["input"] for input_ in inputs]
+ if any(key not in self.runnables for key in keys):
+ msg = "One or more keys do not have a corresponding runnable"
+ raise ValueError(msg)
+
+ def invoke(
+ runnable: Runnable[Input, Output], input_: Input, config: RunnableConfig
+ ) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return runnable.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return runnable.invoke(input_, config, **kwargs)
+
+ runnables = [self.runnables[key] for key in keys]
+ configs = get_config_list(config, len(inputs))
+ with get_executor_for_config(configs[0]) as executor:
+ return cast(
+ "list[Output]",
+ list(executor.map(invoke, runnables, actual_inputs, configs)),
+ )
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[RouterInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ keys = [input_["key"] for input_ in inputs]
+ actual_inputs = [input_["input"] for input_ in inputs]
+ if any(key not in self.runnables for key in keys):
+ msg = "One or more keys do not have a corresponding runnable"
+ raise ValueError(msg)
+
+ async def ainvoke(
+ runnable: Runnable[Input, Output], input_: Input, config: RunnableConfig
+ ) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return await runnable.ainvoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await runnable.ainvoke(input_, config, **kwargs)
+
+ runnables = [self.runnables[key] for key in keys]
+ configs = get_config_list(config, len(inputs))
+ return await gather_with_concurrency(
+ configs[0].get("max_concurrency"),
+ *map(ainvoke, runnables, actual_inputs, configs),
+ )
+
+ @override
+ def stream(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ yield from runnable.stream(actual_input, config)
+
+ @override
+ async def astream(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ async for output in runnable.astream(actual_input, config):
+ yield output
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/schema.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..29bbcd2ceee47c773dfa6a02c16589f2878aa38c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/schema.py
@@ -0,0 +1,188 @@
+"""Module contains typedefs that are used with `Runnable` objects."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal
+
+from typing_extensions import NotRequired, TypedDict
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+class EventData(TypedDict, total=False):
+ """Data associated with a streaming event."""
+
+ input: Any
+ """The input passed to the `Runnable` that generated the event.
+
+ Inputs will sometimes be available at the *START* of the `Runnable`, and
+ sometimes at the *END* of the `Runnable`.
+
+ If a `Runnable` is able to stream its inputs, then its input by definition
+ won't be known until the *END* of the `Runnable` when it has finished streaming
+ its inputs.
+ """
+ error: NotRequired[BaseException]
+ """The error that occurred during the execution of the `Runnable`.
+
+ This field is only available if the `Runnable` raised an exception.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+ """
+ output: Any
+ """The output of the `Runnable` that generated the event.
+
+ Outputs will only be available at the *END* of the `Runnable`.
+
+ For most `Runnable` objects, this field can be inferred from the `chunk` field,
+ though there might be some exceptions for special a cased `Runnable` (e.g., like
+ chat models), which may return more information.
+ """
+ chunk: Any
+ """A streaming chunk from the output that generated the event.
+
+ chunks support addition in general, and adding them up should result
+ in the output of the `Runnable` that generated the event.
+ """
+ tool_call_id: NotRequired[str | None]
+ """The tool call ID associated with the tool execution.
+
+ This field is available for the `on_tool_error` event and can be used to
+ link errors to specific tool calls in stateless agent implementations.
+ """
+
+
+class BaseStreamEvent(TypedDict):
+ """Streaming event.
+
+ Schema of a streaming event which is produced from the `astream_events` method.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ async def reverse(s: str) -> str:
+ return s[::-1]
+
+
+ chain = RunnableLambda(func=reverse)
+
+ events = [event async for event in chain.astream_events("hello")]
+
+ # Will produce the following events
+ # (where some fields have been omitted for brevity):
+ [
+ {
+ "data": {"input": "hello"},
+ "event": "on_chain_start",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"chunk": "olleh"},
+ "event": "on_chain_stream",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"output": "olleh"},
+ "event": "on_chain_end",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ ]
+ ```
+ """
+
+ event: str
+ """Event names are of the format: `on_[runnable_type]_(start|stream|end)`.
+
+ Runnable types are one of:
+
+ - **llm** - used by non chat models
+ - **chat_model** - used by chat models
+ - **prompt** -- e.g., `ChatPromptTemplate`
+ - **tool** -- from tools defined via `@tool` decorator or inheriting
+ from `Tool`/`BaseTool`
+ - **chain** - most `Runnable` objects are of this type
+
+ Further, the events are categorized as one of:
+
+ - **start** - when the `Runnable` starts
+ - **stream** - when the `Runnable` is streaming
+ - **end* - when the `Runnable` ends
+
+ start, stream and end are associated with slightly different `data` payload.
+
+ Please see the documentation for `EventData` for more details.
+ """
+ run_id: str
+ """An randomly generated ID to keep track of the execution of the given `Runnable`.
+
+ Each child `Runnable` that gets invoked as part of the execution of a parent
+ `Runnable` is assigned its own unique ID.
+ """
+ tags: NotRequired[list[str]]
+ """Tags associated with the `Runnable` that generated this event.
+
+ Tags are always inherited from parent `Runnable` objects.
+
+ Tags can either be bound to a `Runnable` using `.with_config({"tags": ["hello"]})`
+ or passed at run time using `.astream_events(..., {"tags": ["hello"]})`.
+ """
+ metadata: NotRequired[dict[str, Any]]
+ """Metadata associated with the `Runnable` that generated this event.
+
+ Metadata can either be bound to a `Runnable` using
+
+ `.with_config({"metadata": { "foo": "bar" }})`
+
+ or passed at run time using
+
+ `.astream_events(..., {"metadata": {"foo": "bar"}})`.
+ """
+
+ parent_ids: Sequence[str]
+ """A list of the parent IDs associated with this event.
+
+ Root Events will have an empty list.
+
+ For example, if a `Runnable` A calls `Runnable` B, then the event generated by
+ `Runnable` B will have `Runnable` A's ID in the `parent_ids` field.
+
+ The order of the parent IDs is from the root parent to the immediate parent.
+
+ Only supported as of v2 of the astream events API. v1 will return an empty list.
+ """
+
+
+class StandardStreamEvent(BaseStreamEvent):
+ """A standard stream event that follows LangChain convention for event data."""
+
+ data: EventData
+ """Event data.
+
+ The contents of the event data depend on the event type.
+ """
+ name: str
+ """The name of the `Runnable` that generated the event."""
+
+
+class CustomStreamEvent(BaseStreamEvent):
+ """Custom stream event created by the user."""
+
+ # Overwrite the event field to be more specific.
+ event: Literal["on_custom_event"] # type: ignore[misc]
+ """The event type."""
+ name: str
+ """User defined name for the event."""
+ data: Any
+ """The data associated with the event. Free form and can be anything."""
+
+
+StreamEvent = StandardStreamEvent | CustomStreamEvent
diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/utils.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e46251a2070c7c4757d6ab0f83007f81bc12e2ef
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/utils.py
@@ -0,0 +1,779 @@
+"""Utility code for `Runnable` objects."""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import inspect
+import sys
+import textwrap
+
+# Cannot move to TYPE_CHECKING as Mapping and Sequence are needed at runtime by
+# RunnableConfigurableFields.
+from collections.abc import Mapping, Sequence # noqa: TC003
+from functools import lru_cache
+from inspect import signature
+from itertools import groupby
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ NamedTuple,
+ Protocol,
+ TypeGuard,
+ TypeVar,
+)
+
+from typing_extensions import override
+
+# Re-export create-model for backwards compatibility
+from langchain_core.utils.pydantic import create_model # noqa: F401
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ AsyncIterable,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Coroutine,
+ Iterable,
+ )
+ from contextvars import Context
+
+ from langchain_core.runnables.schema import StreamEvent
+
+Input = TypeVar("Input", contravariant=True) # noqa: PLC0105
+# Output type should implement __concat__, as eg str, list, dict do
+Output = TypeVar("Output", covariant=True) # noqa: PLC0105
+
+
+async def gated_coro(semaphore: asyncio.Semaphore, coro: Coroutine) -> Any:
+ """Run a coroutine with a semaphore.
+
+ Args:
+ semaphore: The semaphore to use.
+ coro: The coroutine to run.
+
+ Returns:
+ The result of the coroutine.
+ """
+ async with semaphore:
+ return await coro
+
+
+async def gather_with_concurrency(n: int | None, *coros: Coroutine) -> list:
+ """Gather coroutines with a limit on the number of concurrent coroutines.
+
+ Args:
+ n: The number of coroutines to run concurrently.
+ *coros: The coroutines to run.
+
+ Returns:
+ The results of the coroutines.
+ """
+ if n is None:
+ return await asyncio.gather(*coros)
+
+ semaphore = asyncio.Semaphore(n)
+
+ return await asyncio.gather(*(gated_coro(semaphore, c) for c in coros))
+
+
+def accepts_run_manager(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a run_manager argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a run_manager argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("run_manager") is not None
+ except ValueError:
+ return False
+
+
+def accepts_config(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a config argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a config argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("config") is not None
+ except ValueError:
+ return False
+
+
+def accepts_context(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a context argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a context argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("context") is not None
+ except ValueError:
+ return False
+
+
+def asyncio_accepts_context() -> bool:
+ """Check if asyncio.create_task accepts a `context` arg.
+
+ Returns:
+ True if `asyncio.create_task` accepts a context argument, `False` otherwise.
+ """
+ return sys.version_info >= (3, 11)
+
+
+_T = TypeVar("_T")
+
+
+def coro_with_context(
+ coro: Awaitable[_T], context: Context, *, create_task: bool = False
+) -> Awaitable[_T]:
+ """Await a coroutine with a context.
+
+ Args:
+ coro: The coroutine to await.
+ context: The context to use.
+ create_task: Whether to create a task.
+
+ Returns:
+ The coroutine with the context.
+ """
+ if asyncio_accepts_context():
+ return asyncio.create_task(coro, context=context) # type: ignore[arg-type,call-arg,unused-ignore]
+ if create_task:
+ return asyncio.create_task(coro) # type: ignore[arg-type]
+ return coro
+
+
+class IsLocalDict(ast.NodeVisitor):
+ """Check if a name is a local dict."""
+
+ def __init__(self, name: str, keys: set[str]) -> None:
+ """Initialize the visitor.
+
+ Args:
+ name: The name to check.
+ keys: The keys to populate.
+ """
+ self.name = name
+ self.keys = keys
+
+ @override
+ def visit_Subscript(self, node: ast.Subscript) -> None:
+ """Visit a subscript node.
+
+ Args:
+ node: The node to visit.
+ """
+ if (
+ isinstance(node.ctx, ast.Load)
+ and isinstance(node.value, ast.Name)
+ and node.value.id == self.name
+ and isinstance(node.slice, ast.Constant)
+ and isinstance(node.slice.value, str)
+ ):
+ # we've found a subscript access on the name we're looking for
+ self.keys.add(node.slice.value)
+
+ @override
+ def visit_Call(self, node: ast.Call) -> None:
+ """Visit a call node.
+
+ Args:
+ node: The node to visit.
+ """
+ if (
+ isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == self.name
+ and node.func.attr == "get"
+ and len(node.args) in {1, 2}
+ and isinstance(node.args[0], ast.Constant)
+ and isinstance(node.args[0].value, str)
+ ):
+ # we've found a .get() call on the name we're looking for
+ self.keys.add(node.args[0].value)
+
+
+class IsFunctionArgDict(ast.NodeVisitor):
+ """Check if the first argument of a function is a dict."""
+
+ def __init__(self) -> None:
+ """Create a IsFunctionArgDict visitor."""
+ self.keys: set[str] = set()
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node.body)
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node)
+
+
+class NonLocals(ast.NodeVisitor):
+ """Get nonlocal variables accessed."""
+
+ def __init__(self) -> None:
+ """Create a NonLocals visitor."""
+ self.loads: set[str] = set()
+ self.stores: set[str] = set()
+
+ @override
+ def visit_Name(self, node: ast.Name) -> None:
+ """Visit a name node.
+
+ Args:
+ node: The node to visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ self.loads.add(node.id)
+ elif isinstance(node.ctx, ast.Store):
+ self.stores.add(node.id)
+
+ @override
+ def visit_Attribute(self, node: ast.Attribute) -> None:
+ """Visit an attribute node.
+
+ Args:
+ node: The node to visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ parent = node.value
+ attr_expr = node.attr
+ while isinstance(parent, ast.Attribute):
+ attr_expr = parent.attr + "." + attr_expr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+ self.loads.discard(parent.id)
+ elif isinstance(parent, ast.Call):
+ if isinstance(parent.func, ast.Name):
+ self.loads.add(parent.func.id)
+ else:
+ parent = parent.func
+ attr_expr = ""
+ while isinstance(parent, ast.Attribute):
+ if attr_expr:
+ attr_expr = parent.attr + "." + attr_expr
+ else:
+ attr_expr = parent.attr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+
+
+class FunctionNonLocals(ast.NodeVisitor):
+ """Get the nonlocal variables accessed of a function."""
+
+ def __init__(self) -> None:
+ """Create a FunctionNonLocals visitor."""
+ self.nonlocals: set[str] = set()
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+
+class GetLambdaSource(ast.NodeVisitor):
+ """Get the source code of a lambda function."""
+
+ def __init__(self) -> None:
+ """Initialize the visitor."""
+ self.source: str | None = None
+ self.count = 0
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ self.count += 1
+ if hasattr(ast, "unparse"):
+ self.source = ast.unparse(node)
+
+
+def get_function_first_arg_dict_keys(func: Callable) -> list[str] | None:
+ """Get the keys of the first argument of a function if it is a dict.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The keys of the first argument if it is a dict, None otherwise.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = IsFunctionArgDict()
+ visitor.visit(tree)
+ return sorted(visitor.keys) if visitor.keys else None
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return None
+
+
+def get_lambda_source(func: Callable) -> str | None:
+ """Get the source code of a lambda function.
+
+ Args:
+ func: a Callable that can be a lambda function.
+
+ Returns:
+ the source code of the lambda function.
+ """
+ try:
+ name = func.__name__ if func.__name__ != "" else None
+ except AttributeError:
+ name = None
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = GetLambdaSource()
+ visitor.visit(tree)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return name
+ return visitor.source if visitor.count == 1 else name
+
+
+@lru_cache(maxsize=256)
+def get_function_nonlocals(func: Callable) -> list[Any]:
+ """Get the nonlocal variables accessed by a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The nonlocal variables accessed by the function.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = FunctionNonLocals()
+ visitor.visit(tree)
+ values: list[Any] = []
+ closure = (
+ inspect.getclosurevars(func.__wrapped__)
+ if hasattr(func, "__wrapped__") and callable(func.__wrapped__)
+ else inspect.getclosurevars(func)
+ )
+ candidates = {**closure.globals, **closure.nonlocals}
+ for k, v in candidates.items():
+ if k in visitor.nonlocals:
+ values.append(v)
+ for kk in visitor.nonlocals:
+ if "." in kk and kk.startswith(k):
+ vv = v
+ for part in kk.split(".")[1:]:
+ if vv is None:
+ break
+ try:
+ vv = getattr(vv, part)
+ except AttributeError:
+ break
+ else:
+ values.append(vv)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return []
+
+ return values
+
+
+def indent_lines_after_first(text: str, prefix: str) -> str:
+ """Indent all lines of text after the first line.
+
+ Args:
+ text: The text to indent.
+ prefix: Used to determine the number of spaces to indent.
+
+ Returns:
+ The indented text.
+ """
+ n_spaces = len(prefix)
+ spaces = " " * n_spaces
+ lines = text.splitlines()
+ return "\n".join([lines[0]] + [spaces + line for line in lines[1:]])
+
+
+class AddableDict(dict[str, Any]):
+ """Dictionary that can be added to another dictionary."""
+
+ def __add__(self, other: AddableDict) -> AddableDict:
+ """Add a dictionary to this dictionary.
+
+ Args:
+ other: The other dictionary to add.
+
+ Returns:
+ A dictionary that is the result of adding the two dictionaries.
+ """
+ chunk = AddableDict(self)
+ for key in other:
+ if key not in chunk or chunk[key] is None:
+ chunk[key] = other[key]
+ elif other[key] is not None:
+ try:
+ added = chunk[key] + other[key]
+ except TypeError:
+ added = other[key]
+ chunk[key] = added
+ return chunk
+
+ def __radd__(self, other: AddableDict) -> AddableDict:
+ """Add this dictionary to another dictionary.
+
+ Args:
+ other: The other dictionary to be added to.
+
+ Returns:
+ A dictionary that is the result of adding the two dictionaries.
+ """
+ chunk = AddableDict(other)
+ for key in self:
+ if key not in chunk or chunk[key] is None:
+ chunk[key] = self[key]
+ elif self[key] is not None:
+ try:
+ added = chunk[key] + self[key]
+ except TypeError:
+ added = self[key]
+ chunk[key] = added
+ return chunk
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+_T_contra = TypeVar("_T_contra", contravariant=True)
+
+
+class SupportsAdd(Protocol[_T_contra, _T_co]):
+ """Protocol for objects that support addition."""
+
+ def __add__(self, x: _T_contra, /) -> _T_co:
+ """Add the object to another object."""
+
+
+Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any])
+
+
+def add(addables: Iterable[Addable]) -> Addable | None:
+ """Add a sequence of addable objects together.
+
+ Args:
+ addables: The addable objects to add.
+
+ Returns:
+ The result of adding the addable objects.
+ """
+ final: Addable | None = None
+ for chunk in addables:
+ final = chunk if final is None else final + chunk
+ return final
+
+
+async def aadd(addables: AsyncIterable[Addable]) -> Addable | None:
+ """Asynchronously add a sequence of addable objects together.
+
+ Args:
+ addables: The addable objects to add.
+
+ Returns:
+ The result of adding the addable objects.
+ """
+ final: Addable | None = None
+ async for chunk in addables:
+ final = chunk if final is None else final + chunk
+ return final
+
+
+class ConfigurableField(NamedTuple):
+ """Field that can be configured by the user."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ annotation: Any | None = None
+ """The annotation of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, self.annotation))
+
+
+class ConfigurableFieldSingleOption(NamedTuple):
+ """Field that can be configured by the user with a default value."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ options: Mapping[str, Any]
+ """The options for the field."""
+
+ default: str
+ """The default value for the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, tuple(self.options.keys()), self.default))
+
+
+class ConfigurableFieldMultiOption(NamedTuple):
+ """Field that can be configured by the user with multiple default values."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ options: Mapping[str, Any]
+ """The options for the field."""
+
+ default: Sequence[str]
+ """The default values for the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, tuple(self.options.keys()), tuple(self.default)))
+
+
+AnyConfigurableField = (
+ ConfigurableField | ConfigurableFieldSingleOption | ConfigurableFieldMultiOption
+)
+
+
+class ConfigurableFieldSpec(NamedTuple):
+ """Field that can be configured by the user. It is a specification of a field."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ annotation: Any
+ """The annotation of the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ default: Any = None
+ """The default value for the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ dependencies: list[str] | None = None
+ """The dependencies of the field. """
+
+
+def get_unique_config_specs(
+ specs: Iterable[ConfigurableFieldSpec],
+) -> list[ConfigurableFieldSpec]:
+ """Get the unique config specs from a sequence of config specs.
+
+ Args:
+ specs: The config specs.
+
+ Returns:
+ The unique config specs.
+
+ Raises:
+ ValueError: If the runnable sequence contains conflicting config specs.
+ """
+ grouped = groupby(
+ sorted(specs, key=lambda s: (s.id, *(s.dependencies or []))), lambda s: s.id
+ )
+ unique: list[ConfigurableFieldSpec] = []
+ for spec_id, dupes in grouped:
+ first = next(dupes)
+ others = list(dupes)
+ if len(others) == 0 or all(o == first for o in others):
+ unique.append(first)
+ else:
+ msg = (
+ "RunnableSequence contains conflicting config specs"
+ f"for {spec_id}: {[first, *others]}"
+ )
+ raise ValueError(msg)
+ return unique
+
+
+class _RootEventFilter:
+ def __init__(
+ self,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ ) -> None:
+ """Utility to filter the root event in the astream_events implementation.
+
+ This is simply binding the arguments to the namespace to make save on
+ a bit of typing in the astream_events implementation.
+ """
+ self.include_names = include_names
+ self.include_types = include_types
+ self.include_tags = include_tags
+ self.exclude_names = exclude_names
+ self.exclude_types = exclude_types
+ self.exclude_tags = exclude_tags
+
+ def include_event(self, event: StreamEvent, root_type: str) -> bool:
+ """Determine whether to include an event."""
+ if (
+ self.include_names is None
+ and self.include_types is None
+ and self.include_tags is None
+ ):
+ include = True
+ else:
+ include = False
+
+ event_tags = event.get("tags") or []
+
+ if self.include_names is not None:
+ include = include or event["name"] in self.include_names
+ if self.include_types is not None:
+ include = include or root_type in self.include_types
+ if self.include_tags is not None:
+ include = include or any(tag in self.include_tags for tag in event_tags)
+
+ if self.exclude_names is not None:
+ include = include and event["name"] not in self.exclude_names
+ if self.exclude_types is not None:
+ include = include and root_type not in self.exclude_types
+ if self.exclude_tags is not None:
+ include = include and all(
+ tag not in self.exclude_tags for tag in event_tags
+ )
+
+ return include
+
+
+def is_async_generator(
+ func: Any,
+) -> TypeGuard[Callable[..., AsyncIterator]]:
+ """Check if a function is an async generator.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ `True` if the function is an async generator, `False` otherwise.
+ """
+ return inspect.isasyncgenfunction(func) or (
+ hasattr(func, "__call__") # noqa: B004
+ and inspect.isasyncgenfunction(func.__call__)
+ )
+
+
+def is_async_callable(
+ func: Any,
+) -> TypeGuard[Callable[..., Awaitable]]:
+ """Check if a function is async.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ `True` if the function is async, `False` otherwise.
+ """
+ return asyncio.iscoroutinefunction(func) or (
+ hasattr(func, "__call__") # noqa: B004
+ and asyncio.iscoroutinefunction(func.__call__)
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..445ca9909096971984b865f99050515c7531b611
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/__init__.py
@@ -0,0 +1,95 @@
+"""Tools are classes that an Agent uses to interact with the world.
+
+Each tool has a description. Agent uses the description to choose the right tool for the
+job.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.tools.base import (
+ FILTERED_ARGS,
+ ArgsSchema,
+ BaseTool,
+ BaseToolkit,
+ InjectedToolArg,
+ InjectedToolCallId,
+ SchemaAnnotationError,
+ ToolException,
+ _get_runnable_config_param,
+ create_schema_from_function,
+ )
+ from langchain_core.tools.convert import (
+ convert_runnable_to_tool,
+ tool,
+ )
+ from langchain_core.tools.render import (
+ ToolsRenderer,
+ render_text_description,
+ render_text_description_and_args,
+ )
+ from langchain_core.tools.retriever import (
+ RetrieverInput,
+ create_retriever_tool,
+ )
+ from langchain_core.tools.simple import Tool
+ from langchain_core.tools.structured import StructuredTool
+
+__all__ = (
+ "FILTERED_ARGS",
+ "ArgsSchema",
+ "BaseTool",
+ "BaseToolkit",
+ "InjectedToolArg",
+ "InjectedToolCallId",
+ "RetrieverInput",
+ "SchemaAnnotationError",
+ "StructuredTool",
+ "Tool",
+ "ToolException",
+ "ToolsRenderer",
+ "_get_runnable_config_param",
+ "convert_runnable_to_tool",
+ "create_retriever_tool",
+ "create_schema_from_function",
+ "render_text_description",
+ "render_text_description_and_args",
+ "tool",
+)
+
+_dynamic_imports = {
+ "FILTERED_ARGS": "base",
+ "ArgsSchema": "base",
+ "BaseTool": "base",
+ "BaseToolkit": "base",
+ "InjectedToolArg": "base",
+ "InjectedToolCallId": "base",
+ "SchemaAnnotationError": "base",
+ "ToolException": "base",
+ "_get_runnable_config_param": "base",
+ "create_schema_from_function": "base",
+ "convert_runnable_to_tool": "convert",
+ "tool": "convert",
+ "ToolsRenderer": "render",
+ "render_text_description": "render",
+ "render_text_description_and_args": "render",
+ "RetrieverInput": "retriever",
+ "create_retriever_tool": "retriever",
+ "Tool": "simple",
+ "StructuredTool": "structured",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81a993685e2d580f874e762089cba6dea1ba35eb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5feab5b1276da9a0c4a5a2d558a7a99aacb9e73
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/convert.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/convert.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3b5adb154090d2893b5c0966b984fcfd83554b4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/convert.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/render.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/render.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e5692c82313a2a803bc36d62ff4c84500ead4ae
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/render.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/retriever.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/retriever.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79118f966529407fe2750c299180315c5e71f5aa
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/retriever.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/simple.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/simple.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cef8f6045756366c31328e2d41cec390ff186111
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/simple.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/structured.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/structured.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d0da811d2842cc73b4b70c7b005e88a50283db5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tools/__pycache__/structured.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/base.py b/python/user_packages/Python313/site-packages/langchain_core/tools/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f069771f39e16930caaba9c45ad6f248e8256c5b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/base.py
@@ -0,0 +1,1593 @@
+"""Base classes and utilities for LangChain tools."""
+
+from __future__ import annotations
+
+import functools
+import inspect
+import json
+import logging
+import typing
+import warnings
+from abc import ABC, abstractmethod
+from collections.abc import Callable # noqa: TC003
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+ TypeVar,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+import typing_extensions
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ PydanticDeprecationWarning,
+ SkipValidation,
+ ValidationError,
+ validate_arguments,
+)
+from pydantic.fields import FieldInfo
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import ValidationError as ValidationErrorV1
+from pydantic.v1 import validate_arguments as validate_arguments_v1
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ CallbackManager,
+ Callbacks,
+)
+from langchain_core.messages.tool import ToolCall, ToolMessage, ToolOutputMixin
+from langchain_core.runnables import (
+ RunnableConfig,
+ RunnableSerializable,
+ ensure_config,
+ patch_config,
+ run_in_executor,
+)
+from langchain_core.runnables.config import set_config_context
+from langchain_core.runnables.utils import coro_with_context
+from langchain_core.utils.function_calling import (
+ _parse_google_docstring,
+ _py_38_safe_origin,
+)
+from langchain_core.utils.pydantic import (
+ TypeBaseModel,
+ _create_subset_model,
+ get_fields,
+ is_basemodel_subclass,
+ is_pydantic_v1_subclass,
+ is_pydantic_v2_subclass,
+)
+
+if TYPE_CHECKING:
+ import uuid
+ from collections.abc import Sequence
+
+FILTERED_ARGS = ("run_manager", "callbacks")
+TOOL_MESSAGE_BLOCK_TYPES = (
+ "text",
+ "image_url",
+ "image",
+ "json",
+ "search_result",
+ "custom_tool_call_output",
+ "document",
+ "file",
+)
+
+_logger = logging.getLogger(__name__)
+
+
+class SchemaAnnotationError(TypeError):
+ """Raised when `args_schema` is missing or has an incorrect type annotation."""
+
+
+def _is_annotated_type(typ: type[Any]) -> bool:
+ """Check if a type is an `Annotated` type.
+
+ Args:
+ typ: The type to check.
+
+ Returns:
+ `True` if the type is an `Annotated` type, `False` otherwise.
+ """
+ return get_origin(typ) in {typing.Annotated, typing_extensions.Annotated}
+
+
+def _get_annotation_description(arg_type: type) -> str | None:
+ """Extract description from an `Annotated` type.
+
+ Checks for string annotations and `FieldInfo` objects with descriptions.
+
+ Args:
+ arg_type: The type to extract description from.
+
+ Returns:
+ The description string if found, `None` otherwise.
+ """
+ if _is_annotated_type(arg_type):
+ annotated_args = get_args(arg_type)
+ for annotation in annotated_args[1:]:
+ if isinstance(annotation, str):
+ return annotation
+ if isinstance(annotation, FieldInfo) and annotation.description:
+ return annotation.description
+ return None
+
+
+def _get_filtered_args(
+ inferred_model: type[BaseModel],
+ func: Callable,
+ *,
+ filter_args: Sequence[str],
+ include_injected: bool = True,
+) -> dict:
+ """Get filtered arguments from a function's signature.
+
+ Args:
+ inferred_model: The Pydantic model inferred from the function.
+ func: The function to extract arguments from.
+ filter_args: Arguments to exclude from the result.
+ include_injected: Whether to include injected arguments.
+
+ Returns:
+ Dictionary of filtered arguments with their schema definitions.
+ """
+ schema = inferred_model.model_json_schema()["properties"]
+ valid_keys = signature(func).parameters
+ return {
+ k: schema[k]
+ for i, (k, param) in enumerate(valid_keys.items())
+ if k not in filter_args
+ and (i > 0 or param.name not in {"self", "cls"})
+ and (include_injected or not _is_injected_arg_type(param.annotation))
+ }
+
+
+def _parse_python_function_docstring(
+ function: Callable, annotations: dict, *, error_on_invalid_docstring: bool = False
+) -> tuple[str, dict]:
+ """Parse function and argument descriptions from a docstring.
+
+ Assumes the function docstring follows Google Python style guide.
+
+ Args:
+ function: The function to parse the docstring from.
+ annotations: Type annotations for the function parameters.
+ error_on_invalid_docstring: Whether to raise an error on invalid docstring.
+
+ Returns:
+ A tuple containing the function description and argument descriptions.
+ """
+ docstring = inspect.getdoc(function)
+ return _parse_google_docstring(
+ docstring,
+ list(annotations),
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ )
+
+
+def _validate_docstring_args_against_annotations(
+ arg_descriptions: dict, annotations: dict
+) -> None:
+ """Validate that docstring arguments match function annotations.
+
+ Args:
+ arg_descriptions: Arguments described in the docstring.
+ annotations: Type annotations from the function signature.
+
+ Raises:
+ ValueError: If a docstring argument is not found in function signature.
+ """
+ for docstring_arg in arg_descriptions:
+ if docstring_arg not in annotations:
+ msg = f"Arg {docstring_arg} in docstring not found in function signature."
+ raise ValueError(msg)
+
+
+def _infer_arg_descriptions(
+ fn: Callable,
+ *,
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+) -> tuple[str, dict]:
+ """Infer argument descriptions from function docstring and annotations.
+
+ Args:
+ fn: The function to infer descriptions from.
+ parse_docstring: Whether to parse the docstring for descriptions.
+ error_on_invalid_docstring: Whether to raise error on invalid docstring.
+
+ Returns:
+ A tuple containing the function description and argument descriptions.
+ """
+ annotations = typing.get_type_hints(fn, include_extras=True)
+ if parse_docstring:
+ description, arg_descriptions = _parse_python_function_docstring(
+ fn, annotations, error_on_invalid_docstring=error_on_invalid_docstring
+ )
+ else:
+ description = inspect.getdoc(fn) or ""
+ arg_descriptions = {}
+ if parse_docstring:
+ _validate_docstring_args_against_annotations(arg_descriptions, annotations)
+ for arg, arg_type in annotations.items():
+ if arg in arg_descriptions:
+ continue
+ if desc := _get_annotation_description(arg_type):
+ arg_descriptions[arg] = desc
+ return description, arg_descriptions
+
+
+def _is_pydantic_annotation(annotation: Any, pydantic_version: str = "v2") -> bool:
+ """Check if a type annotation is a Pydantic model.
+
+ Args:
+ annotation: The type annotation to check.
+ pydantic_version: The Pydantic version to check against (`'v1'` or `'v2'`).
+
+ Returns:
+ `True` if the annotation is a Pydantic model, `False` otherwise.
+ """
+ base_model_class = BaseModelV1 if pydantic_version == "v1" else BaseModel
+ try:
+ return issubclass(annotation, base_model_class)
+ except TypeError:
+ return False
+
+
+def _function_annotations_are_pydantic_v1(
+ signature: inspect.Signature, func: Callable
+) -> bool:
+ """Check if all Pydantic annotations in a function are from v1.
+
+ Args:
+ signature: The function signature to check.
+ func: The function being checked.
+
+ Returns:
+ True if all Pydantic annotations are from v1, `False` otherwise.
+
+ Raises:
+ NotImplementedError: If the function contains mixed v1 and v2 annotations.
+ """
+ any_v1_annotations = any(
+ _is_pydantic_annotation(parameter.annotation, pydantic_version="v1")
+ for parameter in signature.parameters.values()
+ )
+ any_v2_annotations = any(
+ _is_pydantic_annotation(parameter.annotation, pydantic_version="v2")
+ for parameter in signature.parameters.values()
+ )
+ if any_v1_annotations and any_v2_annotations:
+ msg = (
+ f"Function {func} contains a mix of Pydantic v1 and v2 annotations. "
+ "Only one version of Pydantic annotations per function is supported."
+ )
+ raise NotImplementedError(msg)
+ return any_v1_annotations and not any_v2_annotations
+
+
+class _SchemaConfig:
+ """Configuration for Pydantic models generated from function signatures."""
+
+ extra: str = "forbid"
+ """Whether to allow extra fields in the model."""
+
+ arbitrary_types_allowed: bool = True
+ """Whether to allow arbitrary types in the model."""
+
+
+def create_schema_from_function(
+ model_name: str,
+ func: Callable,
+ *,
+ filter_args: Sequence[str] | None = None,
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+ include_injected: bool = True,
+) -> type[BaseModel]:
+ """Create a Pydantic schema from a function's signature.
+
+ Args:
+ model_name: Name to assign to the generated Pydantic schema.
+ func: Function to generate the schema from.
+ filter_args: Optional list of arguments to exclude from the schema.
+
+ Defaults to `FILTERED_ARGS`.
+ parse_docstring: Whether to parse the function's docstring for descriptions
+ for each argument.
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ include_injected: Whether to include injected arguments in the schema.
+
+ Defaults to `True`, since we want to include them in the schema when
+ *validating* tool inputs.
+
+ Returns:
+ A Pydantic model with the same arguments as the function.
+ """
+ sig = inspect.signature(func)
+
+ if _function_annotations_are_pydantic_v1(sig, func):
+ validated = validate_arguments_v1(func, config=_SchemaConfig) # type: ignore[call-overload]
+ else:
+ # https://docs.pydantic.dev/latest/usage/validation_decorator/
+ with warnings.catch_warnings():
+ # We are using deprecated functionality here.
+ # This code should be re-written to simply construct a Pydantic model
+ # using inspect.signature and create_model.
+ warnings.simplefilter("ignore", category=PydanticDeprecationWarning)
+ validated = validate_arguments(func, config=_SchemaConfig) # type: ignore[operator]
+
+ # Let's ignore `self` and `cls` arguments for class and instance methods
+ # If qualified name has a ".", then it likely belongs in a class namespace
+ in_class = bool(func.__qualname__ and "." in func.__qualname__)
+
+ has_args = False
+ has_kwargs = False
+
+ for param in sig.parameters.values():
+ if param.kind == param.VAR_POSITIONAL:
+ has_args = True
+ elif param.kind == param.VAR_KEYWORD:
+ has_kwargs = True
+
+ inferred_model = validated.model
+
+ if filter_args:
+ filter_args_ = filter_args
+ else:
+ # Handle classmethods and instance methods
+ existing_params: list[str] = list(sig.parameters.keys())
+ if existing_params and existing_params[0] in {"self", "cls"} and in_class:
+ filter_args_ = [existing_params[0], *list(FILTERED_ARGS)]
+ else:
+ filter_args_ = list(FILTERED_ARGS)
+
+ for existing_param in existing_params:
+ if not include_injected and _is_injected_arg_type(
+ sig.parameters[existing_param].annotation
+ ):
+ filter_args_.append(existing_param)
+
+ description, arg_descriptions = _infer_arg_descriptions(
+ func,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ )
+ # Pydantic adds placeholder virtual fields we need to strip
+ valid_properties = []
+ for field in get_fields(inferred_model):
+ if not has_args and field == "args":
+ continue
+ if not has_kwargs and field == "kwargs":
+ continue
+
+ if field == "v__duplicate_kwargs": # Internal pydantic field
+ continue
+
+ if field not in filter_args_:
+ valid_properties.append(field)
+
+ return _create_subset_model(
+ model_name,
+ inferred_model,
+ list(valid_properties),
+ descriptions=arg_descriptions,
+ fn_description=description,
+ )
+
+
+class ToolException(Exception): # noqa: N818
+ """Exception thrown when a tool execution error occurs.
+
+ This exception allows tools to signal errors without stopping the agent.
+
+ The error is handled according to the tool's `handle_tool_error` setting, and the
+ result is returned as an observation to the agent.
+ """
+
+
+ArgsSchema = TypeBaseModel | dict[str, Any]
+
+_EMPTY_SET: frozenset[str] = frozenset()
+
+
+class BaseTool(RunnableSerializable[str | dict | ToolCall, Any]):
+ """Base class for all LangChain tools.
+
+ This abstract class defines the interface that all LangChain tools must implement.
+
+ Tools are components that can be called by agents to perform specific actions.
+ """
+
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ """Validate the tool class definition during subclass creation.
+
+ Args:
+ **kwargs: Additional keyword arguments passed to the parent class.
+
+ Raises:
+ SchemaAnnotationError: If `args_schema` has incorrect type annotation.
+ """
+ super().__init_subclass__(**kwargs)
+
+ args_schema_type = cls.__annotations__.get("args_schema", None)
+
+ if args_schema_type is not None and args_schema_type == BaseModel:
+ # Throw errors for common mis-annotations.
+ # TODO: Use get_args / get_origin and fully
+ # specify valid annotations.
+ typehint_mandate = """
+class ChildTool(BaseTool):
+ ...
+ args_schema: Type[BaseModel] = SchemaClass
+ ..."""
+ name = cls.__name__
+ msg = (
+ f"Tool definition for {name} must include valid type annotations"
+ f" for argument 'args_schema' to behave as expected.\n"
+ f"Expected annotation of 'Type[BaseModel]'"
+ f" but got '{args_schema_type}'.\n"
+ f"Expected class looks like:\n"
+ f"{typehint_mandate}"
+ )
+ raise SchemaAnnotationError(msg)
+
+ name: str
+ """The unique name of the tool that clearly communicates its purpose."""
+
+ description: str
+ """Used to tell the model how/when/why to use the tool.
+
+ You can provide few-shot examples as a part of the description.
+ """
+
+ args_schema: Annotated[ArgsSchema | None, SkipValidation()] = Field(
+ default=None, description="The tool schema."
+ )
+ """Pydantic model class to validate and parse the tool's input arguments.
+
+ Args schema should be either:
+
+ - A subclass of `pydantic.BaseModel`.
+ - A subclass of `pydantic.v1.BaseModel` if accessing v1 namespace in pydantic 2
+ - A JSON schema dict
+ """
+
+ return_direct: bool = False
+ """Whether to return the tool's output directly.
+
+ Setting this to `True` means that after the tool is called, the `AgentExecutor` will
+ stop looping.
+ """
+
+ verbose: bool = False
+ """Whether to log the tool's progress."""
+
+ callbacks: Callbacks = Field(default=None, exclude=True)
+ """Callbacks to be called during tool execution."""
+
+ tags: list[str] | None = None
+ """Optional list of tags associated with the tool.
+
+ These tags will be associated with each call to this tool,
+ and passed as arguments to the handlers defined in `callbacks`.
+
+ You can use these to, e.g., identify a specific instance of a tool with its use
+ case.
+ """
+
+ metadata: dict[str, Any] | None = None
+ """Optional metadata associated with the tool.
+
+ This metadata will be associated with each call to this tool,
+ and passed as arguments to the handlers defined in `callbacks`.
+
+ You can use these to, e.g., identify a specific instance of a tool with its usecase.
+ """
+
+ handle_tool_error: bool | str | Callable[[ToolException], str] | None = False
+ """Handle the content of the `ToolException` thrown."""
+
+ handle_validation_error: (
+ bool | str | Callable[[ValidationError | ValidationErrorV1], str] | None
+ ) = False
+ """Handle the content of the `ValidationError` thrown."""
+
+ response_format: Literal["content", "content_and_artifact"] = "content"
+ """The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the contents of a
+ `ToolMessage`. If `'content_and_artifact'` then the output is expected to be a
+ two-tuple corresponding to the `(content, artifact)` of a `ToolMessage`.
+ """
+
+ extras: dict[str, Any] | None = None
+ """Optional provider-specific extra fields for the tool.
+
+ This is used to pass provider-specific configuration that doesn't fit into
+ standard tool fields.
+
+ Example:
+ Anthropic-specific fields like [`cache_control`](https://docs.langchain.com/oss/python/integrations/chat/anthropic#prompt-caching),
+ [`defer_loading`](https://docs.langchain.com/oss/python/integrations/chat/anthropic#tool-search),
+ or `input_examples`.
+
+ ```python
+ @tool(extras={"defer_loading": True, "cache_control": {"type": "ephemeral"}})
+ def my_tool(x: str) -> str:
+ return x
+ ```
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize the tool.
+
+ Raises:
+ TypeError: If `args_schema` is not a subclass of pydantic `BaseModel` or
+ `dict`.
+ """
+ if (
+ "args_schema" in kwargs
+ and kwargs["args_schema"] is not None
+ and not is_basemodel_subclass(kwargs["args_schema"])
+ and not isinstance(kwargs["args_schema"], dict)
+ ):
+ msg = (
+ "args_schema must be a subclass of pydantic BaseModel or "
+ f"a JSON schema dict. Got: {kwargs['args_schema']}."
+ )
+ raise TypeError(msg)
+ super().__init__(**kwargs)
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ def is_single_input(self) -> bool:
+ """Check if the tool accepts only a single input argument.
+
+ Returns:
+ `True` if the tool has only one input argument, `False` otherwise.
+ """
+ keys = {k for k in self.args if k != "kwargs"}
+ return len(keys) == 1
+
+ @property
+ def args(self) -> dict:
+ """Get the tool's input arguments schema.
+
+ Returns:
+ `dict` containing the tool's argument properties.
+ """
+ if isinstance(self.args_schema, dict):
+ json_schema = self.args_schema
+ elif self.args_schema and issubclass(self.args_schema, BaseModelV1):
+ json_schema = self.args_schema.schema()
+ else:
+ input_schema = self.tool_call_schema
+ if isinstance(input_schema, dict):
+ json_schema = input_schema
+ else:
+ json_schema = input_schema.model_json_schema()
+ return cast("dict", json_schema["properties"])
+
+ @property
+ def tool_call_schema(self) -> ArgsSchema:
+ """Get the schema for tool calls, excluding injected arguments.
+
+ Returns:
+ The schema that should be used for tool calls from language models.
+ """
+ if isinstance(self.args_schema, dict):
+ if self.description:
+ return {
+ **self.args_schema,
+ "description": self.description,
+ }
+
+ return self.args_schema
+
+ full_schema = self.get_input_schema()
+ fields = []
+ for name, type_ in get_all_basemodel_annotations(full_schema).items():
+ if not _is_injected_arg_type(type_):
+ fields.append(name)
+ return _create_subset_model(
+ self.name, full_schema, fields, fn_description=self.description
+ )
+
+ @functools.cached_property
+ def _injected_args_keys(self) -> frozenset[str]:
+ # Base implementation doesn't manage injected args
+ return _EMPTY_SET
+
+ # --- Runnable ---
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """The tool's input schema.
+
+ Args:
+ config: The configuration for the tool.
+
+ Returns:
+ The input schema for the tool.
+ """
+ if self.args_schema is not None:
+ if isinstance(self.args_schema, dict):
+ return super().get_input_schema(config)
+ return self.args_schema
+ return create_schema_from_function(self.name, self._run)
+
+ @override
+ def invoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ tool_input, kwargs = _prep_run_args(input, config, **kwargs)
+ return self.run(tool_input, **kwargs)
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ tool_input, kwargs = _prep_run_args(input, config, **kwargs)
+ return await self.arun(tool_input, **kwargs)
+
+ # --- Tool ---
+
+ def _parse_input(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> str | dict[str, Any]:
+ """Parse and validate tool input using the args schema.
+
+ Args:
+ tool_input: The raw input to the tool.
+ tool_call_id: The ID of the tool call, if available.
+
+ Returns:
+ The parsed and validated input.
+
+ Raises:
+ ValueError: If `string` input is provided with JSON schema `args_schema`.
+ ValueError: If `InjectedToolCallId` is required but `tool_call_id` is not
+ provided.
+ TypeError: If `args_schema` is not a Pydantic `BaseModel` or dict.
+ """
+ input_args = self.args_schema
+
+ if isinstance(tool_input, str):
+ if input_args is not None:
+ if isinstance(input_args, dict):
+ msg = (
+ "String tool inputs are not allowed when "
+ "using tools with JSON schema args_schema."
+ )
+ raise ValueError(msg)
+ key_ = next(iter(get_fields(input_args).keys()))
+ if issubclass(input_args, BaseModel):
+ input_args.model_validate({key_: tool_input})
+ elif issubclass(input_args, BaseModelV1):
+ input_args.parse_obj({key_: tool_input})
+ else:
+ msg = f"args_schema must be a Pydantic BaseModel, got {input_args}"
+ raise TypeError(msg)
+ return tool_input
+
+ if input_args is not None:
+ if isinstance(input_args, dict):
+ return tool_input
+ if issubclass(input_args, BaseModel):
+ # Check args_schema for InjectedToolCallId
+ for k, v in get_all_basemodel_annotations(input_args).items():
+ if _is_injected_arg_type(v, injected_type=InjectedToolCallId):
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ tool_input[k] = tool_call_id
+ result = input_args.model_validate(tool_input)
+ result_dict = result.model_dump()
+ elif issubclass(input_args, BaseModelV1):
+ # Check args_schema for InjectedToolCallId
+ for k, v in get_all_basemodel_annotations(input_args).items():
+ if _is_injected_arg_type(v, injected_type=InjectedToolCallId):
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ tool_input[k] = tool_call_id
+ result = input_args.parse_obj(tool_input)
+ result_dict = result.dict()
+ else:
+ msg = (
+ f"args_schema must be a Pydantic BaseModel, got {self.args_schema}"
+ )
+ raise NotImplementedError(msg)
+
+ # Include fields from tool_input, plus fields with explicit defaults.
+ # This applies Pydantic defaults (like Field(default=1)) while excluding
+ # synthetic "args"/"kwargs" fields that Pydantic creates for *args/**kwargs.
+ field_info = get_fields(input_args)
+ validated_input = {}
+ for k in result_dict:
+ if k in tool_input:
+ # Field was provided in input - include it (validated)
+ validated_input[k] = getattr(result, k)
+ elif k in field_info and k not in {"args", "kwargs"}:
+ # Check if field has an explicit default defined in the schema.
+ # Exclude "args"/"kwargs" as these are synthetic fields for variadic
+ # parameters that should not be passed as keyword arguments.
+ fi = field_info[k]
+ # Pydantic v2 uses is_required() method, v1 uses required attribute
+ has_default = (
+ not fi.is_required()
+ if hasattr(fi, "is_required")
+ else not getattr(fi, "required", True)
+ )
+ if has_default:
+ validated_input[k] = getattr(result, k)
+
+ for k in self._injected_args_keys:
+ if k in tool_input:
+ validated_input[k] = tool_input[k]
+ elif k == "tool_call_id":
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ validated_input[k] = tool_call_id
+
+ return validated_input
+
+ return tool_input
+
+ @abstractmethod
+ def _run(self, *args: Any, **kwargs: Any) -> Any:
+ """Use the tool.
+
+ Add `run_manager: CallbackManagerForToolRun | None = None` to child
+ implementations to enable tracing.
+
+ Returns:
+ The result of the tool execution.
+ """
+
+ async def _arun(self, *args: Any, **kwargs: Any) -> Any:
+ """Use the tool asynchronously.
+
+ Add `run_manager: AsyncCallbackManagerForToolRun | None = None` to child
+ implementations to enable tracing.
+
+ Returns:
+ The result of the tool execution.
+ """
+ if kwargs.get("run_manager") and signature(self._run).parameters.get(
+ "run_manager"
+ ):
+ kwargs["run_manager"] = kwargs["run_manager"].get_sync()
+ return await run_in_executor(None, self._run, *args, **kwargs)
+
+ def _filter_injected_args(self, tool_input: dict) -> dict:
+ """Filter out injected tool arguments from the input dictionary.
+
+ Injected arguments are those annotated with `InjectedToolArg` or its
+ subclasses, or arguments in `FILTERED_ARGS` like `run_manager` and callbacks.
+
+ Args:
+ tool_input: The tool input dictionary to filter.
+
+ Returns:
+ A filtered dictionary with injected arguments removed.
+ """
+ # Start with filtered args from the constant
+ filtered_keys = set[str](FILTERED_ARGS)
+
+ # Add injected args from function signature (e.g., ToolRuntime parameters)
+ filtered_keys.update(self._injected_args_keys)
+
+ # If we have an args_schema, use it to identify injected args
+ # Skip if args_schema is a dict (JSON Schema) as it's not a Pydantic model
+ if self.args_schema is not None and not isinstance(self.args_schema, dict):
+ try:
+ annotations = get_all_basemodel_annotations(self.args_schema)
+ for field_name, field_type in annotations.items():
+ if _is_injected_arg_type(field_type):
+ filtered_keys.add(field_name)
+ except Exception:
+ # If we can't get annotations, just use FILTERED_ARGS
+ _logger.debug(
+ "Failed to get args_schema annotations for filtering.",
+ exc_info=True,
+ )
+
+ # Filter out the injected keys from tool_input
+ return {k: v for k, v in tool_input.items() if k not in filtered_keys}
+
+ def _to_args_and_kwargs(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> tuple[tuple, dict]:
+ """Convert tool input to positional and keyword arguments.
+
+ Args:
+ tool_input: The input to the tool.
+ tool_call_id: The ID of the tool call, if available.
+
+ Returns:
+ A tuple of `(positional_args, keyword_args)` for the tool.
+
+ Raises:
+ TypeError: If the tool input type is invalid.
+ """
+ if (
+ self.args_schema is not None
+ and isinstance(self.args_schema, type)
+ and is_basemodel_subclass(self.args_schema)
+ and not get_fields(self.args_schema)
+ ):
+ # StructuredTool with no args
+ return (), {}
+ tool_input = self._parse_input(tool_input, tool_call_id)
+ # For backwards compatibility, if run_input is a string,
+ # pass as a positional argument.
+ if isinstance(tool_input, str):
+ return (tool_input,), {}
+ if isinstance(tool_input, dict):
+ # Make a shallow copy of the input to allow downstream code
+ # to modify the root level of the input without affecting the
+ # original input.
+ # This is used by the tool to inject run time information like
+ # the callback manager.
+ return (), tool_input.copy()
+ # This code path is not expected to be reachable.
+ msg = f"Invalid tool input type: {type(tool_input)}"
+ raise TypeError(msg)
+
+ def run(
+ self,
+ tool_input: str | dict[str, Any],
+ verbose: bool | None = None, # noqa: FBT001
+ start_color: str | None = "green",
+ color: str | None = "green",
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ config: RunnableConfig | None = None,
+ tool_call_id: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run the tool.
+
+ Args:
+ tool_input: The input to the tool.
+ verbose: Whether to log the tool's progress.
+ start_color: The color to use when starting the tool.
+ color: The color to use when ending the tool.
+ callbacks: Callbacks to be called during tool execution.
+ tags: Optional list of tags associated with the tool.
+ metadata: Optional metadata associated with the tool.
+ run_name: The name of the run.
+ run_id: The id of the run.
+ config: The configuration for the tool.
+ tool_call_id: The id of the tool call.
+ **kwargs: Keyword arguments to be passed to tool callbacks (event handler)
+
+ Returns:
+ The output of the tool.
+
+ Raises:
+ ToolException: If an error occurs during tool execution.
+ """
+ callback_manager = CallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose or bool(verbose),
+ tags,
+ self.tags,
+ metadata,
+ self.metadata,
+ )
+
+ # Filter out injected arguments from callback inputs
+ filtered_tool_input = (
+ self._filter_injected_args(tool_input)
+ if isinstance(tool_input, dict)
+ else None
+ )
+
+ # Use filtered inputs for the input_str parameter as well
+ tool_input_str = (
+ tool_input
+ if isinstance(tool_input, str)
+ else str(
+ filtered_tool_input if filtered_tool_input is not None else tool_input
+ )
+ )
+
+ run_manager = callback_manager.on_tool_start(
+ {"name": self.name, "description": self.description},
+ tool_input_str,
+ color=start_color,
+ name=run_name,
+ run_id=run_id,
+ inputs=filtered_tool_input,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ )
+
+ content = None
+ artifact = None
+ status = "success"
+ error_to_raise: Exception | KeyboardInterrupt | None = None
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ tool_args, tool_kwargs = self._to_args_and_kwargs(
+ tool_input, tool_call_id
+ )
+ if signature(self._run).parameters.get("run_manager"):
+ tool_kwargs |= {"run_manager": run_manager}
+ if config_param := _get_runnable_config_param(self._run):
+ tool_kwargs |= {config_param: config}
+ response = context.run(self._run, *tool_args, **tool_kwargs)
+ if self.response_format == "content_and_artifact":
+ msg = (
+ "Since response_format='content_and_artifact' "
+ "a two-tuple of the message content and raw tool output is "
+ f"expected. Instead, generated response is of type: "
+ f"{type(response)}."
+ )
+ if not isinstance(response, tuple):
+ error_to_raise = ValueError(msg)
+ else:
+ try:
+ content, artifact = response
+ except ValueError:
+ error_to_raise = ValueError(msg)
+ else:
+ content = response
+ except (ValidationError, ValidationErrorV1) as e:
+ if not self.handle_validation_error:
+ error_to_raise = e
+ else:
+ content = _handle_validation_error(e, flag=self.handle_validation_error)
+ status = "error"
+ except ToolException as e:
+ if not self.handle_tool_error:
+ error_to_raise = e
+ else:
+ content = _handle_tool_error(e, flag=self.handle_tool_error)
+ status = "error"
+ except (Exception, KeyboardInterrupt) as e:
+ error_to_raise = e
+
+ if error_to_raise:
+ run_manager.on_tool_error(error_to_raise, tool_call_id=tool_call_id)
+ raise error_to_raise
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
+ run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
+ return output
+
+ async def arun(
+ self,
+ tool_input: str | dict,
+ verbose: bool | None = None, # noqa: FBT001
+ start_color: str | None = "green",
+ color: str | None = "green",
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ config: RunnableConfig | None = None,
+ tool_call_id: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run the tool asynchronously.
+
+ Args:
+ tool_input: The input to the tool.
+ verbose: Whether to log the tool's progress.
+ start_color: The color to use when starting the tool.
+ color: The color to use when ending the tool.
+ callbacks: Callbacks to be called during tool execution.
+ tags: Optional list of tags associated with the tool.
+ metadata: Optional metadata associated with the tool.
+ run_name: The name of the run.
+ run_id: The id of the run.
+ config: The configuration for the tool.
+ tool_call_id: The id of the tool call.
+ **kwargs: Keyword arguments to be passed to tool callbacks
+
+ Returns:
+ The output of the tool.
+
+ Raises:
+ ToolException: If an error occurs during tool execution.
+ """
+ callback_manager = AsyncCallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose or bool(verbose),
+ tags,
+ self.tags,
+ metadata,
+ self.metadata,
+ )
+
+ # Filter out injected arguments from callback inputs
+ filtered_tool_input = (
+ self._filter_injected_args(tool_input)
+ if isinstance(tool_input, dict)
+ else None
+ )
+
+ # Use filtered inputs for the input_str parameter as well
+ tool_input_str = (
+ tool_input
+ if isinstance(tool_input, str)
+ else str(
+ filtered_tool_input if filtered_tool_input is not None else tool_input
+ )
+ )
+
+ run_manager = await callback_manager.on_tool_start(
+ {"name": self.name, "description": self.description},
+ tool_input_str,
+ color=start_color,
+ name=run_name,
+ run_id=run_id,
+ inputs=filtered_tool_input,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ )
+ content = None
+ artifact = None
+ status = "success"
+ error_to_raise: Exception | KeyboardInterrupt | None = None
+ try:
+ tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input, tool_call_id)
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ func_to_check = (
+ self._run if self.__class__._arun is BaseTool._arun else self._arun # noqa: SLF001
+ )
+ if signature(func_to_check).parameters.get("run_manager"):
+ tool_kwargs["run_manager"] = run_manager
+ if config_param := _get_runnable_config_param(func_to_check):
+ tool_kwargs[config_param] = config
+
+ coro = self._arun(*tool_args, **tool_kwargs)
+ response = await coro_with_context(coro, context)
+ if self.response_format == "content_and_artifact":
+ msg = (
+ "Since response_format='content_and_artifact' "
+ "a two-tuple of the message content and raw tool output is "
+ f"expected. Instead, generated response is of type: "
+ f"{type(response)}."
+ )
+ if not isinstance(response, tuple):
+ error_to_raise = ValueError(msg)
+ else:
+ try:
+ content, artifact = response
+ except ValueError:
+ error_to_raise = ValueError(msg)
+ else:
+ content = response
+ except ValidationError as e:
+ if not self.handle_validation_error:
+ error_to_raise = e
+ else:
+ content = _handle_validation_error(e, flag=self.handle_validation_error)
+ status = "error"
+ except ToolException as e:
+ if not self.handle_tool_error:
+ error_to_raise = e
+ else:
+ content = _handle_tool_error(e, flag=self.handle_tool_error)
+ status = "error"
+ except (Exception, KeyboardInterrupt) as e:
+ error_to_raise = e
+
+ if error_to_raise:
+ await run_manager.on_tool_error(error_to_raise, tool_call_id=tool_call_id)
+ raise error_to_raise
+
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
+ await run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
+ return output
+
+
+def _is_tool_call(x: Any) -> bool:
+ """Check if the input is a tool call dictionary.
+
+ Args:
+ x: The input to check.
+
+ Returns:
+ `True` if the input is a tool call, `False` otherwise.
+ """
+ return isinstance(x, dict) and x.get("type") == "tool_call"
+
+
+def _handle_validation_error(
+ e: ValidationError | ValidationErrorV1,
+ *,
+ flag: Literal[True] | str | Callable[[ValidationError | ValidationErrorV1], str],
+) -> str:
+ """Handle validation errors based on the configured flag.
+
+ Args:
+ e: The validation error that occurred.
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
+
+ Returns:
+ The error message to return.
+
+ Raises:
+ ValueError: If the flag type is unexpected.
+ """
+ if isinstance(flag, bool):
+ content = "Tool input validation error"
+ elif isinstance(flag, str):
+ content = flag
+ elif callable(flag):
+ content = flag(e)
+ else:
+ msg = (
+ f"Got unexpected type of `handle_validation_error`. Expected bool, "
+ f"str or callable. Received: {flag}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return content
+
+
+def _handle_tool_error(
+ e: ToolException,
+ *,
+ flag: Literal[True] | str | Callable[[ToolException], str] | None,
+) -> str:
+ """Handle tool execution errors based on the configured flag.
+
+ Args:
+ e: The tool exception that occurred.
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
+
+ Returns:
+ The error message to return.
+
+ Raises:
+ ValueError: If the flag type is unexpected.
+ """
+ if isinstance(flag, bool):
+ content = e.args[0] if e.args else "Tool execution error"
+ elif isinstance(flag, str):
+ content = flag
+ elif callable(flag):
+ content = flag(e)
+ else:
+ msg = (
+ f"Got unexpected type of `handle_tool_error`. Expected bool, str "
+ f"or callable. Received: {flag}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return content
+
+
+def _prep_run_args(
+ value: str | dict | ToolCall,
+ config: RunnableConfig | None,
+ **kwargs: Any,
+) -> tuple[str | dict, dict]:
+ """Prepare arguments for tool execution.
+
+ Args:
+ value: The input value (`str`, `dict`, or `ToolCall`).
+ config: The runnable configuration.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A tuple of `(tool_input, run_kwargs)`.
+ """
+ config = ensure_config(config)
+ if _is_tool_call(value):
+ tool_call_id: str | None = cast("ToolCall", value)["id"]
+ tool_input: str | dict = cast("ToolCall", value)["args"].copy()
+ else:
+ tool_call_id = None
+ tool_input = cast("str | dict", value)
+ return (
+ tool_input,
+ dict(
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ config=config,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ ),
+ )
+
+
+def _format_output(
+ content: Any,
+ artifact: Any,
+ tool_call_id: str | None,
+ name: str,
+ status: str,
+) -> ToolOutputMixin | Any:
+ """Format tool output as a `ToolMessage` if appropriate.
+
+ Args:
+ content: The main content of the tool output.
+ artifact: Any artifact data from the tool.
+ tool_call_id: The ID of the tool call.
+ name: The name of the tool.
+ status: The execution status.
+
+ Returns:
+ The formatted output, either as a `ToolMessage`, the original content,
+ or an unchanged list of `ToolOutputMixin` instances.
+ """
+ if (
+ isinstance(content, list)
+ and content
+ and all(isinstance(item, ToolOutputMixin) for item in content)
+ ):
+ return content
+ if isinstance(content, ToolOutputMixin) or tool_call_id is None:
+ return content
+ if not _is_message_content_type(content):
+ content = _stringify(content)
+ return ToolMessage(
+ content,
+ artifact=artifact,
+ tool_call_id=tool_call_id,
+ name=name,
+ status=status,
+ )
+
+
+def _is_message_content_type(obj: Any) -> bool:
+ """Check if object is valid message content format.
+
+ Validates content for OpenAI or Anthropic format tool messages.
+
+ Args:
+ obj: The object to check.
+
+ Returns:
+ `True` if the object is valid message content, `False` otherwise.
+ """
+ return isinstance(obj, str) or (
+ isinstance(obj, list) and all(_is_message_content_block(e) for e in obj)
+ )
+
+
+def _is_message_content_block(obj: Any) -> bool:
+ """Check if object is a valid message content block.
+
+ Validates content blocks for OpenAI or Anthropic format.
+
+ Args:
+ obj: The object to check.
+
+ Returns:
+ `True` if the object is a valid content block, `False` otherwise.
+ """
+ if isinstance(obj, str):
+ return True
+ if isinstance(obj, dict):
+ return obj.get("type", None) in TOOL_MESSAGE_BLOCK_TYPES
+ return False
+
+
+def _stringify(content: Any) -> str:
+ """Convert content to string, preferring JSON format.
+
+ Args:
+ content: The content to stringify.
+
+ Returns:
+ String representation of the content.
+ """
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except Exception:
+ return str(content)
+
+
+def _get_type_hints(func: Callable) -> dict[str, type] | None:
+ """Get type hints from a function, handling partial functions.
+
+ Args:
+ func: The function to get type hints from.
+
+ Returns:
+ `dict` of type hints, or `None` if extraction fails.
+ """
+ if isinstance(func, functools.partial):
+ func = func.func
+ try:
+ return get_type_hints(func)
+ except Exception:
+ return None
+
+
+def _get_runnable_config_param(func: Callable) -> str | None:
+ """Find the parameter name for `RunnableConfig` in a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The parameter name for `RunnableConfig`, or `None` if not found.
+ """
+ type_hints = _get_type_hints(func)
+ if not type_hints:
+ return None
+ for name, type_ in type_hints.items():
+ if type_ is RunnableConfig:
+ return name
+ return None
+
+
+class InjectedToolArg:
+ """Annotation for tool arguments that are injected at runtime.
+
+ Tool arguments annotated with this class are not included in the tool
+ schema sent to language models and are instead injected during execution.
+ """
+
+
+class _DirectlyInjectedToolArg:
+ """Annotation for tool arguments that are injected at runtime.
+
+ Injected via direct type annotation, rather than annotated metadata.
+
+ For example, `ToolRuntime` is a directly injected argument.
+
+ Note the direct annotation rather than the verbose alternative:
+ `Annotated[ToolRuntime, InjectedRuntime]`
+
+ ```python
+ from langchain_core.tools import tool, ToolRuntime
+
+
+ @tool
+ def foo(x: int, runtime: ToolRuntime) -> str:
+ # use runtime.state, runtime.context, runtime.store, etc.
+ ...
+ ```
+ """
+
+
+class InjectedToolCallId(InjectedToolArg):
+ """Annotation for injecting the tool call ID.
+
+ This annotation is used to mark a tool parameter that should receive the tool call
+ ID at runtime.
+
+ ```python
+ from typing import Annotated
+ from langchain_core.messages import ToolMessage
+ from langchain_core.tools import tool, InjectedToolCallId
+
+ @tool
+ def foo(
+ x: int, tool_call_id: Annotated[str, InjectedToolCallId]
+ ) -> ToolMessage:
+ \"\"\"Return x.\"\"\"
+ return ToolMessage(
+ str(x),
+ artifact=x,
+ name="foo",
+ tool_call_id=tool_call_id
+ )
+ ```
+ """
+
+
+def _is_directly_injected_arg_type(type_: Any) -> bool:
+ """Check if a type annotation indicates a directly injected argument.
+
+ This is currently only used for `ToolRuntime`.
+
+ Checks if either the annotation itself is a subclass of `_DirectlyInjectedToolArg`
+ or the origin of the annotation is a subclass of `_DirectlyInjectedToolArg`.
+
+ For example, `ToolRuntime` or `ToolRuntime[ContextT, StateT]` would both return
+ `True`.
+ """
+ return (
+ isinstance(type_, type) and issubclass(type_, _DirectlyInjectedToolArg)
+ ) or (
+ (origin := get_origin(type_)) is not None
+ and isinstance(origin, type)
+ and issubclass(origin, _DirectlyInjectedToolArg)
+ )
+
+
+def _is_injected_arg_type(
+ type_: type | TypeVar, injected_type: type[InjectedToolArg] | None = None
+) -> bool:
+ """Check if a type annotation indicates an injected argument.
+
+ Args:
+ type_: The type annotation to check.
+ injected_type: The specific injected type to check for.
+
+ Returns:
+ `True` if the type is an injected argument, `False` otherwise.
+ """
+ if injected_type is None:
+ # if no injected type is specified,
+ # check if the type is a directly injected argument
+ if _is_directly_injected_arg_type(type_):
+ return True
+ injected_type = InjectedToolArg
+
+ # if the type is an Annotated type, check if annotated metadata
+ # is an intance or subclass of the injected type
+ return any(
+ isinstance(arg, injected_type)
+ or (isinstance(arg, type) and issubclass(arg, injected_type))
+ for arg in get_args(type_)[1:]
+ )
+
+
+def get_all_basemodel_annotations(
+ cls: TypeBaseModel | Any, *, default_to_bound: bool = True
+) -> dict[str, type | TypeVar]:
+ """Get all annotations from a Pydantic `BaseModel` and its parents.
+
+ Args:
+ cls: The Pydantic `BaseModel` class.
+ default_to_bound: Whether to default to the bound of a `TypeVar` if it exists.
+
+ Returns:
+ `dict` of field names to their type annotations.
+ """
+ # cls has no subscript: cls = FooBar
+ if isinstance(cls, type):
+ fields = get_fields(cls)
+ alias_map = {field.alias: name for name, field in fields.items() if field.alias}
+
+ annotations: dict[str, type | TypeVar] = {}
+ for name, param in inspect.signature(cls).parameters.items():
+ # Exclude hidden init args added by pydantic Config. For example if
+ # BaseModel(extra="allow") then "extra_data" will part of init sig.
+ if name not in fields and name not in alias_map:
+ continue
+ field_name = alias_map.get(name, name)
+ annotations[field_name] = param.annotation
+ orig_bases: tuple = getattr(cls, "__orig_bases__", ())
+ # cls has subscript: cls = FooBar[int]
+ else:
+ annotations = get_all_basemodel_annotations(
+ get_origin(cls), default_to_bound=False
+ )
+ orig_bases = (cls,)
+
+ # Pydantic v2 automatically resolves inherited generics, Pydantic v1 does not.
+ if not (isinstance(cls, type) and is_pydantic_v2_subclass(cls)):
+ # if cls = FooBar inherits from Baz[str], orig_bases will contain Baz[str]
+ # if cls = FooBar inherits from Baz, orig_bases will contain Baz
+ # if cls = FooBar[int], orig_bases will contain FooBar[int]
+ for parent in orig_bases:
+ # if class = FooBar inherits from Baz, parent = Baz
+ if isinstance(parent, type) and is_pydantic_v1_subclass(parent):
+ annotations.update(
+ get_all_basemodel_annotations(parent, default_to_bound=False)
+ )
+ continue
+
+ parent_origin = get_origin(parent)
+
+ # if class = FooBar inherits from non-pydantic class
+ if not parent_origin:
+ continue
+
+ # if class = FooBar inherits from Baz[str]:
+ # parent = class Baz[str],
+ # parent_origin = class Baz,
+ # generic_type_vars = (type vars in Baz)
+ # generic_map = {type var in Baz: str}
+ generic_type_vars: tuple = getattr(parent_origin, "__parameters__", ())
+ generic_map = dict(zip(generic_type_vars, get_args(parent), strict=False))
+ for field in getattr(parent_origin, "__annotations__", {}):
+ annotations[field] = _replace_type_vars(
+ annotations[field], generic_map, default_to_bound=default_to_bound
+ )
+
+ return {
+ k: _replace_type_vars(v, default_to_bound=default_to_bound)
+ for k, v in annotations.items()
+ }
+
+
+def _replace_type_vars(
+ type_: type | TypeVar,
+ generic_map: dict[TypeVar, type] | None = None,
+ *,
+ default_to_bound: bool = True,
+) -> type | TypeVar:
+ """Replace `TypeVar`s in a type annotation with concrete types.
+
+ Args:
+ type_: The type annotation to process.
+ generic_map: Mapping of `TypeVar`s to concrete types.
+ default_to_bound: Whether to use `TypeVar` bounds as defaults.
+
+ Returns:
+ The type with `TypeVar`s replaced.
+ """
+ generic_map = generic_map or {}
+ if isinstance(type_, TypeVar):
+ if type_ in generic_map:
+ return generic_map[type_]
+ if default_to_bound:
+ return type_.__bound__ if type_.__bound__ is not None else Any
+ return type_
+ if (origin := get_origin(type_)) and (args := get_args(type_)):
+ new_args = tuple(
+ _replace_type_vars(arg, generic_map, default_to_bound=default_to_bound)
+ for arg in args
+ )
+ return cast("type", _py_38_safe_origin(origin)[new_args]) # type: ignore[index]
+ return type_
+
+
+class BaseToolkit(BaseModel, ABC):
+ """Base class for toolkits containing related tools.
+
+ A toolkit is a collection of related tools that can be used together to accomplish a
+ specific task or work with a particular system.
+ """
+
+ @abstractmethod
+ def get_tools(self) -> list[BaseTool]:
+ """Get all tools in the toolkit.
+
+ Returns:
+ List of tools contained in this toolkit.
+ """
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/convert.py b/python/user_packages/Python313/site-packages/langchain_core/tools/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..48c518a29822aebfac0cf7ccb871a614ae888cdc
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/convert.py
@@ -0,0 +1,476 @@
+"""Convert functions and runnables to tools."""
+
+import inspect
+from collections.abc import Callable
+from typing import Any, Literal, cast, get_type_hints, overload
+
+from pydantic import BaseModel, Field, create_model
+
+from langchain_core.callbacks import Callbacks
+from langchain_core.runnables import Runnable
+from langchain_core.tools.base import ArgsSchema, BaseTool
+from langchain_core.tools.simple import Tool
+from langchain_core.tools.structured import StructuredTool
+
+
+@overload
+def tool(
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> Callable[[Callable | Runnable], BaseTool]: ...
+
+
+@overload
+def tool(
+ name_or_callable: str,
+ runnable: Runnable,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool: ...
+
+
+@overload
+def tool(
+ name_or_callable: Callable,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool: ...
+
+
+@overload
+def tool(
+ name_or_callable: str,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> Callable[[Callable | Runnable], BaseTool]: ...
+
+
+def tool(
+ name_or_callable: str | Callable | None = None,
+ runnable: Runnable | None = None,
+ *args: Any,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
+ """Convert Python functions and `Runnables` to LangChain tools.
+
+ Can be used as a decorator with or without arguments to create tools from functions.
+
+ Functions can have any signature - the tool will automatically infer input schemas
+ unless disabled.
+
+ !!! note "Requirements"
+
+ - Functions should have type hints for proper schema inference.
+ - Functions may accept multiple arguments and return types are flexible;
+ outputs will be serialized if needed.
+ - When using with `Runnable`, a string name must be provided.
+
+ Args:
+ name_or_callable: Optional name of the tool or the `Callable` to be
+ converted to a tool.
+
+ Overrides the function's name.
+
+ Must be provided as a positional argument.
+ runnable: Optional `Runnable` to convert to a tool.
+
+ Must be provided as a positional argument.
+ description: Optional description for the tool.
+
+ Precedence for the tool description value is as follows:
+
+ - This `description` argument (used even if docstring and/or `args_schema`
+ are provided)
+ - Tool function docstring (used even if `args_schema` is provided)
+ - `args_schema` description (used only if `description` and docstring are
+ not provided)
+ *args: Extra positional arguments.
+
+ Must be empty.
+ return_direct: Whether to return directly from the tool rather than continuing
+ the agent loop.
+ args_schema: Optional argument schema for user to specify.
+ infer_schema: Whether to infer the schema of the arguments from the function's
+ signature.
+
+ This also makes the resultant tool accept a dictionary input to its `run()`
+ function.
+ response_format: The tool response format.
+
+ If `'content'`, then the output of the tool is interpreted as the contents
+ of a `ToolMessage`.
+
+ If `'content_and_artifact'`, then the output is expected to be a two-tuple
+ corresponding to the `(content, artifact)` of a `ToolMessage`.
+ parse_docstring: If `infer_schema` and `parse_docstring`, will attempt to
+ parse parameter descriptions from Google Style function docstrings.
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ extras: Optional provider-specific extra fields for the tool.
+
+ Used to pass configuration that doesn't fit into standard tool fields.
+ Chat models should process known extras when constructing model payloads.
+
+ !!! example
+
+ For example, Anthropic-specific fields like `cache_control`,
+ `defer_loading`, or `input_examples`.
+
+ Raises:
+ ValueError: If too many positional arguments are provided (e.g. violating the
+ `*args` constraint).
+ ValueError: If a `Runnable` is provided without a string name. When using `tool`
+ with a `Runnable`, a `str` name must be provided as the `name_or_callable`.
+ ValueError: If the first argument is not a string or callable with
+ a `__name__` attribute.
+ ValueError: If the function does not have a docstring and description
+ is not provided and `infer_schema` is `False`.
+ ValueError: If `parse_docstring` is `True` and the function has an invalid
+ Google-style docstring and `error_on_invalid_docstring` is True.
+ ValueError: If a `Runnable` is provided that does not have an object schema.
+
+ Returns:
+ The tool.
+
+ Examples:
+ ```python
+ @tool
+ def search_api(query: str) -> str:
+ # Searches the API for the query.
+ return
+
+
+ @tool("search", return_direct=True)
+ def search_api(query: str) -> str:
+ # Searches the API for the query.
+ return
+
+
+ @tool(response_format="content_and_artifact")
+ def search_api(query: str) -> tuple[str, dict]:
+ return "partial json of results", {"full": "object of results"}
+ ```
+
+ Parse Google-style docstrings:
+
+ ```python
+ @tool(parse_docstring=True)
+ def foo(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+
+ Args:
+ bar: The bar.
+ baz: The baz.
+ \"\"\"
+ return bar
+
+ foo.args_schema.model_json_schema()
+ ```
+
+ ```python
+ {
+ "title": "foo",
+ "description": "The foo.",
+ "type": "object",
+ "properties": {
+ "bar": {
+ "title": "Bar",
+ "description": "The bar.",
+ "type": "string",
+ },
+ "baz": {
+ "title": "Baz",
+ "description": "The baz.",
+ "type": "integer",
+ },
+ },
+ "required": ["bar", "baz"],
+ }
+ ```
+
+ Note that parsing by default will raise `ValueError` if the docstring is
+ considered invalid. A docstring is considered invalid if it contains arguments
+ not in the function signature, or is unable to be parsed into a summary and
+ `'Args:'` blocks. Examples below:
+
+ ```python
+ # No args section
+ def invalid_docstring_1(bar: str, baz: int) -> str:
+ \"\"\"The foo.\"\"\"
+ return bar
+
+ # Improper whitespace between summary and args section
+ def invalid_docstring_2(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+ Args:
+ bar: The bar.
+ baz: The baz.
+ \"\"\"
+ return bar
+
+ # Documented args absent from function signature
+ def invalid_docstring_3(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+
+ Args:
+ banana: The bar.
+ monkey: The baz.
+ \"\"\"
+ return bar
+
+ ```
+ """ # noqa: D214, D410, D411 # We're intentionally showing bad formatting in examples
+
+ def _create_tool_factory(
+ tool_name: str,
+ ) -> Callable[[Callable | Runnable], BaseTool]:
+ """Create a decorator that takes a callable and returns a tool.
+
+ Args:
+ tool_name: The name that will be assigned to the tool.
+
+ Returns:
+ A function that takes a callable or `Runnable` and returns a tool.
+ """
+
+ def _tool_factory(dec_func: Callable | Runnable) -> BaseTool:
+ tool_description = description
+ if isinstance(dec_func, Runnable):
+ runnable = dec_func
+
+ if runnable.input_schema.model_json_schema().get("type") != "object":
+ msg = "Runnable must have an object schema."
+ raise ValueError(msg)
+
+ async def ainvoke_wrapper(
+ callbacks: Callbacks | None = None, **kwargs: Any
+ ) -> Any:
+ return await runnable.ainvoke(kwargs, {"callbacks": callbacks})
+
+ def invoke_wrapper(
+ callbacks: Callbacks | None = None, **kwargs: Any
+ ) -> Any:
+ return runnable.invoke(kwargs, {"callbacks": callbacks})
+
+ coroutine = ainvoke_wrapper
+ func = invoke_wrapper
+ schema: ArgsSchema | None = runnable.input_schema
+ tool_description = description or repr(runnable)
+ elif inspect.iscoroutinefunction(dec_func):
+ coroutine = dec_func
+ func = None
+ schema = args_schema
+ else:
+ coroutine = None
+ func = dec_func
+ schema = args_schema
+
+ if infer_schema or args_schema is not None:
+ return StructuredTool.from_function(
+ func,
+ coroutine,
+ name=tool_name,
+ description=tool_description,
+ return_direct=return_direct,
+ args_schema=schema,
+ infer_schema=infer_schema,
+ response_format=response_format,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ extras=extras,
+ )
+ # If someone doesn't want a schema applied, we must treat it as
+ # a simple string->string function
+ if dec_func.__doc__ is None:
+ msg = (
+ "Function must have a docstring if "
+ "description not provided and infer_schema is False."
+ )
+ raise ValueError(msg)
+ return Tool(
+ name=tool_name,
+ func=func,
+ description=f"{tool_name} tool",
+ return_direct=return_direct,
+ coroutine=coroutine,
+ response_format=response_format,
+ extras=extras,
+ )
+
+ return _tool_factory
+
+ if len(args) != 0:
+ # Triggered if a user attempts to use positional arguments that
+ # do not exist in the function signature
+ # e.g., @tool("name", runnable, "extra_arg")
+ # Here, "extra_arg" is not a valid argument
+ msg = "Too many arguments for tool decorator. A decorator "
+ raise ValueError(msg)
+
+ if runnable is not None:
+ # tool is used as a function
+ # for instance tool_from_runnable = tool("name", runnable)
+ if not name_or_callable:
+ msg = "Runnable without name for tool constructor"
+ raise ValueError(msg)
+ if not isinstance(name_or_callable, str):
+ msg = "Name must be a string for tool constructor"
+ raise ValueError(msg)
+ return _create_tool_factory(name_or_callable)(runnable)
+ if name_or_callable is not None:
+ if callable(name_or_callable) and hasattr(name_or_callable, "__name__"):
+ # Used as a decorator without parameters
+ # @tool
+ # def my_tool():
+ # pass
+ return _create_tool_factory(name_or_callable.__name__)(name_or_callable)
+ if isinstance(name_or_callable, str):
+ # Used with a new name for the tool
+ # @tool("search")
+ # def my_tool():
+ # pass
+ #
+ # or
+ #
+ # @tool("search", parse_docstring=True)
+ # def my_tool():
+ # pass
+ return _create_tool_factory(name_or_callable)
+ msg = (
+ f"The first argument must be a string or a callable with a __name__ "
+ f"for tool decorator. Got {type(name_or_callable)}"
+ )
+ raise ValueError(msg)
+
+ # Tool is used as a decorator with parameters specified
+ # @tool(parse_docstring=True)
+ # def my_tool():
+ # pass
+ def _partial(func: Callable | Runnable) -> BaseTool:
+ """Partial function that takes a `Callable` and returns a tool."""
+ name_ = func.get_name() if isinstance(func, Runnable) else func.__name__
+ tool_factory = _create_tool_factory(name_)
+ return tool_factory(func)
+
+ return _partial
+
+
+def _get_description_from_runnable(runnable: Runnable) -> str:
+ """Generate a placeholder description of a `Runnable`."""
+ input_schema = runnable.input_schema.model_json_schema()
+ return f"Takes {input_schema}."
+
+
+def _get_schema_from_runnable_and_arg_types(
+ runnable: Runnable,
+ name: str,
+ arg_types: dict[str, type] | None = None,
+) -> type[BaseModel]:
+ """Infer `args_schema` for tool."""
+ if arg_types is None:
+ try:
+ arg_types = get_type_hints(runnable.InputType)
+ except TypeError as e:
+ msg = (
+ "Tool input must be str or dict. If dict, dict arguments must be "
+ "typed. Either annotate types (e.g., with TypedDict) or pass "
+ f"arg_types into `.as_tool` to specify. {e}"
+ )
+ raise TypeError(msg) from e
+ fields = {key: (key_type, Field(...)) for key, key_type in arg_types.items()}
+ return cast("type[BaseModel]", create_model(name, **fields)) # type: ignore[call-overload]
+
+
+def convert_runnable_to_tool(
+ runnable: Runnable,
+ args_schema: type[BaseModel] | None = None,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ arg_types: dict[str, type] | None = None,
+) -> BaseTool:
+ """Convert a `Runnable` into a `BaseTool`.
+
+ Args:
+ runnable: The `Runnable` to convert.
+ args_schema: The schema for the tool's input arguments.
+ name: The name of the tool.
+ description: The description of the tool.
+ arg_types: The types of the arguments.
+
+ Returns:
+ The tool.
+ """
+ if args_schema:
+ runnable = runnable.with_types(input_type=args_schema)
+ description = description or _get_description_from_runnable(runnable)
+ name = name or runnable.get_name()
+
+ schema = runnable.input_schema.model_json_schema()
+ if schema.get("type") == "string":
+ return Tool(
+ name=name,
+ func=runnable.invoke,
+ coroutine=runnable.ainvoke,
+ description=description,
+ )
+
+ async def ainvoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
+ return await runnable.ainvoke(kwargs, config={"callbacks": callbacks})
+
+ def invoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
+ return runnable.invoke(kwargs, config={"callbacks": callbacks})
+
+ if (
+ arg_types is None
+ and schema.get("type") == "object"
+ and schema.get("properties")
+ ):
+ args_schema = runnable.input_schema
+ else:
+ args_schema = _get_schema_from_runnable_and_arg_types(
+ runnable, name, arg_types=arg_types
+ )
+
+ return StructuredTool.from_function(
+ name=name,
+ func=invoke_wrapper,
+ coroutine=ainvoke_wrapper,
+ description=description,
+ args_schema=args_schema,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/render.py b/python/user_packages/Python313/site-packages/langchain_core/tools/render.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f8b10149e98bcc7dc65451860a49b75fdf8c14
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/render.py
@@ -0,0 +1,67 @@
+"""Utilities to render tools."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from inspect import signature
+
+from langchain_core.tools.base import BaseTool
+
+ToolsRenderer = Callable[[list[BaseTool]], str]
+
+
+def render_text_description(tools: list[BaseTool]) -> str:
+ """Render the tool name and description in plain text.
+
+ Args:
+ tools: The tools to render.
+
+ Returns:
+ The rendered text.
+
+ Output will be in the format of:
+
+ ```txt
+ search: This tool is used for search
+ calculator: This tool is used for math
+ ```
+ """
+ descriptions = []
+ for tool in tools:
+ if hasattr(tool, "func") and tool.func:
+ sig = signature(tool.func)
+ description = f"{tool.name}{sig} - {tool.description}"
+ else:
+ description = f"{tool.name} - {tool.description}"
+
+ descriptions.append(description)
+ return "\n".join(descriptions)
+
+
+def render_text_description_and_args(tools: list[BaseTool]) -> str:
+ """Render the tool name, description, and args in plain text.
+
+ Args:
+ tools: The tools to render.
+
+ Returns:
+ The rendered text.
+
+ Output will be in the format of:
+
+ ```txt
+ search: This tool is used for search, args: {"query": {"type": "string"}}
+ calculator: This tool is used for math, \
+ args: {"expression": {"type": "string"}}
+ ```
+ """
+ tool_strings = []
+ for tool in tools:
+ args_schema = str(tool.args)
+ if hasattr(tool, "func") and tool.func:
+ sig = signature(tool.func)
+ description = f"{tool.name}{sig} - {tool.description}"
+ else:
+ description = f"{tool.name} - {tool.description}"
+ tool_strings.append(f"{description}, args: {args_schema}")
+ return "\n".join(tool_strings)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/retriever.py b/python/user_packages/Python313/site-packages/langchain_core/tools/retriever.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2d84dcb0ca79ca4837d05c2863785f88e42ced
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/retriever.py
@@ -0,0 +1,94 @@
+"""Retriever tool."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from pydantic import BaseModel, Field
+
+# Cannot move Callbacks and Document to TYPE_CHECKING as StructuredTool's
+# func/coroutine parameter annotations are evaluated at runtime.
+from langchain_core.callbacks import Callbacks # noqa: TC001
+from langchain_core.documents import Document # noqa: TC001
+from langchain_core.prompts import (
+ BasePromptTemplate,
+ PromptTemplate,
+ aformat_document,
+ format_document,
+)
+from langchain_core.tools.structured import StructuredTool
+
+if TYPE_CHECKING:
+ from langchain_core.retrievers import BaseRetriever
+
+
+class RetrieverInput(BaseModel):
+ """Input to the retriever."""
+
+ query: str = Field(description="query to look up in retriever")
+
+
+def create_retriever_tool(
+ retriever: BaseRetriever,
+ name: str,
+ description: str,
+ *,
+ document_prompt: BasePromptTemplate | None = None,
+ document_separator: str = "\n\n",
+ response_format: Literal["content", "content_and_artifact"] = "content",
+) -> StructuredTool:
+ r"""Create a tool to do retrieval of documents.
+
+ Args:
+ retriever: The retriever to use for the retrieval
+ name: The name for the tool.
+
+ This will be passed to the language model, so should be unique and somewhat
+ descriptive.
+ description: The description for the tool.
+
+ This will be passed to the language model, so should be descriptive.
+ document_prompt: The prompt to use for the document.
+ document_separator: The separator to use between documents.
+ response_format: The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the contents of
+ a `ToolMessage`. If `'content_and_artifact'` then the output is expected to
+ be a two-tuple corresponding to the `(content, artifact)` of a `ToolMessage`
+ (artifact being a list of documents in this case).
+
+ Returns:
+ Tool class to pass to an agent.
+ """
+ document_prompt_ = document_prompt or PromptTemplate.from_template("{page_content}")
+
+ def func(
+ query: str, callbacks: Callbacks = None
+ ) -> str | tuple[str, list[Document]]:
+ docs = retriever.invoke(query, config={"callbacks": callbacks})
+ content = document_separator.join(
+ format_document(doc, document_prompt_) for doc in docs
+ )
+ if response_format == "content_and_artifact":
+ return (content, docs)
+ return content
+
+ async def afunc(
+ query: str, callbacks: Callbacks = None
+ ) -> str | tuple[str, list[Document]]:
+ docs = await retriever.ainvoke(query, config={"callbacks": callbacks})
+ content = document_separator.join(
+ [await aformat_document(doc, document_prompt_) for doc in docs]
+ )
+ if response_format == "content_and_artifact":
+ return (content, docs)
+ return content
+
+ return StructuredTool(
+ name=name,
+ description=description,
+ func=func,
+ coroutine=afunc,
+ args_schema=RetrieverInput,
+ response_format=response_format,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/simple.py b/python/user_packages/Python313/site-packages/langchain_core/tools/simple.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca80164df88d2a74a866fc8e5b24e52dbc36dff4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/simple.py
@@ -0,0 +1,204 @@
+"""Tool that takes in function or coroutine directly."""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+# Cannot move to TYPE_CHECKING as _run/_arun parameter annotations are needed at runtime
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForToolRun, # noqa: TC001
+ CallbackManagerForToolRun, # noqa: TC001
+)
+from langchain_core.runnables import RunnableConfig, run_in_executor
+from langchain_core.tools.base import (
+ ArgsSchema,
+ BaseTool,
+ ToolException,
+ _get_runnable_config_param,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.messages import ToolCall
+
+
+class Tool(BaseTool):
+ """Tool that takes in function or coroutine directly."""
+
+ description: str = ""
+
+ func: Callable[..., str] | None
+ """The function to run when the tool is called."""
+
+ coroutine: Callable[..., Awaitable[str]] | None = None
+ """The asynchronous version of the function."""
+
+ # --- Runnable ---
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not self.coroutine:
+ # If the tool does not implement async, fall back to default implementation
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ return await super().ainvoke(input, config, **kwargs)
+
+ # --- Tool ---
+
+ @property
+ def args(self) -> dict:
+ """The tool's input arguments.
+
+ Returns:
+ The input arguments for the tool.
+ """
+ if self.args_schema is not None:
+ return super().args
+ # For backwards compatibility, if the function signature is ambiguous,
+ # assume it takes a single string input.
+ return {"tool_input": {"type": "string"}}
+
+ def _to_args_and_kwargs(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> tuple[tuple, dict]:
+ """Convert tool input to Pydantic model.
+
+ Args:
+ tool_input: The input to the tool.
+ tool_call_id: The ID of the tool call.
+
+ Raises:
+ ToolException: If the tool input is invalid.
+
+ Returns:
+ The Pydantic model args and kwargs.
+ """
+ args, kwargs = super()._to_args_and_kwargs(tool_input, tool_call_id)
+ # For backwards compatibility. The tool must be run with a single input
+ all_args = list(args) + list(kwargs.values())
+ if len(all_args) != 1:
+ msg = (
+ f"""Too many arguments to single-input tool {self.name}.
+ Consider using StructuredTool instead."""
+ f" Args: {all_args}"
+ )
+ raise ToolException(msg)
+ return tuple(all_args), {}
+
+ def _run(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.func:
+ if run_manager and signature(self.func).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.func):
+ kwargs[config_param] = config
+ return self.func(*args, **kwargs)
+ msg = "Tool does not support sync invocation."
+ raise NotImplementedError(msg)
+
+ async def _arun(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool asynchronously.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.coroutine:
+ if run_manager and signature(self.coroutine).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.coroutine):
+ kwargs[config_param] = config
+ return await self.coroutine(*args, **kwargs)
+
+ # NOTE: this code is unreachable since _arun is only called if coroutine is not
+ # None.
+ return await super()._arun(
+ *args, config=config, run_manager=run_manager, **kwargs
+ )
+
+ # TODO: this is for backwards compatibility, remove in future
+ def __init__(
+ self, name: str, func: Callable | None, description: str, **kwargs: Any
+ ) -> None:
+ """Initialize tool."""
+ super().__init__(name=name, func=func, description=description, **kwargs)
+
+ @classmethod
+ def from_function(
+ cls,
+ func: Callable | None,
+ name: str, # We keep these required to support backwards compatibility
+ description: str,
+ return_direct: bool = False, # noqa: FBT001,FBT002
+ args_schema: ArgsSchema | None = None,
+ coroutine: Callable[..., Awaitable[Any]]
+ | None = None, # This is last for compatibility, but should be after func
+ **kwargs: Any,
+ ) -> Tool:
+ """Initialize tool from a function.
+
+ Args:
+ func: The function to create the tool from.
+ name: The name of the tool.
+ description: The description of the tool.
+ return_direct: Whether to return the output directly.
+ args_schema: The schema of the tool's input arguments.
+ coroutine: The asynchronous version of the function.
+ **kwargs: Additional arguments to pass to the tool.
+
+ Returns:
+ The tool.
+
+ Raises:
+ ValueError: If the function is not provided.
+ """
+ if func is None and coroutine is None:
+ msg = "Function and/or coroutine must be provided"
+ raise ValueError(msg)
+ return cls(
+ name=name,
+ func=func,
+ coroutine=coroutine,
+ description=description,
+ return_direct=return_direct,
+ args_schema=args_schema,
+ **kwargs,
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tools/structured.py b/python/user_packages/Python313/site-packages/langchain_core/tools/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b67e3b4547c6fc7900874570ebd9c36dfd90504
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tools/structured.py
@@ -0,0 +1,271 @@
+"""Structured tool."""
+
+from __future__ import annotations
+
+import functools
+import textwrap
+from collections.abc import Awaitable, Callable
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+)
+
+from pydantic import Field, SkipValidation
+from typing_extensions import override
+
+# Cannot move to TYPE_CHECKING as _run/_arun parameter annotations are needed at runtime
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForToolRun, # noqa: TC001
+ CallbackManagerForToolRun, # noqa: TC001
+)
+from langchain_core.runnables import RunnableConfig, run_in_executor
+from langchain_core.tools.base import (
+ _EMPTY_SET,
+ FILTERED_ARGS,
+ ArgsSchema,
+ BaseTool,
+ _get_runnable_config_param,
+ _is_injected_arg_type,
+ create_schema_from_function,
+)
+from langchain_core.utils.pydantic import is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from langchain_core.messages import ToolCall
+
+
+class StructuredTool(BaseTool):
+ """Tool that can operate on any number of inputs."""
+
+ description: str = ""
+
+ args_schema: Annotated[ArgsSchema, SkipValidation()] = Field(
+ ..., description="The tool schema."
+ )
+ """The input arguments' schema."""
+
+ func: Callable[..., Any] | None = None
+ """The function to run when the tool is called."""
+
+ coroutine: Callable[..., Awaitable[Any]] | None = None
+ """The asynchronous version of the function."""
+
+ # --- Runnable ---
+
+ # TODO: Is this needed?
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not self.coroutine:
+ # If the tool does not implement async, fall back to default implementation
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ return await super().ainvoke(input, config, **kwargs)
+
+ # --- Tool ---
+
+ def _run(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.func:
+ if run_manager and signature(self.func).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.func):
+ kwargs[config_param] = config
+ return self.func(*args, **kwargs)
+ msg = "StructuredTool does not support sync invocation."
+ raise NotImplementedError(msg)
+
+ async def _arun(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool asynchronously.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.coroutine:
+ if run_manager and signature(self.coroutine).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.coroutine):
+ kwargs[config_param] = config
+ return await self.coroutine(*args, **kwargs)
+
+ # If self.coroutine is None, then this will delegate to the default
+ # implementation which is expected to delegate to _run on a separate thread.
+ return await super()._arun(
+ *args, config=config, run_manager=run_manager, **kwargs
+ )
+
+ @classmethod
+ def from_function(
+ cls,
+ func: Callable | None = None,
+ coroutine: Callable[..., Awaitable[Any]] | None = None,
+ name: str | None = None,
+ description: str | None = None,
+ return_direct: bool = False, # noqa: FBT001,FBT002
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True, # noqa: FBT001,FBT002
+ *,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+ **kwargs: Any,
+ ) -> StructuredTool:
+ """Create tool from a given function.
+
+ A classmethod that helps to create a tool from a function.
+
+ Args:
+ func: The function from which to create a tool.
+ coroutine: The async function from which to create a tool.
+ name: The name of the tool.
+
+ Defaults to the function name.
+ description: The description of the tool.
+
+ Defaults to the function docstring.
+ return_direct: Whether to return the result directly or as a callback.
+ args_schema: The schema of the tool's input arguments.
+ infer_schema: Whether to infer the schema from the function's signature.
+ response_format: The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the
+ contents of a `ToolMessage`. If `'content_and_artifact'` then the output
+ is expected to be a two-tuple corresponding to the `(content, artifact)`
+ of a `ToolMessage`.
+ parse_docstring: If `infer_schema` and `parse_docstring`, will attempt
+ to parse parameter descriptions from Google Style function docstrings.
+ error_on_invalid_docstring: if `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ **kwargs: Additional arguments to pass to the tool
+
+ Returns:
+ The tool.
+
+ Raises:
+ ValueError: If the function is not provided.
+ ValueError: If the function does not have a docstring and description
+ is not provided.
+ TypeError: If the `args_schema` is not a `BaseModel` or dict.
+
+ Examples:
+ ```python
+ def add(a: int, b: int) -> int:
+ \"\"\"Add two numbers\"\"\"
+ return a + b
+ tool = StructuredTool.from_function(add)
+ tool.run(1, 2) # 3
+
+ ```
+ """
+ if func is not None:
+ source_function = func
+ elif coroutine is not None:
+ source_function = coroutine
+ else:
+ msg = "Function and/or coroutine must be provided"
+ raise ValueError(msg)
+ name = name or source_function.__name__
+ if args_schema is None and infer_schema:
+ # schema name is appended within function
+ args_schema = create_schema_from_function(
+ name,
+ source_function,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ filter_args=_filter_schema_args(source_function),
+ )
+ description_ = description
+ if description is None and not parse_docstring:
+ description_ = source_function.__doc__ or None
+ if description_ is None and args_schema:
+ if isinstance(args_schema, type) and is_basemodel_subclass(args_schema):
+ description_ = args_schema.__doc__
+ if (
+ description_
+ and "A base class for creating Pydantic models" in description_
+ ):
+ description_ = ""
+ elif not description_:
+ description_ = None
+ elif isinstance(args_schema, dict):
+ description_ = args_schema.get("description")
+ else:
+ msg = (
+ "Invalid args_schema: expected BaseModel or dict, "
+ f"got {args_schema}"
+ )
+ raise TypeError(msg)
+ if description_ is None:
+ msg = "Function must have a docstring if description not provided."
+ raise ValueError(msg)
+ if description is None:
+ # Only apply if using the function's docstring
+ description_ = textwrap.dedent(description_).strip()
+
+ # Description example:
+ # search_api(query: str) - Searches the API for the query.
+ description_ = f"{description_.strip()}"
+ return cls(
+ name=name,
+ func=func,
+ coroutine=coroutine,
+ args_schema=args_schema,
+ description=description_,
+ return_direct=return_direct,
+ response_format=response_format,
+ **kwargs,
+ )
+
+ @functools.cached_property
+ def _injected_args_keys(self) -> frozenset[str]:
+ fn = self.func or self.coroutine
+ if fn is None:
+ return _EMPTY_SET
+ return frozenset(
+ k
+ for k, v in signature(fn).parameters.items()
+ if _is_injected_arg_type(v.annotation)
+ )
+
+
+def _filter_schema_args(func: Callable) -> list[str]:
+ filter_args = list(FILTERED_ARGS)
+ if config_param := _get_runnable_config_param(func):
+ filter_args.append(config_param)
+ # filter_args.extend(_get_non_model_params(type_hints))
+ return filter_args
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d35bc2a4467db0282790d67edca70fe9b5c0e1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/__init__.py
@@ -0,0 +1,50 @@
+"""Tracers are classes for tracing runs."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.tracers.base import BaseTracer
+ from langchain_core.tracers.evaluation import EvaluatorCallbackHandler
+ from langchain_core.tracers.langchain import LangChainTracer
+ from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ RunLog,
+ RunLogPatch,
+ )
+ from langchain_core.tracers.schemas import Run
+ from langchain_core.tracers.stdout import ConsoleCallbackHandler
+
+__all__ = (
+ "BaseTracer",
+ "ConsoleCallbackHandler",
+ "EvaluatorCallbackHandler",
+ "LangChainTracer",
+ "LogStreamCallbackHandler",
+ "Run",
+ "RunLog",
+ "RunLogPatch",
+)
+
+_dynamic_imports = {
+ "BaseTracer": "base",
+ "EvaluatorCallbackHandler": "evaluation",
+ "LangChainTracer": "langchain",
+ "LogStreamCallbackHandler": "log_stream",
+ "RunLog": "log_stream",
+ "RunLogPatch": "log_stream",
+ "Run": "schemas",
+ "ConsoleCallbackHandler": "stdout",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1401319013d53c07e10c7f24c2de0b3a8eaeae7e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..274c3d1f97375bfe2fb55ba721708727c6dbbedb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59252f077036bbb80e18ad66096882d86b082c28
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f09abd686c1052641e0bd7a538c17d7b20df76a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/context.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/context.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..155d1468e2bf6ecd3ac7e54c965643d71f13ee0a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/context.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/core.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/core.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00db298c08ece8093a6b484fe10740246ba1e7af
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/core.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c4ee1a0e1558423799a11da3916d0519e7f9332
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32f806ece1529d365fb320e0be7e6ad8fefa335d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..328273ed0f01b43a72c6094499f3cba2b3143c0e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b43e98634735e9294d4a62babcdaeb11b4367c99
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bda73752438f3788f1e4c1272e4f432127c3874f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbb1365f5c4fb5267c8735ec7a5237da7b325d11
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e45a4cdc0225691d682192e0a4af9444a5247ea1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fa030af80a1cd8dac6c92a000357091354799d8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73d173c3a4249b7f1c00a2af0633c7b2ab72d8f0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/_compat.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..54c2f49da034627c282dd37bb1fc30a91c53fc15
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/_compat.py
@@ -0,0 +1,95 @@
+"""Compatibility helpers for Pydantic v1/v2 with langsmith `Run` objects.
+
+!!! note
+
+ The generic helpers (`pydantic_to_dict`, `pydantic_copy`) detect Pydanti version
+ based on the langsmith `Run` model. They're intended for langsmith objects (`Run`,
+ `Example`) which migrate together.
+
+For general Pydantic v1/v2 handling, see `langchain_core.utils.pydantic`.
+"""
+
+from __future__ import annotations
+
+from typing import Any, TypeVar
+
+from langchain_core.tracers.schemas import Run
+
+# Detect Pydantic version once at import time based on Run model
+_RUN_IS_PYDANTIC_V2 = hasattr(Run, "model_dump")
+
+T = TypeVar("T")
+
+
+def run_to_dict(run: Run, **kwargs: Any) -> dict[str, Any]:
+ """Convert run to dict, compatible with both Pydantic v1 and v2.
+
+ Args:
+ run: The run to convert.
+ **kwargs: Additional arguments passed to `model_dump`/`dict`.
+
+ Returns:
+ Dictionary representation of the run.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return run.model_dump(**kwargs)
+ return run.dict(**kwargs) # type: ignore[deprecated]
+
+
+def run_copy(run: Run, **kwargs: Any) -> Run:
+ """Copy run, compatible with both Pydantic v1 and v2.
+
+ Args:
+ run: The run to copy.
+ **kwargs: Additional arguments passed to `model_copy`/`copy`.
+
+ Returns:
+ A copy of the run.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return run.model_copy(**kwargs)
+ return run.copy(**kwargs) # type: ignore[deprecated]
+
+
+def run_construct(**kwargs: Any) -> Run:
+ """Construct run without validation, compatible with both Pydantic v1 and v2.
+
+ Args:
+ **kwargs: Fields to set on the run.
+
+ Returns:
+ A new `Run` instance constructed without validation.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return Run.model_construct(**kwargs)
+ return Run.construct(**kwargs) # type: ignore[deprecated]
+
+
+def pydantic_to_dict(obj: Any, **kwargs: Any) -> dict[str, Any]:
+ """Convert any Pydantic model to dict, compatible with both v1 and v2.
+
+ Args:
+ obj: The Pydantic model to convert.
+ **kwargs: Additional arguments passed to `model_dump`/`dict`.
+
+ Returns:
+ Dictionary representation of the model.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return obj.model_dump(**kwargs) # type: ignore[no-any-return]
+ return obj.dict(**kwargs) # type: ignore[no-any-return]
+
+
+def pydantic_copy(obj: T, **kwargs: Any) -> T:
+ """Copy any Pydantic model, compatible with both v1 and v2.
+
+ Args:
+ obj: The Pydantic model to copy.
+ **kwargs: Additional arguments passed to `model_copy`/`copy`.
+
+ Returns:
+ A copy of the model.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return obj.model_copy(**kwargs) # type: ignore[attr-defined,no-any-return]
+ return obj.copy(**kwargs) # type: ignore[attr-defined,no-any-return]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/_streaming.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/_streaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5071bdc078689a61cc3f2b9da741b391e9327f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/_streaming.py
@@ -0,0 +1,53 @@
+"""Internal tracers used for `stream_log` and `astream` events implementations."""
+
+import typing
+from collections.abc import AsyncIterator, Iterator
+from uuid import UUID
+
+T = typing.TypeVar("T")
+
+
+# THIS IS USED IN LANGGRAPH.
+@typing.runtime_checkable
+class _StreamingCallbackHandler(typing.Protocol[T]):
+ """Types for streaming callback handlers.
+
+ This is a common mixin that the callback handlers for both astream events and
+ astream log inherit from.
+
+ The `tap_output_aiter` method is invoked in some contexts to produce callbacks for
+ intermediate results.
+ """
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Used for internal astream_log and astream events implementations."""
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Used for internal astream_log and astream events implementations."""
+
+
+# THIS IS USED IN LANGGRAPH.
+class _V2StreamingCallbackHandler:
+ """Marker base class for handlers that consume `on_stream_event` (v2).
+
+ A handler inheriting from this class signals that it wants content-
+ block lifecycle events from `stream_events(version="v3")` (and its
+ async equivalent) rather than the v1 `on_llm_new_token` chunks.
+ `BaseChatModel.invoke` uses
+ `isinstance(handler, _V2StreamingCallbackHandler)` to decide whether
+ to route an invoke through the v2 event generator.
+
+ Implemented as a concrete marker class (not a `Protocol`) so opt-in
+ is explicit via inheritance. An empty `runtime_checkable` Protocol
+ would match every object and misroute every call. The event
+ delivery contract itself lives on
+ `BaseCallbackHandler.on_stream_event`.
+ """
+
+
+__all__ = [
+ "_StreamingCallbackHandler",
+ "_V2StreamingCallbackHandler",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/base.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..b52420f0d844168becbb52ac6e9131b12c3b587f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/base.py
@@ -0,0 +1,955 @@
+"""Base interfaces for tracing runs."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from abc import ABC, abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandler
+from langchain_core.exceptions import TracerException # noqa: F401
+from langchain_core.tracers.core import _TracerCore
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+ from uuid import UUID
+
+ from tenacity import RetryCallState
+
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+
+class BaseTracer(_TracerCore, BaseCallbackHandler, ABC):
+ """Base interface for tracers."""
+
+ @abstractmethod
+ def _persist_run(self, run: Run) -> None:
+ """Persist a run."""
+
+ def _start_trace(self, run: Run) -> None:
+ """Start a trace for a run."""
+ super()._start_trace(run)
+ self._on_run_create(run)
+
+ def _end_trace(self, run: Run) -> None:
+ """End a trace for a run."""
+ if not run.parent_run_id:
+ self._persist_run(run)
+ self.run_map.pop(str(run.id))
+ # If this run's parent was injected from an external tracing context
+ # (e.g. a langsmith @traceable), decrement its child refcount and
+ # remove it from run_map once the last child is done.
+ parent_id = str(run.parent_run_id) if run.parent_run_id else None
+ if parent_id and parent_id in self._external_run_ids:
+ self._external_run_ids[parent_id] -= 1
+ if self._external_run_ids[parent_id] <= 0:
+ self.run_map.pop(parent_id, None)
+ del self._external_run_ids[parent_id]
+ self._on_run_update(run)
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a chat model run.
+
+ Note:
+ Naming can be confusing here: there is `on_chat_model_start`, but no
+ corresponding `on_chat_model_end` callback. Chat model completion is
+ routed through `on_llm_end` / `_on_llm_end`, which are shared with
+ text LLM runs.
+
+ Args:
+ serialized: The serialized model.
+ messages: The messages to start the chat with.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chat_model_run = self._create_chat_model_run(
+ serialized=serialized,
+ messages=messages,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(chat_model_run)
+ self._on_chat_model_start(chat_model_run)
+ return chat_model_run
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for an LLM run.
+
+ Args:
+ serialized: The serialized model.
+ prompts: The prompts to start the LLM with.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ llm_run = self._create_llm_run(
+ serialized=serialized,
+ prompts=prompts,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(llm_run)
+ self._on_llm_start(llm_run)
+ return llm_run
+
+ @override
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Run on new LLM token.
+
+ Only available when streaming is enabled.
+
+ Args:
+ token: The token.
+ chunk: The chunk.
+ run_id: The run ID.
+ parent_run_id: The parent run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._llm_run_with_token_event(
+ token=token,
+ run_id=run_id,
+ chunk=chunk,
+ parent_run_id=parent_run_id,
+ )
+ self._on_llm_new_token(llm_run, token, chunk)
+ return llm_run
+
+ @override
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Run on retry.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ return self._llm_run_with_retry_event(
+ retry_state=retry_state,
+ run_id=run_id,
+ )
+
+ @override
+ def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any) -> Run:
+ """End a trace for an LLM or chat model run.
+
+ Note:
+ This is the end callback for both run types. Chat models start with
+ `on_chat_model_start`, but there is no `on_chat_model_end`;
+ completion is routed here for callback API compatibility.
+
+ Args:
+ response: The response.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._complete_llm_run(
+ response=response,
+ run_id=run_id,
+ )
+ self._end_trace(llm_run)
+ self._on_llm_end(llm_run)
+ return llm_run
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for an LLM run.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._errored_llm_run(
+ error=error, run_id=run_id, response=kwargs.pop("response", None)
+ )
+ self._end_trace(llm_run)
+ self._on_llm_error(llm_run)
+ return llm_run
+
+ @override
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a chain run.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs for the chain.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ run_type: The type of the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._create_chain_run(
+ serialized=serialized,
+ inputs=inputs,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ run_type=run_type,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(chain_run)
+ self._on_chain_start(chain_run)
+ return chain_run
+
+ @override
+ def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """End a trace for a chain run.
+
+ Args:
+ outputs: The outputs for the chain.
+ run_id: The run ID.
+ inputs: The inputs for the chain.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._complete_chain_run(
+ outputs=outputs,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ self._end_trace(chain_run)
+ self._on_chain_end(chain_run)
+ return chain_run
+
+ @override
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ inputs: dict[str, Any] | None = None,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for a chain run.
+
+ Args:
+ error: The error.
+ inputs: The inputs for the chain.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._errored_chain_run(
+ error=error,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ self._end_trace(chain_run)
+ self._on_chain_error(chain_run)
+ return chain_run
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a tool run.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ inputs: The inputs for the tool.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._create_tool_run(
+ serialized=serialized,
+ input_str=input_str,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ name=name,
+ inputs=inputs,
+ **kwargs,
+ )
+ self._start_trace(tool_run)
+ self._on_tool_start(tool_run)
+ return tool_run
+
+ @override
+ def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> Run:
+ """End a trace for a tool run.
+
+ Args:
+ output: The output for the tool.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._complete_tool_run(
+ output=output,
+ run_id=run_id,
+ )
+ self._end_trace(tool_run)
+ self._on_tool_end(tool_run)
+ return tool_run
+
+ @override
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for a tool run.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._errored_tool_run(
+ error=error,
+ run_id=run_id,
+ )
+ self._end_trace(tool_run)
+ self._on_tool_error(tool_run)
+ return tool_run
+
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Run when the `Retriever` starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The run ID.
+ parent_run_id: The parent run ID.
+ tags: The tags for the run.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._create_retrieval_run(
+ serialized=serialized,
+ query=query,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(retrieval_run)
+ self._on_retriever_start(retrieval_run)
+ return retrieval_run
+
+ @override
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Run when `Retriever` errors.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._errored_retrieval_run(
+ error=error,
+ run_id=run_id,
+ )
+ self._end_trace(retrieval_run)
+ self._on_retriever_error(retrieval_run)
+ return retrieval_run
+
+ @override
+ def on_retriever_end(
+ self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any
+ ) -> Run:
+ """Run when the `Retriever` ends running.
+
+ Args:
+ documents: The documents.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._complete_retrieval_run(
+ documents=documents,
+ run_id=run_id,
+ )
+ self._end_trace(retrieval_run)
+ self._on_retriever_end(retrieval_run)
+ return retrieval_run
+
+ def __deepcopy__(self, memo: dict) -> BaseTracer:
+ """Return self."""
+ return self
+
+ def __copy__(self) -> BaseTracer:
+ """Return self."""
+ return self
+
+
+class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
+ """Async base interface for tracers."""
+
+ @abstractmethod
+ @override
+ async def _persist_run(self, run: Run) -> None:
+ """Persist a run."""
+
+ @override
+ async def _start_trace(self, run: Run) -> None:
+ """Start a trace for a run.
+
+ Starting a trace will run concurrently with each `_on_[run_type]_start` method.
+ No `_on_[run_type]_start` callback should depend on operations in
+ `_start_trace`.
+ """
+ super()._start_trace(run)
+ await self._on_run_create(run)
+
+ @override
+ async def _end_trace(self, run: Run) -> None:
+ """End a trace for a run.
+
+ Ending a trace will run concurrently with each `_on_[run_type]_end` method.
+ No `_on_[run_type]_end` callback should depend on operations in `_end_trace`.
+ """
+ if not run.parent_run_id:
+ await self._persist_run(run)
+ self.run_map.pop(str(run.id))
+ # If this run's parent was injected from an external tracing context
+ # (e.g. a langsmith @traceable), decrement its child refcount and
+ # remove it from run_map once the last child is done.
+ parent_id = str(run.parent_run_id) if run.parent_run_id else None
+ if parent_id and parent_id in self._external_run_ids:
+ self._external_run_ids[parent_id] -= 1
+ if self._external_run_ids[parent_id] <= 0:
+ self.run_map.pop(parent_id, None)
+ del self._external_run_ids[parent_id]
+ await self._on_run_update(run)
+
+ @override
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ chat_model_run = self._create_chat_model_run(
+ serialized=serialized,
+ messages=messages,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ tasks = [
+ self._start_trace(chat_model_run),
+ self._on_chat_model_start(chat_model_run),
+ ]
+ await asyncio.gather(*tasks)
+ return chat_model_run
+
+ @override
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._create_llm_run(
+ serialized=serialized,
+ prompts=prompts,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ **kwargs,
+ )
+ tasks = [self._start_trace(llm_run), self._on_llm_start(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._llm_run_with_token_event(
+ token=token,
+ run_id=run_id,
+ chunk=chunk,
+ parent_run_id=parent_run_id,
+ )
+ await self._on_llm_new_token(llm_run, token, chunk)
+
+ @override
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ self._llm_run_with_retry_event(
+ retry_state=retry_state,
+ run_id=run_id,
+ )
+
+ @override
+ async def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """End a trace for an LLM or chat model run.
+
+ Note:
+ This async callback also handles both run types. Async chat models
+ start with `on_chat_model_start`, but there is no
+ `on_chat_model_end`; completion is routed here for callback API
+ compatibility.
+ """
+ llm_run = self._complete_llm_run(
+ response=response,
+ run_id=run_id,
+ )
+ tasks = [self._on_llm_end(llm_run), self._end_trace(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._errored_llm_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [self._on_llm_error(llm_run), self._end_trace(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._create_chain_run(
+ serialized=serialized,
+ inputs=inputs,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ run_type=run_type,
+ name=name,
+ **kwargs,
+ )
+ tasks = [self._start_trace(chain_run), self._on_chain_start(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._complete_chain_run(
+ outputs=outputs,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ tasks = [self._end_trace(chain_run), self._on_chain_end(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ inputs: dict[str, Any] | None = None,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._errored_chain_run(
+ error=error,
+ inputs=inputs,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(chain_run), self._on_chain_error(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._create_tool_run(
+ serialized=serialized,
+ input_str=input_str,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ inputs=inputs,
+ **kwargs,
+ )
+ tasks = [self._start_trace(tool_run), self._on_tool_start(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._complete_tool_run(
+ output=output,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(tool_run), self._on_tool_end(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._errored_tool_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(tool_run), self._on_tool_error(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retriever_run = self._create_retrieval_run(
+ serialized=serialized,
+ query=query,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ )
+ tasks = [
+ self._start_trace(retriever_run),
+ self._on_retriever_start(retriever_run),
+ ]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retrieval_run = self._errored_retrieval_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [
+ self._end_trace(retrieval_run),
+ self._on_retriever_error(retrieval_run),
+ ]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retrieval_run = self._complete_retrieval_run(
+ documents=documents,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(retrieval_run), self._on_retriever_end(retrieval_run)]
+ await asyncio.gather(*tasks)
+
+ async def _on_run_create(self, run: Run) -> None:
+ """Process a run upon creation."""
+
+ async def _on_run_update(self, run: Run) -> None:
+ """Process a run upon update."""
+
+ async def _on_llm_start(self, run: Run) -> None:
+ """Process the LLM Run upon start."""
+
+ async def _on_llm_end(self, run: Run) -> None:
+ """Process LLM/chat model run completion."""
+
+ async def _on_llm_error(self, run: Run) -> None:
+ """Process the LLM Run upon error."""
+
+ async def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> None:
+ """Process new LLM token."""
+
+ async def _on_chain_start(self, run: Run) -> None:
+ """Process the Chain Run upon start."""
+
+ async def _on_chain_end(self, run: Run) -> None:
+ """Process the Chain Run."""
+
+ async def _on_chain_error(self, run: Run) -> None:
+ """Process the Chain Run upon error."""
+
+ async def _on_tool_start(self, run: Run) -> None:
+ """Process the Tool Run upon start."""
+
+ async def _on_tool_end(self, run: Run) -> None:
+ """Process the Tool Run."""
+
+ async def _on_tool_error(self, run: Run) -> None:
+ """Process the Tool Run upon error."""
+
+ async def _on_chat_model_start(self, run: Run) -> None:
+ """Process the Chat Model Run upon start."""
+
+ async def _on_retriever_start(self, run: Run) -> None:
+ """Process the Retriever Run upon start."""
+
+ async def _on_retriever_end(self, run: Run) -> None:
+ """Process the Retriever Run."""
+
+ async def _on_retriever_error(self, run: Run) -> None:
+ """Process the Retriever Run upon error."""
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/context.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ad17663910fdd7bd19bcdfe786e27ad438b7276
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/context.py
@@ -0,0 +1,205 @@
+"""Context management for tracers."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+from uuid import UUID
+
+from langsmith import run_helpers as ls_rh
+from langsmith import utils as ls_utils
+
+from langchain_core.tracers.langchain import LangChainTracer
+from langchain_core.tracers.run_collector import RunCollectorCallbackHandler
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+ from langsmith import Client as LangSmithClient
+
+ from langchain_core.callbacks.base import BaseCallbackHandler, Callbacks
+ from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+
+# for backwards partial compatibility if this is imported by users but unused
+tracing_callback_var: Any = None
+tracing_v2_callback_var: ContextVar[LangChainTracer | None] = ContextVar(
+ "tracing_callback_v2", default=None
+)
+run_collector_var: ContextVar[RunCollectorCallbackHandler | None] = ContextVar(
+ "run_collector", default=None
+)
+
+
+@contextmanager
+def tracing_v2_enabled(
+ project_name: str | None = None,
+ *,
+ example_id: str | UUID | None = None,
+ tags: list[str] | None = None,
+ client: LangSmithClient | None = None,
+) -> Generator[LangChainTracer, None, None]:
+ """Instruct LangChain to log all runs in context to LangSmith.
+
+ Args:
+ project_name: The name of the project.
+
+ Defaults to `'default'`.
+ example_id: The ID of the example.
+ tags: The tags to add to the run.
+ client: The client of the langsmith.
+
+ Yields:
+ The LangChain tracer.
+
+ Example:
+ >>> with tracing_v2_enabled():
+ ... # LangChain code will automatically be traced
+
+ You can use this to fetch the LangSmith run URL:
+
+ >>> with tracing_v2_enabled() as cb:
+ ... chain.invoke("foo")
+ ... run_url = cb.get_run_url()
+ """
+ if isinstance(example_id, str):
+ example_id = UUID(example_id)
+ cb = LangChainTracer(
+ example_id=example_id,
+ project_name=project_name,
+ tags=tags,
+ client=client,
+ )
+ token = tracing_v2_callback_var.set(cb)
+ try:
+ yield cb
+ finally:
+ tracing_v2_callback_var.reset(token)
+
+
+@contextmanager
+def collect_runs() -> Generator[RunCollectorCallbackHandler, None, None]:
+ """Collect all run traces in context.
+
+ Yields:
+ The run collector callback handler.
+
+ Example:
+ >>> with collect_runs() as runs_cb:
+ chain.invoke("foo")
+ run_id = runs_cb.traced_runs[0].id
+ """
+ cb = RunCollectorCallbackHandler()
+ token = run_collector_var.set(cb)
+ try:
+ yield cb
+ finally:
+ run_collector_var.reset(token)
+
+
+def _get_trace_callbacks(
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ callback_manager: CallbackManager | AsyncCallbackManager | None = None,
+) -> Callbacks:
+ if _tracing_v2_is_enabled():
+ project_name_ = project_name or _get_tracer_project()
+ tracer = tracing_v2_callback_var.get() or LangChainTracer(
+ project_name=project_name_,
+ example_id=example_id,
+ )
+ if callback_manager is None:
+ cb = cast("Callbacks", [tracer])
+ else:
+ if not any(
+ isinstance(handler, LangChainTracer)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(tracer)
+ # If it already has a LangChainTracer, we don't need to add another one.
+ # this would likely mess up the trace hierarchy.
+ cb = callback_manager
+ else:
+ cb = None
+ return cb
+
+
+def _tracing_v2_is_enabled() -> bool | Literal["local"]:
+ if tracing_v2_callback_var.get() is not None:
+ return True
+ return ls_utils.tracing_is_enabled()
+
+
+def _get_tracer_project() -> str:
+ tracing_context = ls_rh.get_tracing_context()
+ run_tree = tracing_context["parent"]
+ if run_tree is None and tracing_context["project_name"] is not None:
+ return cast("str", tracing_context["project_name"])
+ return getattr(
+ run_tree,
+ "session_name",
+ getattr(
+ # Note, if people are trying to nest @traceable functions and the
+ # tracing_v2_enabled context manager, this will likely mess up the
+ # tree structure.
+ tracing_v2_callback_var.get(),
+ "project",
+ # Have to set this to a string even though it always will return
+ # a string because `get_tracer_project` technically can return
+ # None, but only when a specific argument is supplied.
+ # Therefore, this just tricks the mypy type checker
+ str(ls_utils.get_tracer_project()),
+ ),
+ )
+
+
+_configure_hooks: list[
+ tuple[
+ ContextVar[BaseCallbackHandler | None],
+ bool,
+ type[BaseCallbackHandler] | None,
+ str | None,
+ ]
+] = []
+
+
+def register_configure_hook(
+ context_var: ContextVar[Any | None],
+ inheritable: bool, # noqa: FBT001
+ handle_class: type[BaseCallbackHandler] | None = None,
+ env_var: str | None = None,
+) -> None:
+ """Register a configure hook.
+
+ Args:
+ context_var: The context variable.
+ inheritable: Whether the context variable is inheritable.
+ handle_class: The callback handler class.
+ env_var: The environment variable.
+
+ Raises:
+ ValueError: If `env_var` is set, `handle_class` must also be set to a non-`None`
+ value.
+ """
+ if env_var is not None and handle_class is None:
+ msg = "If env_var is set, handle_class must also be set to a non-None value."
+ raise ValueError(msg)
+
+ _configure_hooks.append(
+ (
+ # the typings of ContextVar do not have the generic arg set as covariant
+ # so we have to cast it
+ cast("ContextVar[BaseCallbackHandler | None]", context_var),
+ inheritable,
+ handle_class,
+ env_var,
+ )
+ )
+
+
+register_configure_hook(run_collector_var, inheritable=False)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/core.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..75614e3c881de46c60a651b67523fd1797c706e8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/core.py
@@ -0,0 +1,724 @@
+"""Utilities for the root listener."""
+
+from __future__ import annotations
+
+import logging
+import traceback
+from abc import ABC, abstractmethod
+from datetime import datetime, timezone
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+
+from langchain_core.exceptions import TracerException
+from langchain_core.load import dumpd
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from collections.abc import Coroutine, Sequence
+ from uuid import UUID
+
+ from tenacity import RetryCallState
+
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ GenerationChunk,
+ LLMResult,
+ )
+
+logger = logging.getLogger(__name__)
+
+SCHEMA_FORMAT_TYPE = Literal["original", "streaming_events"]
+
+
+class _TracerCore(ABC):
+ """Abstract base class for tracers.
+
+ This class provides common methods, and reusable methods for tracers.
+ """
+
+ log_missing_parent: bool = True
+
+ def __init__(
+ self,
+ *,
+ _schema_format: Literal[
+ "original", "streaming_events", "original+chat"
+ ] = "original",
+ run_map: dict[str, Run] | None = None,
+ order_map: dict[UUID, tuple[UUID, str]] | None = None,
+ _external_run_ids: dict[str, int] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ _schema_format: Primarily changes how the inputs and outputs are handled.
+
+ For internal use only. This API will change.
+
+ - `'original'` is the format used by all current tracers.
+
+ This format is slightly inconsistent with respect to inputs and
+ outputs.
+ - `'streaming_events'` is used for supporting streaming events, for
+ internal usage. It will likely change in the future, or be
+ deprecated entirely in favor of a dedicated async tracer for
+ streaming events.
+ - `'original+chat'` is a format that is the same as `'original'` except
+ it does NOT raise an attribute error `on_chat_model_start`
+ run_map: Optional shared map of run ID to run.
+ order_map: Optional shared map of run ID to trace ordering data.
+ _external_run_ids: Optional shared set of externally injected run IDs.
+ **kwargs: Additional keyword arguments that will be passed to the
+ superclass.
+ """
+ super().__init__(**kwargs)
+
+ self._schema_format = _schema_format # For internal use only API will change.
+
+ self.run_map = run_map if run_map is not None else {}
+ """Map of run ID to run. Cleared on run end."""
+
+ self.order_map = order_map if order_map is not None else {}
+ """Map of run ID to (trace_id, dotted_order). Cleared when tracer GCed."""
+
+ self._external_run_ids: dict[str, int] = (
+ _external_run_ids if _external_run_ids is not None else {}
+ )
+ """Refcount of active children per externally-injected run ID.
+
+ These runs are added to `run_map` so child runs can find their parent,
+ but they are not managed by the tracer's callback lifecycle. When
+ the last child finishes the entry is evicted to avoid memory leaks.
+ """
+
+ @abstractmethod
+ def _persist_run(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Persist a run."""
+
+ @staticmethod
+ def _add_child_run(
+ parent_run: Run,
+ child_run: Run,
+ ) -> None:
+ """Add child run to a chain run or tool run."""
+ parent_run.child_runs.append(child_run)
+
+ @staticmethod
+ def _get_stacktrace(error: BaseException) -> str:
+ """Get the stacktrace of the parent error."""
+ msg = repr(error)
+ try:
+ tb = traceback.format_exception(error)
+ return (msg + "\n\n".join(tb)).strip()
+ except Exception:
+ return msg
+
+ def _start_trace(self, run: Run) -> Coroutine[Any, Any, None] | None: # type: ignore[return]
+ current_dotted_order = run.start_time.strftime("%Y%m%dT%H%M%S%fZ") + str(run.id)
+ if run.parent_run_id:
+ if parent := self.order_map.get(run.parent_run_id):
+ run.trace_id, run.dotted_order = parent
+ run.dotted_order += "." + current_dotted_order
+ if parent_run := self.run_map.get(str(run.parent_run_id)):
+ self._add_child_run(parent_run, run)
+ parent_key = str(run.parent_run_id)
+ if parent_key in self._external_run_ids:
+ self._external_run_ids[parent_key] += 1
+ else:
+ if self.log_missing_parent:
+ logger.debug(
+ "Parent run %s not found for run %s. Treating as a root run.",
+ run.parent_run_id,
+ run.id,
+ )
+ run.parent_run_id = None
+ run.trace_id = run.id
+ run.dotted_order = current_dotted_order
+ else:
+ run.trace_id = run.id
+ run.dotted_order = current_dotted_order
+ self.order_map[run.id] = (run.trace_id, run.dotted_order)
+ self.run_map[str(run.id)] = run
+
+ def _get_run(self, run_id: UUID, run_type: str | set[str] | None = None) -> Run:
+ try:
+ run = self.run_map[str(run_id)]
+ except KeyError as exc:
+ msg = f"No indexed run ID {run_id}."
+ raise TracerException(msg) from exc
+
+ if isinstance(run_type, str):
+ run_types: set[str] | None = {run_type}
+ else:
+ run_types = run_type
+ if run_types is not None and run.run_type not in run_types:
+ msg = (
+ f"Found {run.run_type} run at ID {run_id}, "
+ f"but expected {run_types} run."
+ )
+ raise TracerException(msg)
+ return run
+
+ def _create_chat_model_run(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a chat model run."""
+ if self._schema_format not in {"streaming_events", "original+chat"}:
+ # Please keep this un-implemented for backwards compatibility.
+ # When it's unimplemented old tracers that use the "original" format
+ # fallback on the on_llm_start method implementation if they
+ # find that the on_chat_model_start method is not implemented.
+ # This can eventually be cleaned up by writing a "modern" tracer
+ # that has all the updated schema changes corresponding to
+ # the "streaming_events" format.
+ msg = (
+ f"Chat model tracing is not supported in "
+ f"for {self._schema_format} format."
+ )
+ raise NotImplementedError(msg)
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"messages": [[dumpd(msg) for msg in batch] for batch in messages]},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ # WARNING: This is valid ONLY for streaming_events.
+ # run_type="llm" is what's used by virtually all tracers.
+ # Changing this to "chat_model" may break triggering on_llm_start
+ run_type="chat_model",
+ tags=tags,
+ name=name,
+ )
+
+ def _create_llm_run(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a llm run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ # TODO: Figure out how to expose kwargs here
+ inputs={"prompts": prompts},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ run_type="llm",
+ tags=tags or [],
+ name=name,
+ )
+
+ def _llm_run_with_token_event(
+ self,
+ token: str,
+ run_id: UUID,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ parent_run_id: UUID | None = None,
+ ) -> Run:
+ """Append token event to LLM run and return the run."""
+ _ = parent_run_id
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ event_kwargs: dict[str, Any] = {"token": token}
+ if chunk:
+ event_kwargs["chunk"] = chunk
+ llm_run.events.append(
+ {
+ "name": "new_token",
+ "time": datetime.now(timezone.utc),
+ "kwargs": event_kwargs,
+ },
+ )
+ return llm_run
+
+ def _llm_run_with_retry_event(
+ self,
+ retry_state: RetryCallState,
+ run_id: UUID,
+ ) -> Run:
+ llm_run = self._get_run(run_id)
+ retry_d: dict[str, Any] = {
+ "slept": retry_state.idle_for,
+ "attempt": retry_state.attempt_number,
+ }
+ if retry_state.outcome is None:
+ retry_d["outcome"] = "N/A"
+ elif retry_state.outcome.failed:
+ retry_d["outcome"] = "failed"
+ exception = retry_state.outcome.exception()
+ retry_d["exception"] = str(exception)
+ retry_d["exception_type"] = exception.__class__.__name__
+ else:
+ retry_d["outcome"] = "success"
+ retry_d["result"] = str(retry_state.outcome.result())
+ llm_run.events.append(
+ {
+ "name": "retry",
+ "time": datetime.now(timezone.utc),
+ "kwargs": retry_d,
+ },
+ )
+ return llm_run
+
+ def _complete_llm_run(self, response: LLMResult, run_id: UUID) -> Run:
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ if getattr(llm_run, "outputs", None) is None:
+ llm_run.outputs = {}
+ else:
+ llm_run.outputs = cast("dict[str, Any]", llm_run.outputs)
+ if not llm_run.extra.get("__omit_auto_outputs", False):
+ llm_run.outputs.update(response.model_dump())
+ for i, generations in enumerate(response.generations):
+ for j, generation in enumerate(generations):
+ output_generation = llm_run.outputs["generations"][i][j]
+ if "message" in output_generation:
+ output_generation["message"] = dumpd(
+ cast("ChatGeneration", generation).message
+ )
+ llm_run.end_time = datetime.now(timezone.utc)
+ llm_run.events.append({"name": "end", "time": llm_run.end_time})
+
+ tool_call_count = 0
+ for generations in response.generations:
+ for generation in generations:
+ if hasattr(generation, "message"):
+ msg = generation.message
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
+ tool_call_count += len(msg.tool_calls)
+ if tool_call_count > 0:
+ llm_run.extra["tool_call_count"] = tool_call_count
+
+ return llm_run
+
+ def _errored_llm_run(
+ self, error: BaseException, run_id: UUID, response: LLMResult | None = None
+ ) -> Run:
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ llm_run.error = self._get_stacktrace(error)
+ if response:
+ if getattr(llm_run, "outputs", None) is None:
+ llm_run.outputs = {}
+ else:
+ llm_run.outputs = cast("dict[str, Any]", llm_run.outputs)
+ if not llm_run.extra.get("__omit_auto_outputs", False):
+ llm_run.outputs.update(response.model_dump())
+ for i, generations in enumerate(response.generations):
+ for j, generation in enumerate(generations):
+ output_generation = llm_run.outputs["generations"][i][j]
+ if "message" in output_generation:
+ output_generation["message"] = dumpd(
+ cast("ChatGeneration", generation).message
+ )
+ llm_run.end_time = datetime.now(timezone.utc)
+ llm_run.events.append({"name": "error", "time": llm_run.end_time})
+
+ return llm_run
+
+ def _create_chain_run(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a chain Run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs=self._get_chain_inputs(inputs),
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ child_runs=[],
+ run_type=run_type or "chain",
+ name=name,
+ tags=tags or [],
+ )
+
+ def _get_chain_inputs(self, inputs: Any) -> Any:
+ """Get the inputs for a chain run."""
+ if self._schema_format in {"original", "original+chat"}:
+ return inputs if isinstance(inputs, dict) else {"input": inputs}
+ if self._schema_format == "streaming_events":
+ return {
+ "input": inputs,
+ }
+ msg = f"Invalid format: {self._schema_format}"
+ raise ValueError(msg)
+
+ def _get_chain_outputs(self, outputs: Any) -> Any:
+ """Get the outputs for a chain run."""
+ if self._schema_format in {"original", "original+chat"}:
+ return outputs if isinstance(outputs, dict) else {"output": outputs}
+ if self._schema_format == "streaming_events":
+ return {
+ "output": outputs,
+ }
+ msg = f"Invalid format: {self._schema_format}"
+ raise ValueError(msg)
+
+ def _complete_chain_run(
+ self,
+ outputs: dict[str, Any],
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ ) -> Run:
+ """Update a chain run with outputs and end time."""
+ chain_run = self._get_run(run_id)
+ if getattr(chain_run, "outputs", None) is None:
+ chain_run.outputs = {}
+ if not chain_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", chain_run.outputs).update(
+ self._get_chain_outputs(outputs)
+ )
+ chain_run.end_time = datetime.now(timezone.utc)
+ chain_run.events.append({"name": "end", "time": chain_run.end_time})
+ if inputs is not None:
+ chain_run.inputs = self._get_chain_inputs(inputs)
+ return chain_run
+
+ def _errored_chain_run(
+ self,
+ error: BaseException,
+ inputs: dict[str, Any] | None,
+ run_id: UUID,
+ ) -> Run:
+ chain_run = self._get_run(run_id)
+ chain_run.error = self._get_stacktrace(error)
+ chain_run.end_time = datetime.now(timezone.utc)
+ chain_run.events.append({"name": "error", "time": chain_run.end_time})
+ if inputs is not None:
+ chain_run.inputs = self._get_chain_inputs(inputs)
+ return chain_run
+
+ def _create_tool_run(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a tool run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+
+ if self._schema_format in {"original", "original+chat"}:
+ inputs = inputs if isinstance(inputs, dict) else {"input": input_str}
+ elif self._schema_format == "streaming_events":
+ inputs = {"input": inputs}
+ else:
+ msg = f"Invalid format: {self._schema_format}"
+ raise AssertionError(msg)
+
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ # Wrapping in dict since Run requires a dict object.
+ inputs=inputs,
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ child_runs=[],
+ run_type="tool",
+ tags=tags or [],
+ name=name,
+ )
+
+ def _complete_tool_run(
+ self,
+ output: dict[str, Any],
+ run_id: UUID,
+ ) -> Run:
+ """Update a tool run with outputs and end time."""
+ tool_run = self._get_run(run_id, run_type="tool")
+ if getattr(tool_run, "outputs", None) is None:
+ tool_run.outputs = {}
+ if not tool_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", tool_run.outputs).update({"output": output})
+ tool_run.end_time = datetime.now(timezone.utc)
+ tool_run.events.append({"name": "end", "time": tool_run.end_time})
+ return tool_run
+
+ def _errored_tool_run(
+ self,
+ error: BaseException,
+ run_id: UUID,
+ ) -> Run:
+ """Update a tool run with error and end time."""
+ tool_run = self._get_run(run_id, run_type="tool")
+ tool_run.error = self._get_stacktrace(error)
+ tool_run.end_time = datetime.now(timezone.utc)
+ tool_run.events.append({"name": "error", "time": tool_run.end_time})
+ return tool_run
+
+ def _create_retrieval_run(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a retrieval run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ name=name or "Retriever",
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"query": query},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ tags=tags,
+ child_runs=[],
+ run_type="retriever",
+ )
+
+ def _complete_retrieval_run(
+ self,
+ documents: Sequence[Document],
+ run_id: UUID,
+ ) -> Run:
+ """Update a retrieval run with outputs and end time."""
+ retrieval_run = self._get_run(run_id, run_type="retriever")
+ if getattr(retrieval_run, "outputs", None) is None:
+ retrieval_run.outputs = {}
+ if not retrieval_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", retrieval_run.outputs).update(
+ {"documents": documents}
+ )
+ retrieval_run.end_time = datetime.now(timezone.utc)
+ retrieval_run.events.append({"name": "end", "time": retrieval_run.end_time})
+ return retrieval_run
+
+ def _errored_retrieval_run(
+ self,
+ error: BaseException,
+ run_id: UUID,
+ ) -> Run:
+ retrieval_run = self._get_run(run_id, run_type="retriever")
+ retrieval_run.error = self._get_stacktrace(error)
+ retrieval_run.end_time = datetime.now(timezone.utc)
+ retrieval_run.events.append({"name": "error", "time": retrieval_run.end_time})
+ return retrieval_run
+
+ def __deepcopy__(self, memo: dict) -> _TracerCore:
+ """Return self deepcopied."""
+ return self
+
+ def __copy__(self) -> _TracerCore:
+ """Return self copied."""
+ return self
+
+ def _end_trace(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """End a trace for a run.
+
+ Args:
+ run: The run.
+ """
+ _ = run
+ return None
+
+ def _on_run_create(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process a run upon creation.
+
+ Args:
+ run: The created run.
+ """
+ _ = run
+ return None
+
+ def _on_run_update(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process a run upon update.
+
+ Args:
+ run: The updated run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run upon start.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> Coroutine[Any, Any, None] | None:
+ """Process new LLM token.
+
+ Args:
+ run: The LLM run.
+ token: The new token.
+ chunk: Optional chunk.
+ """
+ _ = (run, token, chunk)
+ return None
+
+ def _on_llm_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run upon error.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run upon start.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run upon error.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run upon start.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run upon error.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_chat_model_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chat Model Run upon start.
+
+ Args:
+ run: The chat model run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run upon start.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run upon error.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/evaluation.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/evaluation.py
new file mode 100644
index 0000000000000000000000000000000000000000..22c6f600f58c4ed38ee9e876c656e30172fe6b99
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/evaluation.py
@@ -0,0 +1,226 @@
+"""A tracer that runs evaluators over completed runs."""
+
+from __future__ import annotations
+
+import logging
+import threading
+import weakref
+from concurrent.futures import Future, ThreadPoolExecutor, wait
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
+
+import langsmith
+from langsmith.evaluation.evaluator import EvaluationResult, EvaluationResults
+
+from langchain_core.tracers import langchain as langchain_tracer
+from langchain_core.tracers._compat import run_copy
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.context import tracing_v2_enabled
+from langchain_core.tracers.langchain import _get_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+_TRACERS: weakref.WeakSet[EvaluatorCallbackHandler] = weakref.WeakSet()
+
+
+def wait_for_all_evaluators() -> None:
+ """Wait for all tracers to finish."""
+ for tracer in list(_TRACERS):
+ if tracer is not None:
+ tracer.wait_for_futures()
+
+
+class EvaluatorCallbackHandler(BaseTracer):
+ """Tracer that runs a run evaluator whenever a run is persisted.
+
+ Attributes:
+ client: The LangSmith client instance used for evaluating the runs.
+ """
+
+ name: str = "evaluator_callback_handler"
+
+ example_id: UUID | None = None
+ """The example ID associated with the runs."""
+
+ client: langsmith.Client
+ """The LangSmith client instance used for evaluating the runs."""
+
+ evaluators: Sequence[langsmith.RunEvaluator] = ()
+ """The sequence of run evaluators to be executed."""
+
+ executor: ThreadPoolExecutor | None = None
+ """The thread pool executor used for running the evaluators."""
+
+ futures: weakref.WeakSet[Future] = weakref.WeakSet()
+ """The set of futures representing the running evaluators."""
+
+ skip_unfinished: bool = True
+ """Whether to skip runs that are not finished or raised an error."""
+
+ project_name: str | None = None
+ """The LangSmith project name to be organize eval chain runs under."""
+
+ logged_eval_results: dict[tuple[str, str], list[EvaluationResult]]
+
+ lock: threading.Lock
+
+ def __init__(
+ self,
+ evaluators: Sequence[langsmith.RunEvaluator],
+ client: langsmith.Client | None = None,
+ example_id: UUID | str | None = None,
+ skip_unfinished: bool = True, # noqa: FBT001,FBT002
+ project_name: str | None = "evaluators",
+ max_concurrency: int | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Create an EvaluatorCallbackHandler.
+
+ Args:
+ evaluators: The run evaluators to apply to all top level runs.
+ client: The LangSmith client instance to use for evaluating the runs.
+
+ If not specified, a new instance will be created.
+ example_id: The example ID to be associated with the runs.
+ skip_unfinished: Whether to skip unfinished runs.
+ project_name: The LangSmith project name to be organize eval chain runs
+ under.
+ max_concurrency: The maximum number of concurrent evaluators to run.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.client = client or langchain_tracer.get_client()
+ self.evaluators = evaluators
+ if max_concurrency is None:
+ self.executor = _get_executor()
+ elif max_concurrency > 0:
+ self.executor = ThreadPoolExecutor(max_workers=max_concurrency)
+ weakref.finalize(
+ self,
+ lambda: cast("ThreadPoolExecutor", self.executor).shutdown(wait=True),
+ )
+ else:
+ self.executor = None
+ self.futures = weakref.WeakSet[Future[None]]()
+ self.skip_unfinished = skip_unfinished
+ self.project_name = project_name
+ self.logged_eval_results = {}
+ self.lock = threading.Lock()
+ _TRACERS.add(self)
+
+ def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> None:
+ """Evaluate the run in the project.
+
+ Args:
+ run: The run to be evaluated.
+ evaluator: The evaluator to use for evaluating the run.
+ """
+ try:
+ if self.project_name is None:
+ eval_result = self.client.evaluate_run(run, evaluator)
+ eval_results = [eval_result]
+ with tracing_v2_enabled(
+ project_name=self.project_name, tags=["eval"], client=self.client
+ ) as cb:
+ reference_example = (
+ self.client.read_example(run.reference_example_id)
+ if run.reference_example_id
+ else None
+ )
+ evaluation_result = evaluator.evaluate_run(
+ # This is subclass, but getting errors for some reason
+ run, # type: ignore[arg-type]
+ example=reference_example,
+ )
+ eval_results = self._log_evaluation_feedback(
+ evaluation_result,
+ run,
+ source_run_id=cb.latest_run.id if cb.latest_run else None,
+ )
+ except Exception:
+ logger.exception(
+ "Error evaluating run %s with %s",
+ run.id,
+ evaluator.__class__.__name__,
+ )
+ raise
+ example_id = str(run.reference_example_id)
+ with self.lock:
+ for res in eval_results:
+ run_id = str(getattr(res, "target_run_id", run.id))
+ self.logged_eval_results.setdefault((run_id, example_id), []).append(
+ res
+ )
+
+ @staticmethod
+ def _select_eval_results(
+ results: EvaluationResult | EvaluationResults,
+ ) -> list[EvaluationResult]:
+ if isinstance(results, EvaluationResult):
+ results_ = [results]
+ elif isinstance(results, dict) and "results" in results:
+ results_ = results["results"]
+ else:
+ msg = (
+ f"Invalid evaluation result type {type(results)}."
+ " Expected EvaluationResult or EvaluationResults."
+ )
+ raise TypeError(msg)
+ return results_
+
+ def _log_evaluation_feedback(
+ self,
+ evaluator_response: EvaluationResult | EvaluationResults,
+ run: Run,
+ source_run_id: UUID | None = None,
+ ) -> list[EvaluationResult]:
+ results = self._select_eval_results(evaluator_response)
+ for res in results:
+ source_info_: dict[str, Any] = {}
+ if res.evaluator_info:
+ source_info_ = {**res.evaluator_info, **source_info_}
+ run_id_ = getattr(res, "target_run_id", None)
+ if run_id_ is None:
+ run_id_ = run.id
+ self.client.create_feedback(
+ run_id_,
+ res.key,
+ score=res.score,
+ value=res.value,
+ comment=res.comment,
+ correction=res.correction,
+ source_info=source_info_,
+ source_run_id=res.source_run_id or source_run_id,
+ feedback_source_type=langsmith.schemas.FeedbackSourceType.MODEL,
+ )
+ return results
+
+ def _persist_run(self, run: Run) -> None:
+ """Run the evaluator on the run.
+
+ Args:
+ run: The run to be evaluated.
+ """
+ if self.skip_unfinished and not run.outputs:
+ logger.debug("Skipping unfinished run %s", run.id)
+ return
+ run_ = run_copy(run)
+ run_.reference_example_id = self.example_id
+ for evaluator in self.evaluators:
+ if self.executor is None:
+ self._evaluate_in_project(run_, evaluator)
+ else:
+ self.futures.add(
+ self.executor.submit(self._evaluate_in_project, run_, evaluator)
+ )
+
+ def wait_for_futures(self) -> None:
+ """Wait for all futures to complete."""
+ wait(self.futures)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/event_stream.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/event_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..399a7c19b6eb9db32a6db602bf33b703c42217c5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/event_stream.py
@@ -0,0 +1,1100 @@
+"""Internal tracer to power the event stream API."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypedDict,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import NotRequired, override
+
+from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackManager
+from langchain_core.messages import AIMessageChunk, BaseMessage, BaseMessageChunk
+from langchain_core.outputs import (
+ ChatGenerationChunk,
+ GenerationChunk,
+ LLMResult,
+)
+from langchain_core.runnables import ensure_config
+from langchain_core.runnables.schema import (
+ CustomStreamEvent,
+ EventData,
+ StandardStreamEvent,
+ StreamEvent,
+)
+from langchain_core.runnables.utils import (
+ Input,
+ Output,
+ _RootEventFilter,
+)
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ RunLog,
+ _astream_log_implementation,
+)
+from langchain_core.tracers.memory_stream import _MemoryStream
+from langchain_core.utils.aiter import aclosing
+from langchain_core.utils.uuid import uuid7
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Sequence
+ from uuid import UUID
+
+ from langchain_core.documents import Document
+ from langchain_core.runnables import Runnable, RunnableConfig
+ from langchain_core.tracers.log_stream import LogEntry
+
+logger = logging.getLogger(__name__)
+
+
+class RunInfo(TypedDict):
+ """Information about a run.
+
+ This is used to keep track of the metadata associated with a run.
+ """
+
+ name: str
+ """The name of the run."""
+
+ tags: list[str]
+ """The tags associated with the run."""
+
+ metadata: dict[str, Any]
+ """The metadata associated with the run."""
+
+ run_type: str
+ """The type of the run."""
+
+ inputs: NotRequired[Any]
+ """The inputs to the run."""
+
+ parent_run_id: UUID | None
+ """The ID of the parent run."""
+
+ tool_call_id: NotRequired[str | None]
+ """The tool call ID associated with the run."""
+
+
+def _assign_name(name: str | None, serialized: dict[str, Any] | None) -> str:
+ """Assign a name to a run."""
+ if name is not None:
+ return name
+ if serialized is not None:
+ if "name" in serialized:
+ return cast("str", serialized["name"])
+ if "id" in serialized:
+ return cast("str", serialized["id"][-1])
+ return "Unnamed"
+
+
+T = TypeVar("T")
+
+
+class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHandler):
+ """An implementation of an async callback handler for astream events."""
+
+ def __init__(
+ self,
+ *args: Any,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the tracer."""
+ super().__init__(*args, **kwargs)
+ # Map of run ID to run info.
+ # the entry corresponding to a given run id is cleaned
+ # up when each corresponding run ends.
+ self.run_map: dict[UUID, RunInfo] = {}
+ # The callback event that corresponds to the end of a parent run
+ # may be invoked BEFORE the callback event that corresponds to the end
+ # of a child run, which results in clean up of run_map.
+ # So we keep track of the mapping between children and parent run IDs
+ # in a separate container. This container is GCed when the tracer is GCed.
+ self.parent_map: dict[UUID, UUID | None] = {}
+
+ self.is_tapped: dict[UUID, Any] = {}
+
+ # Filter which events will be sent over the queue.
+ self.root_event_filter = _RootEventFilter(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ memory_stream = _MemoryStream[StreamEvent](loop)
+ self.send_stream = memory_stream.get_send_stream()
+ self.receive_stream = memory_stream.get_receive_stream()
+
+ def _get_parent_ids(self, run_id: UUID) -> list[str]:
+ """Get the parent IDs of a run (non-recursively) cast to strings."""
+ parent_ids = []
+
+ while parent_id := self.parent_map.get(run_id):
+ str_parent_id = str(parent_id)
+ if str_parent_id in parent_ids:
+ msg = (
+ f"Parent ID {parent_id} is already in the parent_ids list. "
+ f"This should never happen."
+ )
+ raise AssertionError(msg)
+ parent_ids.append(str_parent_id)
+ run_id = parent_id
+
+ # Return the parent IDs in reverse order, so that the first
+ # parent ID is the root and the last ID is the immediate parent.
+ return parent_ids[::-1]
+
+ def _send(self, event: StreamEvent, event_type: str) -> None:
+ """Send an event to the stream."""
+ if self.root_event_filter.include_event(event, event_type):
+ self.send_stream.send_nowait(event)
+
+ def __aiter__(self) -> AsyncIterator[Any]:
+ """Iterate over the receive stream.
+
+ Returns:
+ An async iterator over the receive stream.
+ """
+ return self.receive_stream.__aiter__()
+
+ async def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Tap the output aiter.
+
+ This method is used to tap the output of a `Runnable` that produces an async
+ iterator. It is used to generate stream events for the output of the `Runnable`.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output of the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+ """
+ sentinel = object()
+ # atomic check and set
+ tap = self.is_tapped.setdefault(run_id, sentinel)
+ # wait for first chunk
+ first = await anext(output, sentinel)
+ if first is sentinel:
+ return
+ # get run info
+ run_info = self.run_map.get(run_id)
+ if run_info is None:
+ # run has finished, don't issue any stream events
+ yield cast("T", first)
+ return
+ if tap is sentinel:
+ # if we are the first to tap, issue stream events
+ event: StandardStreamEvent = {
+ "event": f"on_{run_info['run_type']}_stream",
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "data": {},
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
+ yield cast("T", first)
+ # consume the rest of the output
+ async for chunk in output:
+ self._send(
+ {**event, "data": {"chunk": chunk}},
+ run_info["run_type"],
+ )
+ yield chunk
+ else:
+ # otherwise just pass through
+ yield cast("T", first)
+ # consume the rest of the output
+ async for chunk in output:
+ yield chunk
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Tap the output iter.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output of the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+ """
+ sentinel = object()
+ # atomic check and set
+ tap = self.is_tapped.setdefault(run_id, sentinel)
+ # wait for first chunk
+ first = next(output, sentinel)
+ if first is sentinel:
+ return
+ # get run info
+ run_info = self.run_map.get(run_id)
+ if run_info is None:
+ # run has finished, don't issue any stream events
+ yield cast("T", first)
+ return
+ if tap is sentinel:
+ # if we are the first to tap, issue stream events
+ event: StandardStreamEvent = {
+ "event": f"on_{run_info['run_type']}_stream",
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "data": {},
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
+ yield cast("T", first)
+ # consume the rest of the output
+ for chunk in output:
+ self._send(
+ {**event, "data": {"chunk": chunk}},
+ run_info["run_type"],
+ )
+ yield chunk
+ else:
+ # otherwise just pass through
+ yield cast("T", first)
+ # consume the rest of the output
+ for chunk in output:
+ yield chunk
+
+ def _write_run_start_info(
+ self,
+ run_id: UUID,
+ *,
+ tags: list[str] | None,
+ metadata: dict[str, Any] | None,
+ parent_run_id: UUID | None,
+ name_: str,
+ run_type: str,
+ **kwargs: Any,
+ ) -> None:
+ """Update the run info."""
+ info: RunInfo = {
+ "tags": tags or [],
+ "metadata": metadata or {},
+ "name": name_,
+ "run_type": run_type,
+ "parent_run_id": parent_run_id,
+ }
+
+ if "inputs" in kwargs:
+ # Handle inputs in a special case to allow inputs to be an
+ # optionally provided and distinguish between missing value
+ # vs. None value.
+ info["inputs"] = kwargs["inputs"]
+
+ if "tool_call_id" in kwargs:
+ # Store tool_call_id in run info for linking errors to tool calls
+ info["tool_call_id"] = kwargs["tool_call_id"]
+
+ self.run_map[run_id] = info
+ self.parent_map[run_id] = parent_run_id
+
+ @override
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a chat model run."""
+ name_ = _assign_name(name, serialized)
+ run_type = "chat_model"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"messages": messages},
+ )
+
+ self._send(
+ {
+ "event": "on_chat_model_start",
+ "data": {
+ "input": {"messages": messages},
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a (non-chat model) LLM run."""
+ name_ = _assign_name(name, serialized)
+ run_type = "llm"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"prompts": prompts},
+ )
+
+ self._send(
+ {
+ "event": "on_llm_start",
+ "data": {
+ "input": {
+ "prompts": prompts,
+ }
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Generate a custom astream event."""
+ event = CustomStreamEvent(
+ event="on_custom_event",
+ run_id=str(run_id),
+ name=name,
+ tags=tags or [],
+ metadata=metadata or {},
+ data=data,
+ parent_ids=self._get_parent_ids(run_id),
+ )
+ self._send(event, name)
+
+ @override
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on new output token.
+
+ Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text-completion LLMs).
+
+ Raises:
+ ValueError: If the run type is not `llm` or `chat_model`.
+ AssertionError: If the run ID is not found in the run map.
+ """
+ run_info = self.run_map.get(run_id)
+ chunk_: GenerationChunk | BaseMessageChunk
+
+ if run_info is None:
+ msg = f"Run ID {run_id} not found in run map."
+ raise AssertionError(msg)
+ if self.is_tapped.get(run_id):
+ return
+ if run_info["run_type"] == "chat_model":
+ event = "on_chat_model_stream"
+
+ if chunk is None:
+ chunk_ = AIMessageChunk(content=token)
+ else:
+ chunk_ = cast("ChatGenerationChunk", chunk).message
+
+ elif run_info["run_type"] == "llm":
+ event = "on_llm_stream"
+ if chunk is None:
+ chunk_ = GenerationChunk(text=token)
+ else:
+ chunk_ = cast("GenerationChunk", chunk)
+ else:
+ msg = f"Unexpected run type: {run_info['run_type']}"
+ raise ValueError(msg)
+
+ self._send(
+ {
+ "event": event,
+ "data": {
+ "chunk": chunk_,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ @override
+ async def on_llm_end(
+ self, response: LLMResult, *, run_id: UUID, **kwargs: Any
+ ) -> None:
+ """End a trace for a model run.
+
+ For both chat models and non-chat models (legacy text-completion LLMs).
+
+ Raises:
+ ValueError: If the run type is not `'llm'` or `'chat_model'`.
+ """
+ run_info = self.run_map.pop(run_id)
+ inputs_ = run_info.get("inputs")
+
+ generations: list[list[GenerationChunk]] | list[list[ChatGenerationChunk]]
+ output: dict | BaseMessage = {}
+
+ if run_info["run_type"] == "chat_model":
+ generations = cast("list[list[ChatGenerationChunk]]", response.generations)
+ for gen in generations:
+ if output != {}:
+ break
+ for chunk in gen:
+ output = chunk.message
+ break
+
+ event = "on_chat_model_end"
+ elif run_info["run_type"] == "llm":
+ generations = cast("list[list[GenerationChunk]]", response.generations)
+ output = {
+ "generations": [
+ [
+ {
+ "text": chunk.text,
+ "generation_info": chunk.generation_info,
+ "type": chunk.type,
+ }
+ for chunk in gen
+ ]
+ for gen in generations
+ ],
+ "llm_output": response.llm_output,
+ }
+ event = "on_llm_end"
+ else:
+ msg = f"Unexpected run type: {run_info['run_type']}"
+ raise ValueError(msg)
+
+ self._send(
+ {
+ "event": event,
+ "data": {"output": output, "input": inputs_},
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a chain run."""
+ name_ = _assign_name(name, serialized)
+ run_type_ = run_type or "chain"
+
+ data: EventData = {}
+
+ # Work-around Runnable core code not sending input in some
+ # cases.
+ if inputs != {"input": ""}:
+ data["input"] = inputs
+ kwargs["inputs"] = inputs
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type_,
+ **kwargs,
+ )
+
+ self._send(
+ {
+ "event": f"on_{run_type_}_start",
+ "data": data,
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type_,
+ )
+
+ @override
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """End a trace for a chain run."""
+ run_info = self.run_map.pop(run_id)
+ run_type = run_info["run_type"]
+
+ event = f"on_{run_type}_end"
+
+ inputs = inputs or run_info.get("inputs") or {}
+
+ data: EventData = {
+ "output": outputs,
+ "input": inputs,
+ }
+
+ self._send(
+ {
+ "event": event,
+ "data": data,
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ def _get_tool_run_info_with_inputs(self, run_id: UUID) -> tuple[RunInfo, Any]:
+ """Get run info for a tool and extract inputs, with validation.
+
+ Args:
+ run_id: The run ID of the tool.
+
+ Returns:
+ A tuple of `(run_info, inputs)`.
+
+ Raises:
+ AssertionError: If the run ID is a tool call and does not have inputs.
+ """
+ run_info = self.run_map.pop(run_id)
+ if "inputs" not in run_info:
+ msg = (
+ f"Run ID {run_id} is a tool call and is expected to have "
+ f"inputs associated with it."
+ )
+ raise AssertionError(msg)
+ inputs = run_info["inputs"]
+ return run_info, inputs
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a tool run."""
+ name_ = _assign_name(name, serialized)
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type="tool",
+ inputs=inputs,
+ tool_call_id=kwargs.get("tool_call_id"),
+ )
+
+ self._send(
+ {
+ "event": "on_tool_start",
+ "data": {
+ "input": inputs or {},
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ "tool",
+ )
+
+ @override
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors."""
+ # Extract tool_call_id from kwargs if passed directly, or from run_info
+ # (which was stored during on_tool_start) as a fallback
+ tool_call_id = kwargs.get("tool_call_id")
+ run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
+ if tool_call_id is None:
+ tool_call_id = run_info.get("tool_call_id")
+
+ event: StandardStreamEvent = {
+ "event": "on_tool_error",
+ "data": {
+ "error": error,
+ "input": inputs,
+ "tool_call_id": tool_call_id,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send(event, "tool")
+
+ @override
+ async def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> None:
+ """End a trace for a tool run."""
+ run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
+
+ self._send(
+ {
+ "event": "on_tool_end",
+ "data": {
+ "output": output,
+ "input": inputs,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ "tool",
+ )
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when `Retriever` starts running."""
+ name_ = _assign_name(name, serialized)
+ run_type = "retriever"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"query": query},
+ )
+
+ self._send(
+ {
+ "event": "on_retriever_start",
+ "data": {
+ "input": {
+ "query": query,
+ }
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_retriever_end(
+ self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any
+ ) -> None:
+ """Run when `Retriever` ends running."""
+ run_info = self.run_map.pop(run_id)
+
+ self._send(
+ {
+ "event": "on_retriever_end",
+ "data": {
+ "output": documents,
+ "input": run_info.get("inputs"),
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ def __deepcopy__(self, memo: dict) -> _AstreamEventsCallbackHandler:
+ """Return self."""
+ return self
+
+ def __copy__(self) -> _AstreamEventsCallbackHandler:
+ """Return self."""
+ return self
+
+
+async def _astream_events_implementation_v1(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+) -> AsyncIterator[StandardStreamEvent]:
+ stream = LogStreamCallbackHandler(
+ auto_close=False,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ _schema_format="streaming_events",
+ )
+
+ run_log = RunLog(state=None) # type: ignore[arg-type]
+ encountered_start_event = False
+
+ root_event_filter = _RootEventFilter(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ config = ensure_config(config)
+ root_tags = config.get("tags", [])
+ root_metadata = config.get("metadata", {})
+ root_name = config.get("run_name", runnable.get_name())
+
+ async for log in _astream_log_implementation(
+ runnable,
+ value,
+ config=config,
+ stream=stream,
+ diff=True,
+ with_streamed_output_list=True,
+ **kwargs,
+ ):
+ run_log += log
+
+ if not encountered_start_event:
+ # Yield the start event for the root runnable.
+ encountered_start_event = True
+ state = run_log.state.copy()
+
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_start",
+ run_id=state["id"],
+ name=root_name,
+ tags=root_tags,
+ metadata=root_metadata,
+ data={
+ "input": value,
+ },
+ parent_ids=[], # Not supported in v1
+ )
+
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+ paths = {
+ op["path"].split("/")[2]
+ for op in log.ops
+ if op["path"].startswith("/logs/")
+ }
+ # Elements in a set should be iterated in the same order
+ # as they were inserted in modern python versions.
+ for path in paths:
+ data: EventData = {}
+ log_entry: LogEntry = run_log.state["logs"][path]
+ if log_entry["end_time"] is None:
+ event_type = "stream" if log_entry["streamed_output"] else "start"
+ else:
+ event_type = "end"
+
+ if event_type == "start":
+ # Include the inputs with the start event if they are available.
+ # Usually they will NOT be available for components that operate
+ # on streams, since those components stream the input and
+ # don't know its final value until the end of the stream.
+ inputs = log_entry.get("inputs")
+ if inputs is not None:
+ data["input"] = inputs
+
+ if event_type == "end":
+ inputs = log_entry.get("inputs")
+ if inputs is not None:
+ data["input"] = inputs
+
+ # None is a VALID output for an end event
+ data["output"] = log_entry["final_output"]
+
+ if event_type == "stream":
+ num_chunks = len(log_entry["streamed_output"])
+ if num_chunks != 1:
+ msg = (
+ f"Expected exactly one chunk of streamed output, "
+ f"got {num_chunks} instead. This is impossible. "
+ f"Encountered in: {log_entry['name']}"
+ )
+ raise AssertionError(msg)
+
+ data = {"chunk": log_entry["streamed_output"][0]}
+ # Clean up the stream, we don't need it anymore.
+ # And this avoids duplicates as well!
+ log_entry["streamed_output"] = []
+
+ yield StandardStreamEvent(
+ event=f"on_{log_entry['type']}_{event_type}",
+ name=log_entry["name"],
+ run_id=log_entry["id"],
+ tags=log_entry["tags"],
+ metadata=log_entry["metadata"],
+ data=data,
+ parent_ids=[], # Not supported in v1
+ )
+
+ # Finally, we take care of the streaming output from the root chain
+ # if there is any.
+ state = run_log.state
+ if state["streamed_output"]:
+ num_chunks = len(state["streamed_output"])
+ if num_chunks != 1:
+ msg = (
+ f"Expected exactly one chunk of streamed output, "
+ f"got {num_chunks} instead. This is impossible. "
+ f"Encountered in: {state['name']}"
+ )
+ raise AssertionError(msg)
+
+ data = {"chunk": state["streamed_output"][0]}
+ # Clean up the stream, we don't need it anymore.
+ state["streamed_output"] = []
+
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_stream",
+ run_id=state["id"],
+ tags=root_tags,
+ metadata=root_metadata,
+ name=root_name,
+ data=data,
+ parent_ids=[], # Not supported in v1
+ )
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+ state = run_log.state
+
+ # Finally yield the end event for the root runnable.
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_end",
+ name=root_name,
+ run_id=state["id"],
+ tags=root_tags,
+ metadata=root_metadata,
+ data={
+ "output": state["final_output"],
+ },
+ parent_ids=[], # Not supported in v1
+ )
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+
+async def _astream_events_implementation_v2(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+) -> AsyncIterator[StandardStreamEvent]:
+ """Implementation of the astream events API for v2 runnables."""
+ event_streamer = _AstreamEventsCallbackHandler(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ # Assign the stream handler to the config
+ config = ensure_config(config)
+ if "run_id" in config:
+ run_id = cast("UUID", config["run_id"])
+ else:
+ run_id = uuid7()
+ config["run_id"] = run_id
+ callbacks = config.get("callbacks")
+ if callbacks is None:
+ config["callbacks"] = [event_streamer]
+ elif isinstance(callbacks, list):
+ config["callbacks"] = [*callbacks, event_streamer]
+ elif isinstance(callbacks, BaseCallbackManager):
+ callbacks = callbacks.copy()
+ callbacks.add_handler(event_streamer, inherit=True)
+ config["callbacks"] = callbacks
+ else:
+ msg = (
+ f"Unexpected type for callbacks: {callbacks}."
+ "Expected None, list or AsyncCallbackManager."
+ )
+ raise ValueError(msg)
+
+ # Call the runnable in streaming mode,
+ # add each chunk to the output stream
+ async def consume_astream() -> None:
+ try:
+ # if astream also calls tap_output_aiter this will be a no-op
+ async with aclosing(runnable.astream(value, config, **kwargs)) as stream:
+ async for _ in event_streamer.tap_output_aiter(run_id, stream):
+ # All the content will be picked up
+ pass
+ finally:
+ await event_streamer.send_stream.aclose()
+
+ # Start the runnable in a task, so we can start consuming output
+ task = asyncio.create_task(consume_astream())
+
+ first_event_sent = False
+ first_event_run_id = None
+
+ try:
+ async for event in event_streamer:
+ if not first_event_sent:
+ first_event_sent = True
+ # This is a work-around an issue where the inputs into the
+ # chain are not available until the entire input is consumed.
+ # As a temporary solution, we'll modify the input to be the input
+ # that was passed into the chain.
+ event["data"]["input"] = value
+ first_event_run_id = event["run_id"]
+ yield event
+ continue
+
+ # If it's the end event corresponding to the root runnable
+ # we don't include the input in the event since it's guaranteed
+ # to be included in the first event.
+ if (
+ event["run_id"] == first_event_run_id
+ and event["event"].endswith("_end")
+ and "input" in event["data"]
+ ):
+ del event["data"]["input"]
+
+ yield event
+ except asyncio.CancelledError as exc:
+ # Cancel the task if it's still running
+ task.cancel(exc.args[0] if exc.args else None)
+ raise
+ finally:
+ # Cancel the task if it's still running
+ task.cancel()
+ # Await it anyway, to run any cleanup code, and propagate any exceptions
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/langchain.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/langchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..6295a2f034b1b594b149d7acbf0f5e088f1828eb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/langchain.py
@@ -0,0 +1,490 @@
+"""A tracer implementation that records to LangChain endpoint."""
+
+from __future__ import annotations
+
+import logging
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
+
+from langsmith import Client, get_tracing_context
+from langsmith import run_trees as rt
+from langsmith import utils as ls_utils
+from tenacity import (
+ Retrying,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential_jitter,
+)
+from typing_extensions import override
+
+from langchain_core.env import get_runtime_environment
+from langchain_core.load import dumpd
+from langchain_core.messages.ai import UsageMetadata, add_usage
+from langchain_core.tracers._compat import run_construct, run_to_dict
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
+
+logger = logging.getLogger(__name__)
+_LOGGED = set()
+_EXECUTOR: ThreadPoolExecutor | None = None
+
+OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS: frozenset[str] = frozenset(
+ {"ls_agent_type"}
+)
+"""Allowlist of LangSmith-only tracing metadata keys that bypass the default
+"first wins" merge semantics used when propagating tracer metadata to nested
+runs.
+
+Keys in this set are ALWAYS overridden by the nearest enclosing tracer config,
+so nested callers (e.g. a subagent) can replace a value inherited from an
+ancestor.
+
+Keep this list very small: every key here loses the default "first wins"
+protection and is always clobbered by the nearest enclosing tracer config.
+Only keys that are strictly for LangSmith tracing bookkeeping should be added.
+"""
+
+
+def log_error_once(method: str, exception: Exception) -> None:
+ """Log an error once.
+
+ Args:
+ method: The method that raised the exception.
+ exception: The exception that was raised.
+ """
+ if (method, type(exception)) in _LOGGED:
+ return
+ _LOGGED.add((method, type(exception)))
+ logger.error(exception)
+
+
+def wait_for_all_tracers() -> None:
+ """Wait for all tracers to finish."""
+ if rt._CLIENT is not None: # noqa: SLF001
+ rt._CLIENT.flush() # noqa: SLF001
+
+
+def get_client() -> Client:
+ """Get the client.
+
+ Returns:
+ The LangSmith client.
+ """
+ return rt.get_cached_client()
+
+
+def _get_executor() -> ThreadPoolExecutor:
+ """Get the executor."""
+ global _EXECUTOR # noqa: PLW0603
+ if _EXECUTOR is None:
+ _EXECUTOR = ThreadPoolExecutor()
+ return _EXECUTOR
+
+
+def _get_usage_metadata_from_generations(
+ generations: list[list[dict[str, Any]]],
+) -> UsageMetadata | None:
+ """Extract and aggregate `usage_metadata` from generations.
+
+ Iterates through generations to find and aggregate all `usage_metadata` found in
+ messages. This expects the serialized message payload shape produced by tracer
+ internals:
+
+ `{"message": {"kwargs": {"usage_metadata": {...}}}}`
+
+ Args:
+ generations: List of generation batches, where each batch is a list of
+ generation dicts that may contain a `'message'` key with
+ usage metadata.
+
+ Returns:
+ The aggregated `usage_metadata` dict if found, otherwise `None`.
+ """
+ output: UsageMetadata | None = None
+ for generation_batch in generations:
+ for generation in generation_batch:
+ if isinstance(generation, dict) and "message" in generation:
+ message = generation["message"]
+ usage_metadata = _get_usage_metadata_from_message(message)
+ if usage_metadata is not None:
+ output = add_usage(output, usage_metadata)
+ return output
+
+
+def _get_usage_metadata_from_message(message: Any) -> UsageMetadata | None:
+ """Extract usage metadata from a generation's message payload."""
+ if not isinstance(message, dict):
+ return None
+
+ kwargs = message.get("kwargs")
+ if isinstance(kwargs, dict) and isinstance(kwargs.get("usage_metadata"), dict):
+ return cast("UsageMetadata", kwargs["usage_metadata"])
+
+ return None
+
+
+class LangChainTracer(BaseTracer):
+ """Implementation of the `SharedTracer` that `POSTS` to the LangChain endpoint."""
+
+ run_inline = True
+
+ def __init__(
+ self,
+ example_id: UUID | str | None = None,
+ project_name: str | None = None,
+ client: Client | None = None,
+ tags: list[str] | None = None,
+ *,
+ metadata: Mapping[str, str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the LangChain tracer.
+
+ Args:
+ example_id: The example ID.
+ project_name: The project name.
+
+ Defaults to the tracer project.
+ client: The client.
+
+ Defaults to the global client.
+ tags: The tags.
+
+ Defaults to an empty list.
+ metadata: Additional metadata to include if it isn't already in the run.
+
+ Defaults to None.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.project_name = project_name or ls_utils.get_tracer_project()
+ self.client = client or get_client()
+ self.tags = tags or []
+ self.latest_run: Run | None = None
+ self.run_has_token_event_map: dict[str, bool] = {}
+ self.tracing_metadata: dict[str, str] | None = (
+ dict(metadata) if metadata is not None else None
+ )
+
+ def copy_with_metadata_defaults(
+ self,
+ *,
+ metadata: Mapping[str, str] | None = None,
+ tags: list[str] | None = None,
+ ) -> LangChainTracer:
+ """Return a new tracer with merged tracer-only defaults."""
+ base_metadata = self.tracing_metadata
+ if metadata is None:
+ merged_metadata = dict(base_metadata) if base_metadata is not None else None
+ elif base_metadata is None:
+ merged_metadata = dict(metadata)
+ else:
+ merged_metadata = dict(base_metadata)
+ for key, value in metadata.items():
+ # For allowlisted LangSmith-only inheritable metadata keys
+ # (e.g. ``ls_agent_type``), nested callers are allowed to
+ # OVERRIDE the value inherited from an ancestor. For all
+ # other keys we keep the existing "first wins" behavior so
+ # that ancestor-provided tracing metadata is not accidentally
+ # clobbered by child runs.
+ if (
+ key not in merged_metadata
+ or key in OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS
+ ):
+ merged_metadata[key] = value
+
+ merged_tags = sorted(set(self.tags + tags)) if tags else self.tags
+
+ return self.__class__(
+ example_id=self.example_id,
+ project_name=self.project_name,
+ client=self.client,
+ tags=merged_tags,
+ metadata=merged_metadata,
+ run_map=self.run_map,
+ order_map=self.order_map,
+ _external_run_ids=self._external_run_ids,
+ )
+
+ def _start_trace(self, run: Run) -> None:
+ if self.project_name:
+ run.session_name = self.project_name
+ if self.tags is not None:
+ if run.tags:
+ run.tags = sorted(set(run.tags + self.tags))
+ else:
+ run.tags = self.tags.copy()
+
+ super()._start_trace(run)
+ if run.ls_client is None:
+ run.ls_client = self.client
+ if get_tracing_context().get("enabled") is False:
+ run.extra["__disabled"] = True
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for an LLM run.
+
+ Args:
+ serialized: The serialized model.
+ messages: The messages.
+ run_id: The run ID.
+ tags: The tags.
+ parent_run_id: The parent run ID.
+ metadata: The metadata.
+ name: The name.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The run.
+ """
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ chat_model_run = Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"messages": [[dumpd(msg) for msg in batch] for batch in messages]},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ run_type="llm",
+ tags=tags,
+ name=name,
+ )
+ self._start_trace(chat_model_run)
+ self._on_chat_model_start(chat_model_run)
+ return chat_model_run
+
+ def _persist_run(self, run: Run) -> None:
+ # We want to free up more memory by avoiding keeping a reference to the
+ # whole nested run tree.
+ run_data = run_to_dict(run, exclude={"child_runs", "inputs", "outputs"})
+ self.latest_run = run_construct(
+ **run_data,
+ inputs=run.inputs,
+ outputs=run.outputs,
+ )
+
+ def get_run_url(self) -> str:
+ """Get the LangSmith root run URL.
+
+ Returns:
+ The LangSmith root run URL.
+
+ Raises:
+ ValueError: If no traced run is found.
+ ValueError: If the run URL cannot be found.
+ """
+ if not self.latest_run:
+ msg = "No traced run found."
+ raise ValueError(msg)
+ # If this is the first run in a project, the project may not yet be created.
+ # This method is only really useful for debugging flows, so we will assume
+ # there is some tolerace for latency.
+ for attempt in Retrying(
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(),
+ retry=retry_if_exception_type(ls_utils.LangSmithError),
+ ):
+ with attempt:
+ return self.client.get_run_url(
+ run=self.latest_run, project_name=self.project_name
+ )
+ msg = "Failed to get run URL."
+ raise ValueError(msg)
+
+ def _get_tags(self, run: Run) -> list[str]:
+ """Get combined tags for a run."""
+ tags = set(run.tags or [])
+ tags.update(self.tags or [])
+ return list(tags)
+
+ def _persist_run_single(self, run: Run) -> None:
+ """Persist a run."""
+ if run.extra.get("__disabled"):
+ return
+ try:
+ run.extra["runtime"] = get_runtime_environment()
+ run.tags = self._get_tags(run)
+ _patch_missing_metadata(self, run)
+ if run.ls_client is not self.client:
+ run.ls_client = self.client
+ run.post()
+ except Exception as e:
+ # Errors are swallowed by the thread executor so we need to log them here
+ log_error_once("post", e)
+ raise
+
+ @staticmethod
+ def _update_run_single(run: Run) -> None:
+ """Update a run."""
+ if run.extra.get("__disabled"):
+ return
+ try:
+ run.patch(exclude_inputs=run.extra.get("inputs_is_truthy", False))
+ except Exception as e:
+ # Errors are swallowed by the thread executor so we need to log them here
+ log_error_once("patch", e)
+ raise
+
+ def _on_llm_start(self, run: Run) -> None:
+ """Persist an LLM run."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ @override
+ def _llm_run_with_token_event(
+ self,
+ token: str,
+ run_id: UUID,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ parent_run_id: UUID | None = None,
+ ) -> Run:
+ run_id_str = str(run_id)
+ if run_id_str not in self.run_has_token_event_map:
+ self.run_has_token_event_map[run_id_str] = True
+ else:
+ return self._get_run(run_id, run_type={"llm", "chat_model"})
+ return super()._llm_run_with_token_event(
+ # Drop the chunk; we don't need to save it
+ token,
+ run_id,
+ chunk=None,
+ parent_run_id=parent_run_id,
+ )
+
+ def _on_chat_model_start(self, run: Run) -> None:
+ """Persist a chat model run.
+
+ Note:
+ Naming is historical: there is no `_on_chat_model_end` hook. Chat
+ model completion is handled by `_on_llm_end`, shared with text
+ LLM runs.
+ """
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_llm_end(self, run: Run) -> None:
+ """Process LLM/chat model run completion."""
+ # Extract usage_metadata from outputs and store in extra.metadata
+ if run.outputs and "generations" in run.outputs:
+ usage_metadata = _get_usage_metadata_from_generations(
+ run.outputs["generations"]
+ )
+ if usage_metadata is not None:
+ if "metadata" not in run.extra:
+ run.extra["metadata"] = {}
+ run.extra["metadata"]["usage_metadata"] = usage_metadata
+ self._update_run_single(run)
+
+ def _on_llm_error(self, run: Run) -> None:
+ """Process the LLM Run upon error."""
+ self._update_run_single(run)
+
+ def _on_chain_start(self, run: Run) -> None:
+ """Process the Chain Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ # Skip persisting if inputs are deferred (e.g., iterator/generator inputs).
+ # The run will be posted when _on_chain_end is called with realized inputs.
+ if not run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+
+ def _on_chain_end(self, run: Run) -> None:
+ """Process the Chain Run."""
+ # If inputs were deferred, persist (POST) the run now that inputs are realized.
+ # Otherwise, update (PATCH) the existing run.
+ if run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+ else:
+ self._update_run_single(run)
+
+ def _on_chain_error(self, run: Run) -> None:
+ """Process the Chain Run upon error."""
+ # If inputs were deferred, persist (POST) the run now that inputs are realized.
+ # Otherwise, update (PATCH) the existing run.
+ if run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+ else:
+ self._update_run_single(run)
+
+ def _on_tool_start(self, run: Run) -> None:
+ """Process the Tool Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_tool_end(self, run: Run) -> None:
+ """Process the Tool Run."""
+ self._update_run_single(run)
+
+ def _on_tool_error(self, run: Run) -> None:
+ """Process the Tool Run upon error."""
+ self._update_run_single(run)
+
+ def _on_retriever_start(self, run: Run) -> None:
+ """Process the Retriever Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_retriever_end(self, run: Run) -> None:
+ """Process the Retriever Run."""
+ self._update_run_single(run)
+
+ def _on_retriever_error(self, run: Run) -> None:
+ """Process the Retriever Run upon error."""
+ self._update_run_single(run)
+
+ def wait_for_futures(self) -> None:
+ """Wait for the given futures to complete."""
+ if self.client is not None:
+ self.client.flush()
+
+
+def _patch_missing_metadata(self: LangChainTracer, run: Run) -> None:
+ if not self.tracing_metadata:
+ return
+ metadata = run.metadata
+ patched = None
+ for k, v in self.tracing_metadata.items():
+ # ``OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS`` are a small,
+ # LangSmith-only allowlist that bypasses the "first wins" merge
+ # so a nested caller (e.g. a subagent) can override a parent-set value.
+ if k not in metadata or k in OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:
+ # Skip the copy when the value already matches (avoids cloning
+ # the shared dict in the common "already set" case). Use a
+ # ``k in metadata`` guard so a legitimate missing key whose
+ # tracer value happens to be ``None`` is still patched in.
+ if k in metadata and metadata[k] == v:
+ continue
+ if patched is None:
+ # Copy on first miss to avoid mutating the shared dict.
+ patched = {**metadata}
+ run.extra["metadata"] = patched
+ patched[k] = v
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/log_stream.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/log_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..5131815ebdfbd7a55baafb5677df68dce8f2b8ee
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/log_stream.py
@@ -0,0 +1,769 @@
+"""Tracer that streams run logs to a stream."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import copy
+import threading
+from collections import defaultdict
+from pprint import pformat
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypeVar,
+ overload,
+)
+
+import jsonpatch # type: ignore[import-untyped]
+from typing_extensions import NotRequired, TypedDict, override
+
+from langchain_core.callbacks.base import BaseCallbackManager
+from langchain_core.load import dumps
+from langchain_core.load.load import load
+from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
+from langchain_core.runnables import RunnableConfig, ensure_config
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.memory_stream import _MemoryStream
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Sequence
+ from uuid import UUID
+
+ from langchain_core.runnables import Runnable
+ from langchain_core.runnables.utils import Input, Output
+ from langchain_core.tracers.schemas import Run
+
+
+class LogEntry(TypedDict):
+ """A single entry in the run log."""
+
+ id: str
+ """ID of the sub-run."""
+
+ name: str
+ """Name of the object being run."""
+
+ type: str
+ """Type of the object being run, eg. prompt, chain, llm, etc."""
+
+ tags: list[str]
+ """List of tags for the run."""
+
+ metadata: dict[str, Any]
+ """Key-value pairs of metadata for the run."""
+
+ start_time: str
+ """ISO-8601 timestamp of when the run started."""
+
+ streamed_output_str: list[str]
+ """List of LLM tokens streamed by this run, if applicable."""
+
+ streamed_output: list[Any]
+ """List of output chunks streamed by this run, if available."""
+
+ inputs: NotRequired[Any | None]
+ """Inputs to this run. Not available currently via `astream_log`."""
+
+ final_output: Any | None
+ """Final output of this run.
+
+ Only available after the run has finished successfully.
+ """
+
+ end_time: str | None
+ """ISO-8601 timestamp of when the run ended.
+
+ Only available after the run has finished.
+ """
+
+
+class RunState(TypedDict):
+ """State of the run."""
+
+ id: str
+ """ID of the run."""
+
+ streamed_output: list[Any]
+ """List of output chunks streamed by `Runnable.stream()`"""
+
+ final_output: Any | None
+ """Final output of the run, usually the result of aggregating (`+`) streamed_output.
+
+ Updated throughout the run when supported by the `Runnable`.
+ """
+
+ name: str
+ """Name of the object being run."""
+
+ type: str
+ """Type of the object being run, e.g. prompt, chain, llm, etc."""
+
+ # Do we want tags/metadata on the root run? Client kinda knows it in most situations
+ # tags: list[str]
+
+ logs: dict[str, LogEntry]
+ """Map of run names to sub-runs.
+
+ If filters were supplied, this list will contain only the runs that matched the
+ filters.
+ """
+
+
+class RunLogPatch:
+ """Patch to the run log."""
+
+ ops: list[dict[str, Any]]
+ """List of `JSONPatch` operations, which describe how to create the run state
+ from an empty dict.
+
+ This is the minimal representation of the log, designed to be serialized as JSON and
+ sent over the wire to reconstruct the log on the other side. Reconstruction of the
+ state can be done with any JSONPatch-compliant library, see https://jsonpatch.com
+ for more information.
+ """
+
+ def __init__(self, *ops: dict[str, Any]) -> None:
+ """Create a RunLogPatch.
+
+ Args:
+ *ops: The operations to apply to the state.
+ """
+ self.ops = list(ops)
+
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
+ """Combine two `RunLogPatch` instances.
+
+ Args:
+ other: The other `RunLogPatch` to combine with.
+
+ Raises:
+ TypeError: If the other object is not a `RunLogPatch`.
+
+ Returns:
+ A new `RunLog` representing the combination of the two.
+ """
+ if type(other) is RunLogPatch:
+ ops = self.ops + other.ops
+ state = jsonpatch.apply_patch(None, copy.deepcopy(ops))
+ return RunLog(*ops, state=state)
+
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+ @override
+ def __repr__(self) -> str:
+ # 1:-1 to get rid of the [] around the list
+ return f"RunLogPatch({pformat(self.ops)[1:-1]})"
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, RunLogPatch) and self.ops == other.ops
+
+ __hash__ = None # type: ignore[assignment]
+
+
+class RunLog(RunLogPatch):
+ """Run log."""
+
+ state: RunState
+ """Current state of the log, obtained from applying all ops in sequence."""
+
+ def __init__(self, *ops: dict[str, Any], state: RunState) -> None:
+ """Create a RunLog.
+
+ Args:
+ *ops: The operations to apply to the state.
+ state: The initial state of the run log.
+ """
+ super().__init__(*ops)
+ self.state = state
+
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
+ """Combine two `RunLog` objects.
+
+ Args:
+ other: The other `RunLog` or `RunLogPatch` to combine with.
+
+ Raises:
+ TypeError: If the other object is not a `RunLog` or `RunLogPatch`.
+
+ Returns:
+ A new `RunLog` representing the combination of the two.
+ """
+ if type(other) is RunLogPatch:
+ ops = self.ops + other.ops
+ state = jsonpatch.apply_patch(self.state, other.ops)
+ return RunLog(*ops, state=state)
+
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+ @override
+ def __repr__(self) -> str:
+ return f"RunLog({pformat(self.state)})"
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ """Check if two `RunLog`s are equal.
+
+ Args:
+ other: The other `RunLog` to compare to.
+
+ Returns:
+ `True` if the `RunLog`s are equal, `False` otherwise.
+ """
+ # First compare that the state is the same
+ if not isinstance(other, RunLog):
+ return False
+ if self.state != other.state:
+ return False
+ # Then compare that the ops are the same
+ return super().__eq__(other)
+
+ __hash__ = None
+
+
+T = TypeVar("T")
+
+
+class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
+ """Tracer that streams run logs to a stream."""
+
+ def __init__(
+ self,
+ *,
+ auto_close: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ # Schema format is for internal use only.
+ _schema_format: Literal["original", "streaming_events"] = "streaming_events",
+ ) -> None:
+ """A tracer that streams run logs to a stream.
+
+ Args:
+ auto_close: Whether to close the stream when the root run finishes.
+ include_names: Only include runs from `Runnable` objects with matching
+ names.
+ include_types: Only include runs from `Runnable` objects with matching
+ types.
+ include_tags: Only include runs from `Runnable` objects with matching tags.
+ exclude_names: Exclude runs from `Runnable` objects with matching names.
+ exclude_types: Exclude runs from `Runnable` objects with matching types.
+ exclude_tags: Exclude runs from `Runnable` objects with matching tags.
+ _schema_format: Primarily changes how the inputs and outputs are handled.
+
+ **For internal use only. This API will change.**
+
+ - `'original'` is the format used by all current tracers. This format is
+ slightly inconsistent with respect to inputs and outputs.
+ - 'streaming_events' is used for supporting streaming events, for
+ internal usage. It will likely change in the future,
+ or be deprecated entirely in favor of a dedicated async
+ tracer for streaming events.
+
+ Raises:
+ ValueError: If an invalid schema format is provided (internal use only).
+ """
+ if _schema_format not in {"original", "streaming_events"}:
+ msg = (
+ f"Invalid schema format: {_schema_format}. "
+ f"Expected one of 'original', 'streaming_events'."
+ )
+ raise ValueError(msg)
+ super().__init__(_schema_format=_schema_format)
+
+ self.auto_close = auto_close
+ self.include_names = include_names
+ self.include_types = include_types
+ self.include_tags = include_tags
+ self.exclude_names = exclude_names
+ self.exclude_types = exclude_types
+ self.exclude_tags = exclude_tags
+
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ memory_stream = _MemoryStream[RunLogPatch](loop)
+ self.lock = threading.Lock()
+ self.send_stream = memory_stream.get_send_stream()
+ self.receive_stream = memory_stream.get_receive_stream()
+ self._key_map_by_run_id: dict[UUID, str] = {}
+ self._counter_map_by_name: dict[str, int] = defaultdict(int)
+ self.root_id: UUID | None = None
+
+ def __aiter__(self) -> AsyncIterator[RunLogPatch]:
+ """Iterate over the stream of run logs.
+
+ Returns:
+ An async iterator over the run log patches.
+ """
+ return self.receive_stream.__aiter__()
+
+ def send(self, *ops: dict[str, Any]) -> bool:
+ """Send a patch to the stream, return `False` if the stream is closed.
+
+ Args:
+ *ops: The operations to send to the stream.
+
+ Returns:
+ `True` if the patch was sent successfully, `False` if the stream is closed.
+ """
+ # We will likely want to wrap this in try / except at some point
+ # to handle exceptions that might arise at run time.
+ # For now we'll let the exception bubble up, and always return
+ # True on the happy path.
+ self.send_stream.send_nowait(RunLogPatch(*ops))
+ return True
+
+ async def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Tap an output async iterator to stream its values to the log.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output async iterator.
+
+ Yields:
+ The output value.
+ """
+ async for chunk in output:
+ # root run is handled in .astream_log()
+ # if we can't find the run silently ignore
+ # eg. because this run wasn't included in the log
+ if (
+ run_id != self.root_id
+ and (key := self._key_map_by_run_id.get(run_id))
+ and (
+ not self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{key}/streamed_output/-",
+ "value": chunk,
+ }
+ )
+ )
+ ):
+ break
+
+ yield chunk
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Tap an output iterator to stream its values to the log.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output iterator.
+
+ Yields:
+ The output value.
+ """
+ for chunk in output:
+ # root run is handled in .astream_log()
+ # if we can't find the run silently ignore
+ # eg. because this run wasn't included in the log
+ if (
+ run_id != self.root_id
+ and (key := self._key_map_by_run_id.get(run_id))
+ and (
+ not self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{key}/streamed_output/-",
+ "value": chunk,
+ }
+ )
+ )
+ ):
+ break
+
+ yield chunk
+
+ def include_run(self, run: Run) -> bool:
+ """Check if a `Run` should be included in the log.
+
+ Args:
+ run: The `Run` to check.
+
+ Returns:
+ `True` if the `Run` should be included, `False` otherwise.
+ """
+ if run.id == self.root_id:
+ return False
+
+ run_tags = run.tags or []
+
+ if (
+ self.include_names is None
+ and self.include_types is None
+ and self.include_tags is None
+ ):
+ include = True
+ else:
+ include = False
+
+ if self.include_names is not None:
+ include = include or run.name in self.include_names
+ if self.include_types is not None:
+ include = include or run.run_type in self.include_types
+ if self.include_tags is not None:
+ include = include or any(tag in self.include_tags for tag in run_tags)
+
+ if self.exclude_names is not None:
+ include = include and run.name not in self.exclude_names
+ if self.exclude_types is not None:
+ include = include and run.run_type not in self.exclude_types
+ if self.exclude_tags is not None:
+ include = include and all(tag not in self.exclude_tags for tag in run_tags)
+
+ return include
+
+ def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ def _on_run_create(self, run: Run) -> None:
+ """Start a run."""
+ if self.root_id is None:
+ self.root_id = run.id
+ if not self.send(
+ {
+ "op": "replace",
+ "path": "",
+ "value": RunState(
+ id=str(run.id),
+ streamed_output=[],
+ final_output=None,
+ logs={},
+ name=run.name,
+ type=run.run_type,
+ ),
+ }
+ ):
+ return
+
+ if not self.include_run(run):
+ return
+
+ # Determine previous index, increment by 1
+ with self.lock:
+ self._counter_map_by_name[run.name] += 1
+ count = self._counter_map_by_name[run.name]
+ self._key_map_by_run_id[run.id] = (
+ run.name if count == 1 else f"{run.name}:{count}"
+ )
+
+ entry = LogEntry(
+ id=str(run.id),
+ name=run.name,
+ type=run.run_type,
+ tags=run.tags or [],
+ metadata=(run.extra or {}).get("metadata", {}),
+ start_time=run.start_time.isoformat(timespec="milliseconds"),
+ streamed_output=[],
+ streamed_output_str=[],
+ final_output=None,
+ end_time=None,
+ )
+
+ if self._schema_format == "streaming_events":
+ # If using streaming events let's add inputs as well
+ entry["inputs"] = _get_standardized_inputs(run, self._schema_format)
+
+ # Add the run to the stream
+ self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{self._key_map_by_run_id[run.id]}",
+ "value": entry,
+ }
+ )
+
+ def _on_run_update(self, run: Run) -> None:
+ """Finish a `Run`."""
+ try:
+ index = self._key_map_by_run_id.get(run.id)
+
+ if index is None:
+ return
+
+ ops = []
+
+ if self._schema_format == "streaming_events":
+ ops.append(
+ {
+ "op": "replace",
+ "path": f"/logs/{index}/inputs",
+ "value": _get_standardized_inputs(run, self._schema_format),
+ }
+ )
+
+ ops.extend(
+ [
+ # Replace 'inputs' with final inputs
+ # This is needed because in many cases the inputs are not
+ # known until after the run is finished and the entire
+ # input stream has been processed by the runnable.
+ {
+ "op": "add",
+ "path": f"/logs/{index}/final_output",
+ # to undo the dumpd done by some runnables / tracer / etc
+ "value": _get_standardized_outputs(run, self._schema_format),
+ },
+ {
+ "op": "add",
+ "path": f"/logs/{index}/end_time",
+ "value": run.end_time.isoformat(timespec="milliseconds")
+ if run.end_time is not None
+ else None,
+ },
+ ]
+ )
+
+ self.send(*ops)
+ finally:
+ if run.id == self.root_id and self.auto_close:
+ self.send_stream.close()
+
+ def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> None:
+ """Process new LLM token."""
+ index = self._key_map_by_run_id.get(run.id)
+
+ if index is None:
+ return
+
+ self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{index}/streamed_output_str/-",
+ "value": token,
+ },
+ {
+ "op": "add",
+ "path": f"/logs/{index}/streamed_output/-",
+ "value": chunk.message
+ if isinstance(chunk, ChatGenerationChunk)
+ else token,
+ },
+ )
+
+
+def _get_standardized_inputs(
+ run: Run, schema_format: Literal["original", "streaming_events"]
+) -> Any:
+ """Extract standardized inputs from a `Run`.
+
+ Standardizes the inputs based on the type of the runnable used.
+
+ Args:
+ run: `Run` object
+ schema_format: The schema format to use.
+
+ Returns:
+ Valid inputs are only dict. By conventions, inputs always represented invocation
+ using named arguments. `None` means that the input is not yet known!
+ """
+ if schema_format == "original":
+ msg = (
+ "Do not assign inputs with original schema drop the key for now."
+ "When inputs are added to astream_log they should be added with "
+ "standardized schema for streaming events."
+ )
+ raise NotImplementedError(msg)
+
+ inputs = load(run.inputs, allowed_objects="messages")
+
+ if run.run_type in {"retriever", "llm", "chat_model"}:
+ return inputs
+
+ # new style chains
+ # These nest an additional 'input' key inside the 'inputs' to make sure
+ # the input is always a dict. We need to unpack and use the inner value.
+ inputs = inputs["input"]
+ # We should try to fix this in Runnables and callbacks/tracers
+ # Runnables should be using a None type here not a placeholder
+ # dict.
+ if inputs == {"input": ""}: # Workaround for Runnables not using None
+ # The input is not known, so we don't assign data['input']
+ return None
+ return inputs
+
+
+def _get_standardized_outputs(
+ run: Run, schema_format: Literal["original", "streaming_events", "original+chat"]
+) -> Any | None:
+ """Extract standardized output from a run.
+
+ Standardizes the outputs based on the type of the runnable used.
+
+ Args:
+ run: the run object.
+ schema_format: The schema format to use.
+
+ Returns:
+ An output if returned, otherwise `None`.
+ """
+ outputs = load(run.outputs, allowed_objects="messages")
+ if schema_format == "original":
+ if run.run_type == "prompt" and "output" in outputs:
+ # These were previously dumped before the tracer.
+ # Now we needn't do anything to them.
+ return outputs["output"]
+ # Return the old schema, without standardizing anything
+ return outputs
+
+ if run.run_type in {"retriever", "llm", "chat_model"}:
+ return outputs
+
+ if isinstance(outputs, dict):
+ return outputs.get("output", None)
+
+ return None
+
+
+@overload
+def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: Literal[True] = True,
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLogPatch]: ...
+
+
+@overload
+def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: Literal[False],
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLog]: ...
+
+
+async def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: bool = True,
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]:
+ """Implementation of astream_log for a given runnable.
+
+ The implementation has been factored out (at least temporarily) as both
+ `astream_log` and `astream_events` rely on it.
+
+ Args:
+ runnable: The runnable to run in streaming mode.
+ value: The input to the runnable.
+ config: The config to pass to the runnable.
+ stream: The stream to send the run logs to.
+ diff: Whether to yield run log patches (`True`) or full run logs (`False`).
+ with_streamed_output_list: Whether to include a list of all streamed outputs in
+ each patch. If `False`, only the final output will be included in the
+ patches.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Raises:
+ ValueError: If the callbacks in the config are of an unexpected type.
+
+ Yields:
+ The run log patches or states, depending on the value of `diff`.
+ """
+ # Assign the stream handler to the config
+ config = ensure_config(config)
+ callbacks = config.get("callbacks")
+ if callbacks is None:
+ config["callbacks"] = [stream]
+ elif isinstance(callbacks, list):
+ config["callbacks"] = [*callbacks, stream]
+ elif isinstance(callbacks, BaseCallbackManager):
+ callbacks = callbacks.copy()
+ callbacks.add_handler(stream, inherit=True)
+ config["callbacks"] = callbacks
+ else:
+ msg = (
+ f"Unexpected type for callbacks: {callbacks}."
+ "Expected None, list or AsyncCallbackManager."
+ )
+ raise ValueError(msg)
+
+ # Call the runnable in streaming mode,
+ # add each chunk to the output stream
+ async def consume_astream() -> None:
+ try:
+ prev_final_output: Output | None = None
+ final_output: Output | None = None
+
+ async for chunk in runnable.astream(value, config, **kwargs):
+ prev_final_output = final_output
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ prev_final_output = None
+ final_output = chunk
+ patches: list[dict[str, Any]] = []
+ if with_streamed_output_list:
+ patches.append(
+ {
+ "op": "add",
+ "path": "/streamed_output/-",
+ # chunk cannot be shared between
+ # streamed_output and final_output
+ # otherwise jsonpatch.apply will
+ # modify both
+ "value": copy.deepcopy(chunk),
+ }
+ )
+ patches.extend(
+ {**op, "path": f"/final_output{op['path']}"}
+ for op in jsonpatch.JsonPatch.from_diff(
+ prev_final_output, final_output, dumps=dumps
+ )
+ )
+ await stream.send_stream.send(RunLogPatch(*patches))
+ finally:
+ await stream.send_stream.aclose()
+
+ # Start the runnable in a task, so we can start consuming output
+ task = asyncio.create_task(consume_astream())
+ try:
+ # Yield each chunk from the output stream
+ if diff:
+ async for log in stream:
+ yield log
+ else:
+ state = RunLog(state=None) # type: ignore[arg-type]
+ async for log in stream:
+ state += log
+ yield state
+ finally:
+ # Wait for the runnable to finish, if not cancelled (eg. by break)
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/memory_stream.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/memory_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..42e74fb00d9d82e2bd6c6a261f3b9eb2b1492582
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/memory_stream.py
@@ -0,0 +1,148 @@
+"""Module implements a memory stream for communication between two co-routines.
+
+This module provides a way to communicate between two co-routines using a memory
+channel. The writer and reader can be in the same event loop or in different event
+loops. When they're in different event loops, they will also be in different threads.
+
+Useful in situations when there's a mix of synchronous and asynchronous used in the
+code.
+"""
+
+import asyncio
+from asyncio import AbstractEventLoop, Queue
+from collections.abc import AsyncIterator
+from typing import Generic, TypeVar
+
+T = TypeVar("T")
+
+
+class _SendStream(Generic[T]):
+ def __init__(
+ self, reader_loop: AbstractEventLoop, queue: Queue, done: object
+ ) -> None:
+ """Create a writer for the queue and done object.
+
+ Args:
+ reader_loop: The event loop to use for the writer.
+
+ This loop will be used to schedule the writes to the queue.
+ queue: The queue to write to.
+
+ This is an asyncio queue.
+ done: Special sentinel object to indicate that the writer is done.
+ """
+ self._reader_loop = reader_loop
+ self._queue = queue
+ self._done = done
+
+ async def send(self, item: T) -> None:
+ """Schedule the item to be written to the queue using the original loop.
+
+ This is a coroutine that can be awaited.
+
+ Args:
+ item: The item to write to the queue.
+ """
+ return self.send_nowait(item)
+
+ def send_nowait(self, item: T) -> None:
+ """Schedule the item to be written to the queue using the original loop.
+
+ This is a non-blocking call.
+
+ Args:
+ item: The item to write to the queue.
+
+ Raises:
+ RuntimeError: If the event loop is already closed when trying to write to
+ the queue.
+ """
+ try:
+ self._reader_loop.call_soon_threadsafe(self._queue.put_nowait, item)
+ except RuntimeError:
+ if not self._reader_loop.is_closed():
+ raise # Raise the exception if the loop is not closed
+
+ async def aclose(self) -> None:
+ """Async schedule the done object write the queue using the original loop."""
+ return self.close()
+
+ def close(self) -> None:
+ """Schedule the done object write the queue using the original loop.
+
+ This is a non-blocking call.
+
+ Raises:
+ RuntimeError: If the event loop is already closed when trying to write to
+ the queue.
+ """
+ try:
+ self._reader_loop.call_soon_threadsafe(self._queue.put_nowait, self._done)
+ except RuntimeError:
+ if not self._reader_loop.is_closed():
+ raise # Raise the exception if the loop is not closed
+
+
+class _ReceiveStream(Generic[T]):
+ def __init__(self, queue: Queue, done: object) -> None:
+ """Create a reader for the queue and done object.
+
+ This reader should be used in the same loop as the loop that was passed to the
+ channel.
+ """
+ self._queue = queue
+ self._done = done
+ self._is_closed = False
+
+ async def __aiter__(self) -> AsyncIterator[T]:
+ while True:
+ item = await self._queue.get()
+ if item is self._done:
+ self._is_closed = True
+ break
+ yield item
+
+
+class _MemoryStream(Generic[T]):
+ """Stream data from a writer to a reader even if they are in different threads.
+
+ Uses asyncio queues to communicate between two co-routines. This implementation
+ should work even if the writer and reader co-routines belong to two different event
+ loops (e.g. one running from an event loop in the main thread and the other running
+ in an event loop in a background thread).
+
+ This implementation is meant to be used with a single writer and a single reader.
+
+ This is an internal implementation to LangChain. Do not use it directly.
+ """
+
+ def __init__(self, loop: AbstractEventLoop) -> None:
+ """Create a channel for the given loop.
+
+ Args:
+ loop: The event loop to use for the channel.
+
+ The reader is assumed to be running in the same loop as the one passed
+ to this constructor. This will NOT be validated at run time.
+ """
+ self._loop = loop
+ self._queue: asyncio.Queue = asyncio.Queue(maxsize=0)
+ self._done = object()
+
+ def get_send_stream(self) -> _SendStream[T]:
+ """Get a writer for the channel.
+
+ Returns:
+ The writer for the channel.
+ """
+ return _SendStream[T](
+ reader_loop=self._loop, queue=self._queue, done=self._done
+ )
+
+ def get_receive_stream(self) -> _ReceiveStream[T]:
+ """Get a reader for the channel.
+
+ Returns:
+ The reader for the channel.
+ """
+ return _ReceiveStream[T](queue=self._queue, done=self._done)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/root_listeners.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/root_listeners.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d1c90612e9aafd5e22e50b1a931e2ce083f4e68
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/root_listeners.py
@@ -0,0 +1,130 @@
+"""Tracers that call listeners."""
+
+from collections.abc import Awaitable, Callable
+from typing import TYPE_CHECKING
+
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+)
+from langchain_core.tracers.base import AsyncBaseTracer, BaseTracer
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from uuid import UUID
+
+Listener = Callable[[Run], None] | Callable[[Run, RunnableConfig], None]
+AsyncListener = (
+ Callable[[Run], Awaitable[None]] | Callable[[Run, RunnableConfig], Awaitable[None]]
+)
+
+
+class RootListenersTracer(BaseTracer):
+ """Tracer that calls listeners on run start, end, and error."""
+
+ log_missing_parent = False
+ """Whether to log a warning if the parent is missing."""
+
+ def __init__(
+ self,
+ *,
+ config: RunnableConfig,
+ on_start: Listener | None,
+ on_end: Listener | None,
+ on_error: Listener | None,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ config: The runnable config.
+ on_start: The listener to call on run start.
+ on_end: The listener to call on run end.
+ on_error: The listener to call on run error
+ """
+ super().__init__(_schema_format="original+chat")
+
+ self.config = config
+ self._arg_on_start = on_start
+ self._arg_on_end = on_end
+ self._arg_on_error = on_error
+ self.root_id: UUID | None = None
+
+ def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ def _on_run_create(self, run: Run) -> None:
+ if self.root_id is not None:
+ return
+
+ self.root_id = run.id
+
+ if self._arg_on_start is not None:
+ call_func_with_variable_args(self._arg_on_start, run, self.config)
+
+ def _on_run_update(self, run: Run) -> None:
+ if run.id != self.root_id:
+ return
+
+ if run.error is None:
+ if self._arg_on_end is not None:
+ call_func_with_variable_args(self._arg_on_end, run, self.config)
+ elif self._arg_on_error is not None:
+ call_func_with_variable_args(self._arg_on_error, run, self.config)
+
+
+class AsyncRootListenersTracer(AsyncBaseTracer):
+ """Async tracer that calls listeners on run start, end, and error."""
+
+ log_missing_parent = False
+ """Whether to log a warning if the parent is missing."""
+
+ def __init__(
+ self,
+ *,
+ config: RunnableConfig,
+ on_start: AsyncListener | None,
+ on_end: AsyncListener | None,
+ on_error: AsyncListener | None,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ config: The runnable config.
+ on_start: The listener to call on run start.
+ on_end: The listener to call on run end.
+ on_error: The listener to call on run error
+ """
+ super().__init__(_schema_format="original+chat")
+
+ self.config = config
+ self._arg_on_start = on_start
+ self._arg_on_end = on_end
+ self._arg_on_error = on_error
+ self.root_id: UUID | None = None
+
+ async def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ async def _on_run_create(self, run: Run) -> None:
+ if self.root_id is not None:
+ return
+
+ self.root_id = run.id
+
+ if self._arg_on_start is not None:
+ await acall_func_with_variable_args(self._arg_on_start, run, self.config)
+
+ async def _on_run_update(self, run: Run) -> None:
+ if run.id != self.root_id:
+ return
+
+ if run.error is None:
+ if self._arg_on_end is not None:
+ await acall_func_with_variable_args(self._arg_on_end, run, self.config)
+ elif self._arg_on_error is not None:
+ await acall_func_with_variable_args(self._arg_on_error, run, self.config)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/run_collector.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/run_collector.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d389af2721ca7be7e48b7899f247919069c01a1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/run_collector.py
@@ -0,0 +1,40 @@
+"""A tracer that collects all nested runs in a list."""
+
+from typing import Any
+from uuid import UUID
+
+from langchain_core.tracers._compat import run_copy
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+
+
+class RunCollectorCallbackHandler(BaseTracer):
+ """Tracer that collects all nested runs in a list.
+
+ This tracer is useful for inspection and evaluation purposes.
+ """
+
+ name: str = "run-collector_callback_handler"
+
+ def __init__(self, example_id: UUID | str | None = None, **kwargs: Any) -> None:
+ """Initialize the `RunCollectorCallbackHandler`.
+
+ Args:
+ example_id: The ID of the example being traced.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.traced_runs: list[Run] = []
+
+ def _persist_run(self, run: Run) -> None:
+ """Persist a run by adding it to the `traced_runs` list.
+
+ Args:
+ run: The run to be persisted.
+ """
+ run_ = run_copy(run)
+ run_.reference_example_id = self.example_id
+ self.traced_runs.append(run_)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/schemas.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/schemas.py
new file mode 100644
index 0000000000000000000000000000000000000000..67a37035b4dc4e12007d680ac37154dc1c9a1d3b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/schemas.py
@@ -0,0 +1,14 @@
+"""Schemas for tracers."""
+
+from __future__ import annotations
+
+from langsmith import RunTree
+
+# Begin V2 API Schemas
+
+
+Run = RunTree # For backwards compatibility
+
+__all__ = [
+ "Run",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/tracers/stdout.py b/python/user_packages/Python313/site-packages/langchain_core/tracers/stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..b47bb512a6e6ebd9fc4147c3d9df815eb580ea9a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/tracers/stdout.py
@@ -0,0 +1,205 @@
+"""Tracers that print to the console."""
+
+import json
+from collections.abc import Callable
+from typing import Any
+
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+from langchain_core.utils.input import get_bolded_text, get_colored_text
+
+MILLISECONDS_IN_SECOND = 1000
+
+
+def try_json_stringify(obj: Any, fallback: str) -> str:
+ """Try to stringify an object to JSON.
+
+ Args:
+ obj: Object to stringify.
+ fallback: Fallback string to return if the object cannot be stringified.
+
+ Returns:
+ A JSON string if the object can be stringified, otherwise the fallback string.
+ """
+ try:
+ return json.dumps(obj, indent=2, ensure_ascii=False)
+ except Exception:
+ return fallback
+
+
+def elapsed(run: Any) -> str:
+ """Get the elapsed time of a run.
+
+ Args:
+ run: any object with a `start_time` and `end_time` attribute.
+
+ Returns:
+ A string with the elapsed time in seconds or milliseconds if time is less than a
+ second.
+
+ """
+ elapsed_time = run.end_time - run.start_time
+ seconds = elapsed_time.total_seconds()
+ if seconds < 1:
+ return f"{seconds * MILLISECONDS_IN_SECOND:.0f}ms"
+ return f"{seconds:.2f}s"
+
+
+class FunctionCallbackHandler(BaseTracer):
+ """Tracer that calls a function with a single str parameter."""
+
+ name: str = "function_callback_handler"
+ """The name of the tracer.
+
+ This is used to identify the tracer in the logs.
+ """
+
+ def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:
+ """Create a `FunctionCallbackHandler`.
+
+ Args:
+ function: The callback function to call.
+ """
+ super().__init__(**kwargs)
+ self.function_callback = function
+
+ def _persist_run(self, run: Run) -> None:
+ pass
+
+ def get_parents(self, run: Run) -> list[Run]:
+ """Get the parents of a run.
+
+ Args:
+ run: The run to get the parents of.
+
+ Returns:
+ A list of parent runs.
+ """
+ parents = []
+ current_run = run
+ while current_run.parent_run_id:
+ parent = self.run_map.get(str(current_run.parent_run_id))
+ if parent:
+ parents.append(parent)
+ current_run = parent
+ else:
+ break
+ return parents
+
+ def get_breadcrumbs(self, run: Run) -> str:
+ """Get the breadcrumbs of a run.
+
+ Args:
+ run: The run to get the breadcrumbs of.
+
+ Returns:
+ A string with the breadcrumbs of the run.
+ """
+ parents = self.get_parents(run)[::-1]
+ return " > ".join(
+ f"{parent.run_type}:{parent.name}"
+ for i, parent in enumerate([*parents, run])
+ )
+
+ # logging methods
+ def _on_chain_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering {run_type} run with input:\n")
+ + f"{try_json_stringify(run.inputs, '[inputs]')}"
+ )
+
+ def _on_chain_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting {run_type} run with output:\n"
+ )
+ + f"{try_json_stringify(run.outputs, '[outputs]')}"
+ )
+
+ def _on_chain_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/error]', color='red')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] {run_type} run errored with error:\n"
+ )
+ + f"{try_json_stringify(run.error, '[error]')}"
+ )
+
+ def _on_llm_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ inputs = (
+ {"prompts": [p.strip() for p in run.inputs["prompts"]]}
+ if "prompts" in run.inputs
+ else run.inputs
+ )
+ self.function_callback(
+ f"{get_colored_text('[llm/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering LLM run with input:\n")
+ + f"{try_json_stringify(inputs, '[inputs]')}"
+ )
+
+ def _on_llm_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[llm/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting LLM run with output:\n"
+ )
+ + f"{try_json_stringify(run.outputs, '[response]')}"
+ )
+
+ def _on_llm_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[llm/error]', color='red')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] LLM run errored with error:\n"
+ )
+ + f"{try_json_stringify(run.error, '[error]')}"
+ )
+
+ def _on_tool_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[tool/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering Tool run with input:\n")
+ + f'"{run.inputs["input"].strip()}"'
+ )
+
+ def _on_tool_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ if run.outputs:
+ self.function_callback(
+ f"{get_colored_text('[tool/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting Tool run with output:\n"
+ )
+ + f'"{str(run.outputs["output"]).strip()}"'
+ )
+
+ def _on_tool_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[tool/error]', color='red')} "
+ + get_bolded_text(f"[{crumbs}] [{elapsed(run)}] ")
+ + f"Tool run errored with error:\n"
+ f"{run.error}"
+ )
+
+
+class ConsoleCallbackHandler(FunctionCallbackHandler):
+ """Tracer that prints to the console."""
+
+ name: str = "console_callback_handler"
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Create a ConsoleCallbackHandler."""
+ super().__init__(function=print, **kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0421658370240aa7e3ae6d9584c88d65f6820595
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/__init__.py
@@ -0,0 +1,111 @@
+"""Utility functions for LangChain.
+
+These functions do not depend on any other LangChain module.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ # for type checking and IDE support, we include the imports here
+ # but we don't want to eagerly import them at runtime
+ from langchain_core.utils import image
+ from langchain_core.utils.aiter import abatch_iterate
+ from langchain_core.utils.env import get_from_dict_or_env, get_from_env
+ from langchain_core.utils.formatting import StrictFormatter, formatter
+ from langchain_core.utils.input import (
+ get_bolded_text,
+ get_color_mapping,
+ get_colored_text,
+ print_text,
+ )
+ from langchain_core.utils.iter import batch_iterate
+ from langchain_core.utils.pydantic import pre_init
+ from langchain_core.utils.strings import (
+ comma_list,
+ sanitize_for_postgres,
+ stringify_dict,
+ stringify_value,
+ )
+ from langchain_core.utils.utils import (
+ build_extra_kwargs,
+ check_package_version,
+ convert_to_secret_str,
+ from_env,
+ get_pydantic_field_names,
+ guard_import,
+ mock_now,
+ raise_for_status_with_text,
+ secret_from_env,
+ xor_args,
+ )
+
+__all__ = (
+ "StrictFormatter",
+ "abatch_iterate",
+ "batch_iterate",
+ "build_extra_kwargs",
+ "check_package_version",
+ "comma_list",
+ "convert_to_secret_str",
+ "formatter",
+ "from_env",
+ "get_bolded_text",
+ "get_color_mapping",
+ "get_colored_text",
+ "get_from_dict_or_env",
+ "get_from_env",
+ "get_pydantic_field_names",
+ "guard_import",
+ "image",
+ "mock_now",
+ "pre_init",
+ "print_text",
+ "raise_for_status_with_text",
+ "sanitize_for_postgres",
+ "secret_from_env",
+ "stringify_dict",
+ "stringify_value",
+ "xor_args",
+)
+
+_dynamic_imports = {
+ "image": "__module__",
+ "abatch_iterate": "aiter",
+ "get_from_dict_or_env": "env",
+ "get_from_env": "env",
+ "StrictFormatter": "formatting",
+ "formatter": "formatting",
+ "get_bolded_text": "input",
+ "get_color_mapping": "input",
+ "get_colored_text": "input",
+ "print_text": "input",
+ "batch_iterate": "iter",
+ "pre_init": "pydantic",
+ "comma_list": "strings",
+ "sanitize_for_postgres": "strings",
+ "stringify_dict": "strings",
+ "stringify_value": "strings",
+ "build_extra_kwargs": "utils",
+ "check_package_version": "utils",
+ "convert_to_secret_str": "utils",
+ "from_env": "utils",
+ "get_pydantic_field_names": "utils",
+ "guard_import": "utils",
+ "mock_now": "utils",
+ "secret_from_env": "utils",
+ "xor_args": "utils",
+ "raise_for_status_with_text": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eef49bd681822f58a7b4413f57ff406b70a0f5f4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/_merge.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/_merge.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8540cdd0b8dfbc3a68f138087b534bd1f5bfc773
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/_merge.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/aiter.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/aiter.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2d6d4766e613cdc4d26490e27c7280c24cc1b35
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/aiter.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/env.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/env.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..401371a7b4da981389177f4ec57eb516915a0dd0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/env.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/formatting.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/formatting.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5e6aa8a6b11ebce020fd9441996eee0f3bb3686
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/formatting.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afd569c99fab70aaafb46bd879d820629fed948e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/html.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/html.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9a98c78f08eb3afd43f3620c8d9605aa112c2a4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/html.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/image.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/image.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01a191f873b64be44c83419d2e05f5f50e4daac1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/image.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/input.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/input.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..902005cd444a619e1d887ff4320afb49200389f4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/input.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..479bd6199ca9e3ec0c486f6a527d9af5b8fb42a2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/iter.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/iter.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f978cfe6f601862416c8ac242c34dabc4d17a7cc
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/iter.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46f01ed6a51e00f45979d8da658406513cc8a3e5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a97e1ae8d5278f5f218c288320efab0f699a34f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/mustache.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/mustache.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2e25d4f122bb010375c64ba3113618978635b02
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/mustache.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..320959a0053386c7da963764cb2132a51a791a39
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/strings.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/strings.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fc01fa1cb417daa38bc85974558fb7d3e7ebaea
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/strings.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/usage.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/usage.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f902ee7ee87a3a8012f20b2eeed832ed6ecaa21
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/usage.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64cff6d9e5ab8b1db60ef23fc6c3e5f9d545b870
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/uuid.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/uuid.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74a3845e4a53477c78caba052a0d4cebe5a20aae
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/utils/__pycache__/uuid.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/_merge.py b/python/user_packages/Python313/site-packages/langchain_core/utils/_merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a0cb38f078509ecfb646b6e75981653b9389c4e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/_merge.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:
+ r"""Merge dictionaries.
+
+ Merge many dicts, handling specific scenarios where a key exists in both
+ dictionaries but has a value of `None` in `'left'`. In such cases, the method uses
+ the value from `'right'` for that key in the merged dictionary.
+
+ Args:
+ left: The first dictionary to merge.
+ others: The other dictionaries to merge.
+
+ Returns:
+ The merged dictionary.
+
+ Raises:
+ TypeError: If the key exists in both dictionaries but has a different type.
+ TypeError: If the value has an unsupported type.
+
+ Example:
+ If `left = {"function_call": {"arguments": None}}` and
+ `right = {"function_call": {"arguments": "{\n"}}`, then, after merging, for the
+ key `'function_call'`, the value from `'right'` is used, resulting in
+ `merged = {"function_call": {"arguments": "{\n"}}`.
+ """
+ merged = left.copy()
+ for right in others:
+ for right_k, right_v in right.items():
+ if right_k not in merged or (
+ right_v is not None and merged[right_k] is None
+ ):
+ merged[right_k] = right_v
+ elif right_v is None:
+ continue
+ elif type(merged[right_k]) is not type(right_v):
+ msg = (
+ f'additional_kwargs["{right_k}"] already exists in this message,'
+ " but with a different type."
+ )
+ raise TypeError(msg)
+ elif isinstance(merged[right_k], str):
+ # TODO: Add below special handling for 'type' key in 0.3 and remove
+ # merge_lists 'type' logic.
+ #
+ # if right_k == "type":
+ # if merged[right_k] == right_v:
+ # continue
+ # else:
+ # raise ValueError(
+ # "Unable to merge. Two different values seen for special "
+ # f"key 'type': {merged[right_k]} and {right_v}. 'type' "
+ # "should either occur once or have the same value across "
+ # "all dicts."
+ # )
+ if (right_k == "index" and merged[right_k].startswith("lc_")) or (
+ right_k in {"id", "output_version", "model_provider"}
+ and merged[right_k] == right_v
+ ):
+ continue
+ merged[right_k] += right_v
+ elif isinstance(merged[right_k], dict):
+ merged[right_k] = merge_dicts(merged[right_k], right_v)
+ elif isinstance(merged[right_k], list):
+ merged[right_k] = merge_lists(merged[right_k], right_v)
+ elif merged[right_k] == right_v:
+ continue
+ elif isinstance(merged[right_k], int):
+ # Preserve identification and temporal fields using last-wins strategy
+ # instead of summing:
+ # - index: identifies which tool call a chunk belongs to
+ # - created/timestamp: temporal values that shouldn't be accumulated
+ if right_k in {"index", "created", "timestamp"}:
+ merged[right_k] = right_v
+ else:
+ merged[right_k] += right_v
+ else:
+ msg = (
+ f"Additional kwargs key {right_k} already exists in left dict and "
+ f"value has unsupported type {type(merged[right_k])}."
+ )
+ raise TypeError(msg)
+ return merged
+
+
+def merge_lists(left: list | None, *others: list | None) -> list | None:
+ """Add many lists, handling `None`.
+
+ Args:
+ left: The first list to merge.
+ others: The other lists to merge.
+
+ Returns:
+ The merged list.
+ """
+ merged = left.copy() if left is not None else None
+ for other in others:
+ if other is None:
+ continue
+ if merged is None:
+ merged = other.copy()
+ else:
+ for e in other:
+ if (
+ isinstance(e, dict)
+ and "index" in e
+ and (
+ isinstance(e["index"], int)
+ or (
+ isinstance(e["index"], str) and e["index"].startswith("lc_")
+ )
+ )
+ ):
+ to_merge = [
+ i
+ for i, e_left in enumerate(merged)
+ if (
+ "index" in e_left
+ and e_left["index"] == e["index"] # index matches
+ and ( # IDs not inconsistent
+ e_left.get("id") in (None, "")
+ or e.get("id") in (None, "")
+ or e_left.get("id") == e.get("id")
+ )
+ )
+ ]
+ if to_merge:
+ # TODO: Remove this once merge_dict is updated with special
+ # handling for 'type'.
+ if (left_type := merged[to_merge[0]].get("type")) and (
+ e.get("type") == "non_standard" and "value" in e
+ ):
+ if left_type != "non_standard":
+ # standard + non_standard
+ new_e: dict[str, Any] = {
+ "extras": {
+ k: v
+ for k, v in e["value"].items()
+ if k != "type"
+ }
+ }
+ else:
+ # non_standard + non_standard
+ new_e = {
+ "value": {
+ k: v
+ for k, v in e["value"].items()
+ if k != "type"
+ }
+ }
+ if "index" in e:
+ new_e["index"] = e["index"]
+ else:
+ new_e = (
+ {k: v for k, v in e.items() if k != "type"}
+ if "type" in e
+ else e
+ )
+ merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], new_e)
+ else:
+ merged.append(e)
+ else:
+ merged.append(e)
+ return merged
+
+
+def merge_obj(left: Any, right: Any) -> Any:
+ """Merge two objects.
+
+ It handles specific scenarios where a key exists in both dictionaries but has a
+ value of `None` in `'left'`. In such cases, the method uses the value from `'right'`
+ for that key in the merged dictionary.
+
+ Args:
+ left: The first object to merge.
+ right: The other object to merge.
+
+ Returns:
+ The merged object.
+
+ Raises:
+ TypeError: If the key exists in both dictionaries but has a different type.
+ ValueError: If the two objects cannot be merged.
+ """
+ if left is None or right is None:
+ return left if left is not None else right
+ if type(left) is not type(right):
+ msg = (
+ f"left and right are of different types. Left type: {type(left)}. Right "
+ f"type: {type(right)}."
+ )
+ raise TypeError(msg)
+ if isinstance(left, str):
+ return left + right
+ if isinstance(left, dict):
+ return merge_dicts(left, right)
+ if isinstance(left, list):
+ return merge_lists(left, right)
+ if left == right:
+ return left
+ msg = (
+ f"Unable to merge {left=} and {right=}. Both must be of type str, dict, or "
+ f"list, or else be two equal objects."
+ )
+ raise ValueError(msg)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/aiter.py b/python/user_packages/Python313/site-packages/langchain_core/utils/aiter.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc0d1aea2ebb99269d9c913b911eaeb2979f90
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/aiter.py
@@ -0,0 +1,347 @@
+"""Asynchronous iterator utilities.
+
+Adapted from
+https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
+MIT License.
+"""
+
+from collections import deque
+from collections.abc import (
+ AsyncGenerator,
+ AsyncIterable,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+)
+from contextlib import AbstractAsyncContextManager
+from types import TracebackType
+from typing import (
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+ overload,
+)
+
+from typing_extensions import override
+
+from langchain_core._api.deprecation import deprecated
+
+T = TypeVar("T")
+
+_no_default = object()
+
+
+# https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
+@deprecated(since="1.1.2", removal="2.0.0")
+def py_anext(
+ iterator: AsyncIterator[T], default: T | Any = _no_default
+) -> Awaitable[T | Any | None]:
+ """Pure-Python implementation of `anext()` for testing purposes.
+
+ Closely matches the builtin `anext()` C implementation.
+
+ Can be used to compare the built-in implementation of the inner coroutines machinery
+ to C-implementation of `__anext__()` and `send()` or `throw()` on the returned
+ generator.
+
+ Args:
+ iterator: The async iterator to advance.
+ default: The value to return if the iterator is exhausted.
+
+ If not provided, a `StopAsyncIteration` exception is raised.
+
+ Returns:
+ The next value from the iterator, or the default value if the iterator is
+ exhausted.
+
+ Raises:
+ TypeError: If the iterator is not an async iterator.
+ """
+ try:
+ __anext__ = cast(
+ "Callable[[AsyncIterator[T]], Awaitable[T]]", type(iterator).__anext__
+ )
+ except AttributeError as e:
+ msg = f"{iterator!r} is not an async iterator"
+ raise TypeError(msg) from e
+
+ if default is _no_default:
+ return __anext__(iterator)
+
+ async def anext_impl() -> T | Any:
+ try:
+ # The C code is way more low-level than this, as it implements
+ # all methods of the iterator protocol. In this implementation
+ # we're relying on higher-level coroutine concepts, but that's
+ # exactly what we want -- crosstest pure-Python high-level
+ # implementation and low-level C anext() iterators.
+ return await __anext__(iterator)
+ except StopAsyncIteration:
+ return default
+
+ return anext_impl()
+
+
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection."""
+
+ async def __aenter__(self) -> None:
+ """Do nothing."""
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool:
+ """Return False, exception not suppressed."""
+ return False
+
+
+async def tee_peer(
+ iterator: AsyncIterator[T],
+ # the buffer specific to this peer
+ buffer: deque[T],
+ # the buffers of all peers, including our own
+ peers: list[deque[T]],
+ lock: AbstractAsyncContextManager[Any],
+) -> AsyncGenerator[T, None]:
+ """An individual iterator of a `tee`.
+
+ This function is a generator that yields items from the shared iterator
+ `iterator`. It buffers items until the least advanced iterator has yielded them as
+ well.
+
+ The buffer is shared with all other peers.
+
+ Args:
+ iterator: The shared iterator.
+ buffer: The buffer for this peer.
+ peers: The buffers of all peers.
+ lock: The lock to synchronise access to the shared buffers.
+
+ Yields:
+ The next item from the shared iterator.
+ """
+ try:
+ while True:
+ if not buffer:
+ async with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = await anext(iterator)
+ except StopAsyncIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
+ yield buffer.popleft()
+ finally:
+ async with lock:
+ # this peer is done - remove its buffer
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
+ if peer_buffer is buffer:
+ peers.pop(idx)
+ break
+ # if we are the last peer, try and close the iterator
+ if not peers and hasattr(iterator, "aclose"):
+ await iterator.aclose()
+
+
+class Tee(Generic[T]):
+ """Create `n` separate asynchronous iterators over `iterable`.
+
+ This splits a single `iterable` into multiple iterators, each providing
+ the same items in the same order.
+
+ All child iterators may advance separately but share the same items from `iterable`
+ -- when the most advanced iterator retrieves an item, it is buffered until the least
+ advanced iterator has yielded it as well.
+
+ A `tee` works lazily and can handle an infinite `iterable`, provided
+ that all iterators advance.
+
+ ```python
+ async def derivative(sensor_data):
+ previous, current = a.tee(sensor_data, n=2)
+ await a.anext(previous) # advance one iterator
+ return a.map(operator.sub, previous, current)
+ ```
+
+ Unlike `itertools.tee`, `.tee` returns a custom type instead of a `tuple`. Like a
+ tuple, it can be indexed, iterated and unpacked to get the child iterators. In
+ addition, its `.tee.aclose` method immediately closes all children, and it can be
+ used in an `async with` context for the same effect.
+
+ If `iterable` is an iterator and read elsewhere, `tee` will *not* provide these
+ items. Also, `tee` must internally buffer each item until the last iterator has
+ yielded it; if the most and least advanced iterator differ by most data, using a
+ `list` is more efficient (but not lazy).
+
+ If the underlying iterable is concurrency safe (`anext` may be awaited concurrently)
+ the resulting iterators are concurrency safe as well. Otherwise, the iterators are
+ safe if there is only ever one single "most advanced" iterator.
+
+ To enforce sequential use of `anext`, provide a `lock`
+
+ - e.g. an `asyncio.Lock` instance in an `asyncio` application - and access is
+ automatically synchronised.
+
+ """
+
+ def __init__(
+ self,
+ iterable: AsyncIterator[T],
+ n: int = 2,
+ *,
+ lock: AbstractAsyncContextManager[Any] | None = None,
+ ):
+ """Create a `tee`.
+
+ Args:
+ iterable: The iterable to split.
+ n: The number of iterators to create.
+ lock: The lock to synchronise access to the shared buffers.
+
+ """
+ self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
+ self._children = tuple(
+ tee_peer(
+ iterator=self._iterator,
+ buffer=buffer,
+ peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
+ )
+ for buffer in self._buffers
+ )
+
+ def __len__(self) -> int:
+ """Return the number of child iterators."""
+ return len(self._children)
+
+ @overload
+ def __getitem__(self, item: int) -> AsyncIterator[T]: ...
+
+ @overload
+ def __getitem__(self, item: slice) -> tuple[AsyncIterator[T], ...]: ...
+
+ def __getitem__(
+ self, item: int | slice
+ ) -> AsyncIterator[T] | tuple[AsyncIterator[T], ...]:
+ """Return the child iterator(s) for the given index or slice."""
+ return self._children[item]
+
+ def __iter__(self) -> Iterator[AsyncIterator[T]]:
+ """Iterate over the child iterators.
+
+ Yields:
+ The child iterators.
+ """
+ yield from self._children
+
+ async def __aenter__(self) -> "Tee[T]":
+ """Return the tee instance."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool:
+ """Close all child iterators.
+
+ Returns:
+ `False`, exceptions not suppressed.
+ """
+ await self.aclose()
+ return False
+
+ async def aclose(self) -> None:
+ """Async close all child iterators."""
+ for child in self._children:
+ await child.aclose()
+
+
+atee = Tee
+
+
+class aclosing(AbstractAsyncContextManager): # noqa: N801
+ """Async context manager to wrap an `AsyncGenerator` that has a `aclose()` method.
+
+ Code like this:
+
+ ```python
+ async with aclosing(.fetch()) as agen:
+
+ ```
+
+ ...is equivalent to this:
+
+ ```python
+ agen = .fetch()
+ try:
+
+ finally:
+ await agen.aclose()
+
+ ```
+ """
+
+ def __init__(self, thing: AsyncGenerator[Any, Any] | AsyncIterator[Any]) -> None:
+ """Create the context manager.
+
+ Args:
+ thing: The resource to wrap.
+ """
+ self.thing = thing
+
+ @override
+ async def __aenter__(self) -> AsyncGenerator[Any, Any] | AsyncIterator[Any]:
+ return self.thing
+
+ @override
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ if hasattr(self.thing, "aclose"):
+ await self.thing.aclose()
+
+
+async def abatch_iterate(
+ size: int, iterable: AsyncIterable[T]
+) -> AsyncIterator[list[T]]:
+ """Utility batching function for async iterables.
+
+ Args:
+ size: The size of the batch.
+ iterable: The async iterable to batch.
+
+ Yields:
+ The batches.
+ """
+ batch: list[T] = []
+ async for element in iterable:
+ if len(batch) < size:
+ batch.append(element)
+
+ if len(batch) >= size:
+ yield batch
+ batch = []
+
+ if batch:
+ yield batch
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/env.py b/python/user_packages/Python313/site-packages/langchain_core/utils/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8eab221bfe1fd3827cfc401aa474bc7bbd2a06b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/env.py
@@ -0,0 +1,86 @@
+"""Utilities for environment variables."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+
+def env_var_is_set(env_var: str) -> bool:
+ """Check if an environment variable is set.
+
+ Args:
+ env_var: The name of the environment variable.
+
+ Returns:
+ `True` if the environment variable is set, `False` otherwise.
+ """
+ return env_var in os.environ and os.environ[env_var] not in {
+ "",
+ "0",
+ "false",
+ "False",
+ }
+
+
+def get_from_dict_or_env(
+ data: dict[str, Any],
+ key: str | list[str],
+ env_key: str,
+ default: str | None = None,
+) -> str:
+ """Get a value from a dictionary or an environment variable.
+
+ Args:
+ data: The dictionary to look up the key in.
+ key: The key to look up in the dictionary.
+
+ This can be a list of keys to try in order.
+ env_key: The environment variable to look up if the key is not
+ in the dictionary.
+ default: The default value to return if the key is not in the dictionary
+ or the environment.
+
+ Returns:
+ The dict value or the environment variable value.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if value := data.get(k):
+ return str(value)
+
+ if isinstance(key, str) and key in data and data[key]:
+ return str(data[key])
+
+ key_for_err = key[0] if isinstance(key, (list, tuple)) else key
+
+ return get_from_env(key_for_err, env_key, default=default)
+
+
+def get_from_env(key: str, env_key: str, default: str | None = None) -> str:
+ """Get a value from a dictionary or an environment variable.
+
+ Args:
+ key: The key to look up in the dictionary.
+ env_key: The environment variable to look up if the key is not
+ in the dictionary.
+ default: The default value to return if the key is not in the dictionary
+ or the environment.
+
+ Returns:
+ The value of the key.
+
+ Raises:
+ ValueError: If the key is not in the dictionary and no default value is
+ provided or if the environment variable is not set.
+ """
+ if env_value := os.getenv(env_key):
+ return env_value
+ if default is not None:
+ return default
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{env_key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/formatting.py b/python/user_packages/Python313/site-packages/langchain_core/utils/formatting.py
new file mode 100644
index 0000000000000000000000000000000000000000..48905a4cc03dac62fd57456f3f6b91382487a392
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/formatting.py
@@ -0,0 +1,80 @@
+"""Utilities for formatting strings."""
+
+from collections.abc import Mapping, Sequence
+from string import Formatter
+from typing import Any
+
+
+class StrictFormatter(Formatter):
+ """A string formatter that enforces keyword-only argument substitution.
+
+ This formatter extends Python's built-in `string.Formatter` to provide stricter
+ validation for prompt template formatting. It ensures that all variable
+ substitutions use keyword arguments rather than positional arguments, which improves
+ clarity and reduces errors when formatting prompt templates.
+
+ Example:
+ >>> fmt = StrictFormatter()
+ >>> fmt.format("Hello, {name}!", name="World")
+ 'Hello, World!'
+ >>> fmt.format("Hello, {}!", "World") # Raises ValueError
+ """
+
+ def vformat(
+ self, format_string: str, args: Sequence, kwargs: Mapping[str, Any]
+ ) -> str:
+ """Format a string using only keyword arguments.
+
+ Overrides the base `vformat` to reject positional arguments, ensuring all
+ substitutions are explicit and named.
+
+ Args:
+ format_string: A string containing replacement fields (e.g., `'{name}'`).
+ args: Positional arguments (must be empty).
+ kwargs: Keyword arguments for substitution into the format string.
+
+ Returns:
+ The formatted string with all replacement fields substituted.
+
+ Raises:
+ ValueError: If any positional arguments are provided.
+ """
+ if len(args) > 0:
+ msg = (
+ "No arguments should be provided, "
+ "everything should be passed as keyword arguments."
+ )
+ raise ValueError(msg)
+ return super().vformat(format_string, args, kwargs)
+
+ def validate_input_variables(
+ self, format_string: str, input_variables: list[str]
+ ) -> None:
+ """Validate that input variables match the placeholders in a format string.
+
+ Checks that the provided input variables can be used to format the given string
+ without missing or extra keys. This is useful for validating prompt templates
+ before runtime.
+
+ Args:
+ format_string: A string containing replacement fields to validate
+ against (e.g., `'Hello, {name}!'`).
+ input_variables: List of variable names expected to fill the
+ replacement fields.
+
+ Raises:
+ KeyError: If the format string contains placeholders not present
+ in input_variables.
+
+ Example:
+ >>> fmt = StrictFormatter()
+ >>> fmt.validate_input_variables("Hello, {name}!", ["name"]) # OK
+ >>> fmt.validate_input_variables("Hello, {name}!", ["other"]) # Raises
+ """
+ dummy_inputs = dict.fromkeys(input_variables, "foo")
+ super().format(format_string, **dummy_inputs)
+
+
+#: Default StrictFormatter instance for use throughout LangChain.
+#: Used internally for formatting prompt templates with named variables.
+formatter = StrictFormatter()
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/function_calling.py b/python/user_packages/Python313/site-packages/langchain_core/utils/function_calling.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fefd98b0ebd3733491c1e70603116e4ac830ad5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/function_calling.py
@@ -0,0 +1,829 @@
+"""Methods for creating function specs in the style of OpenAI Functions."""
+
+from __future__ import annotations
+
+import collections
+import inspect
+import logging
+import types
+import typing
+import uuid
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+import typing_extensions
+from pydantic import BaseModel
+from pydantic.errors import PydanticInvalidForJsonSchema
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import Field as Field_v1
+from pydantic.v1 import create_model as create_model_v1
+from typing_extensions import TypedDict, is_typeddict
+
+import langchain_core
+from langchain_core._api import beta
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
+from langchain_core.utils.json_schema import dereference_refs
+from langchain_core.utils.pydantic import is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Mapping
+
+ from langchain_core.tools import BaseTool
+
+logger = logging.getLogger(__name__)
+
+PYTHON_TO_JSON_TYPES = {
+ "str": "string",
+ "int": "integer",
+ "float": "number",
+ "bool": "boolean",
+}
+
+_ORIGIN_MAP: dict[type, Any] = {
+ dict: dict,
+ list: list,
+ tuple: tuple,
+ set: set,
+ collections.abc.Iterable: typing.Iterable,
+ collections.abc.Mapping: typing.Mapping,
+ collections.abc.Sequence: typing.Sequence,
+ collections.abc.MutableMapping: typing.MutableMapping,
+}
+# Add UnionType mapping for Python 3.10+
+if hasattr(types, "UnionType"):
+ _ORIGIN_MAP[types.UnionType] = Union
+
+
+class FunctionDescription(TypedDict):
+ """Representation of a callable function to send to an LLM."""
+
+ name: str
+ """The name of the function."""
+
+ description: str
+ """A description of the function."""
+
+ parameters: dict
+ """The parameters of the function."""
+
+
+class ToolDescription(TypedDict):
+ """Representation of a callable function to the OpenAI API."""
+
+ type: Literal["function"]
+ """The type of the tool."""
+
+ function: FunctionDescription
+ """The function description."""
+
+
+def _rm_titles(kv: dict, prev_key: str = "") -> dict:
+ """Recursively removes `'title'` fields from a JSON schema dictionary.
+
+ Remove `'title'` fields from the input JSON schema dictionary,
+ except when a `'title'` appears within a property definition under `'properties'`.
+
+ Args:
+ kv: The input JSON schema as a dictionary.
+ prev_key: The key from the parent dictionary, used to identify context.
+
+ Returns:
+ A new dictionary with appropriate `'title'` fields removed.
+ """
+ new_kv = {}
+
+ for k, v in kv.items():
+ if k == "title":
+ # If the value is a nested dict and part of a property under "properties",
+ # preserve the title but continue recursion
+ if isinstance(v, dict) and prev_key == "properties":
+ new_kv[k] = _rm_titles(v, k)
+ else:
+ # Otherwise, remove this "title" key
+ continue
+ elif isinstance(v, dict):
+ # Recurse into nested dictionaries
+ new_kv[k] = _rm_titles(v, k)
+ else:
+ # Leave non-dict values untouched
+ new_kv[k] = v
+
+ return new_kv
+
+
+def _convert_json_schema_to_openai_function(
+ schema: dict,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ rm_titles: bool = True,
+) -> FunctionDescription:
+ """Converts a Pydantic model to a function description for the OpenAI API.
+
+ Args:
+ schema: The JSON schema to convert.
+ name: The name of the function.
+
+ If not provided, the title of the schema will be used.
+ description: The description of the function.
+
+ If not provided, the description of the schema will be used.
+ rm_titles: Whether to remove titles from the schema.
+
+ Returns:
+ The function description.
+ """
+ schema = dereference_refs(schema)
+ if "definitions" in schema: # pydantic 1
+ schema.pop("definitions", None)
+ if "$defs" in schema: # pydantic 2
+ schema.pop("$defs", None)
+ title = schema.pop("title", "")
+ default_description = schema.pop("description", "")
+ return {
+ "name": name or title,
+ "description": description or default_description,
+ "parameters": _rm_titles(schema) if rm_titles else schema,
+ }
+
+
+def _convert_pydantic_to_openai_function(
+ model: type,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ rm_titles: bool = True,
+) -> FunctionDescription:
+ """Converts a Pydantic model to a function description for the OpenAI API.
+
+ Args:
+ model: The Pydantic model to convert.
+ name: The name of the function.
+
+ If not provided, the title of the schema will be used.
+ description: The description of the function.
+
+ If not provided, the description of the schema will be used.
+ rm_titles: Whether to remove titles from the schema.
+
+ Raises:
+ TypeError: If the model is not a Pydantic model.
+ TypeError: If the model contains types that cannot be converted to JSON schema.
+
+ Returns:
+ The function description.
+ """
+ try:
+ if hasattr(model, "model_json_schema"):
+ schema = model.model_json_schema() # Pydantic 2
+ elif hasattr(model, "schema"):
+ schema = model.schema() # Pydantic 1
+ else:
+ msg = "Model must be a Pydantic model."
+ raise TypeError(msg)
+ except PydanticInvalidForJsonSchema as e:
+ model_name = getattr(model, "__name__", str(model))
+ msg = (
+ f"Failed to generate JSON schema for '{model_name}': {e}\n\n"
+ "Tool argument schemas must be JSON-serializable. If your schema includes "
+ "custom Python classes, consider:\n"
+ " 1. Converting them to Pydantic models with JSON-compatible fields\n"
+ " 2. Using primitive types (str, int, float, bool, list, dict) instead\n"
+ " 3. Passing the data as serialized JSON strings\n\n"
+ )
+ raise PydanticInvalidForJsonSchema(msg) from e
+ return _convert_json_schema_to_openai_function(
+ schema, name=name, description=description, rm_titles=rm_titles
+ )
+
+
+def _get_python_function_name(function: Callable) -> str:
+ """Get the name of a Python function."""
+ return function.__name__
+
+
+def _convert_python_function_to_openai_function(
+ function: Callable,
+) -> FunctionDescription:
+ """Convert a Python function to an OpenAI function-calling API compatible dict.
+
+ Assumes the Python function has type hints and a docstring with a description. If
+ the docstring has Google Python style argument descriptions, these will be included
+ as well.
+
+ Args:
+ function: The Python function to convert.
+
+ Returns:
+ The OpenAI function description.
+ """
+ func_name = _get_python_function_name(function)
+ model = langchain_core.tools.base.create_schema_from_function(
+ func_name,
+ function,
+ filter_args=(),
+ parse_docstring=True,
+ error_on_invalid_docstring=False,
+ include_injected=False,
+ )
+ return _convert_pydantic_to_openai_function(
+ model,
+ name=func_name,
+ description=model.__doc__,
+ )
+
+
+def _convert_typed_dict_to_openai_function(typed_dict: type) -> FunctionDescription:
+ visited: dict = {}
+
+ model = cast(
+ "type[BaseModel]",
+ _convert_any_typed_dicts_to_pydantic(typed_dict, visited=visited),
+ )
+ return _convert_pydantic_to_openai_function(model)
+
+
+_MAX_TYPED_DICT_RECURSION = 25
+
+
+def _convert_any_typed_dicts_to_pydantic(
+ type_: type,
+ *,
+ visited: dict[type, type],
+ depth: int = 0,
+) -> type:
+ if type_ in visited:
+ return visited[type_]
+ if depth >= _MAX_TYPED_DICT_RECURSION:
+ return type_
+ if is_typeddict(type_):
+ typed_dict = type_
+ docstring = inspect.getdoc(typed_dict)
+ # Use get_type_hints to properly resolve forward references and
+ # string annotations in Python 3.14+ (PEP 649 deferred annotations).
+ # include_extras=True preserves Annotated metadata.
+ try:
+ annotations_ = get_type_hints(typed_dict, include_extras=True)
+ except Exception:
+ # Fallback for edge cases where get_type_hints might fail
+ annotations_ = typed_dict.__annotations__
+ description, arg_descriptions = _parse_google_docstring(
+ docstring, list(annotations_)
+ )
+ fields: dict = {}
+ for arg, arg_type in annotations_.items():
+ if get_origin(arg_type) in {Annotated, typing_extensions.Annotated}:
+ annotated_args = get_args(arg_type)
+ new_arg_type = _convert_any_typed_dicts_to_pydantic(
+ annotated_args[0], depth=depth + 1, visited=visited
+ )
+ field_kwargs = dict(
+ zip(("default", "description"), annotated_args[1:], strict=False)
+ )
+ if (field_desc := field_kwargs.get("description")) and not isinstance(
+ field_desc, str
+ ):
+ msg = (
+ f"Invalid annotation for field {arg}. Third argument to "
+ f"Annotated must be a string description, received value of "
+ f"type {type(field_desc)}."
+ )
+ raise ValueError(msg)
+ if arg_desc := arg_descriptions.get(arg):
+ field_kwargs["description"] = arg_desc
+ fields[arg] = (new_arg_type, Field_v1(**field_kwargs))
+ else:
+ new_arg_type = _convert_any_typed_dicts_to_pydantic(
+ arg_type, depth=depth + 1, visited=visited
+ )
+ field_kwargs = {"default": ...}
+ if arg_desc := arg_descriptions.get(arg):
+ field_kwargs["description"] = arg_desc
+ fields[arg] = (new_arg_type, Field_v1(**field_kwargs))
+ model = cast(
+ "type[BaseModelV1]", create_model_v1(typed_dict.__name__, **fields)
+ )
+ model.__doc__ = description
+ visited[typed_dict] = model
+ return model
+ if (origin := get_origin(type_)) and (type_args := get_args(type_)):
+ subscriptable_origin = _py_38_safe_origin(origin)
+ type_args = tuple(
+ _convert_any_typed_dicts_to_pydantic(arg, depth=depth + 1, visited=visited)
+ for arg in type_args
+ )
+ return cast("type", subscriptable_origin[type_args]) # type: ignore[index]
+ return type_
+
+
+def _format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
+ """Format tool into the OpenAI function API.
+
+ Args:
+ tool: The tool to format.
+
+ Raises:
+ ValueError: If the tool call schema is not supported.
+
+ Returns:
+ The function description.
+ """
+ is_simple_oai_tool = (
+ isinstance(tool, langchain_core.tools.simple.Tool) and not tool.args_schema
+ )
+ if tool.tool_call_schema and not is_simple_oai_tool:
+ if isinstance(tool.tool_call_schema, dict):
+ return _convert_json_schema_to_openai_function(
+ tool.tool_call_schema, name=tool.name, description=tool.description
+ )
+ if issubclass(tool.tool_call_schema, (BaseModel, BaseModelV1)):
+ return _convert_pydantic_to_openai_function(
+ tool.tool_call_schema, name=tool.name, description=tool.description
+ )
+ error_msg = (
+ f"Unsupported tool call schema: {tool.tool_call_schema}. "
+ "Tool call schema must be a JSON schema dict or a Pydantic model."
+ )
+ raise ValueError(error_msg)
+ return {
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": {
+ # This is a hack to get around the fact that some tools
+ # do not expose an args_schema, and expect an argument
+ # which is a string.
+ # And Open AI does not support an array type for the
+ # parameters.
+ "properties": {
+ "__arg1": {"title": "__arg1", "type": "string"},
+ },
+ "required": ["__arg1"],
+ "type": "object",
+ },
+ }
+
+
+def convert_to_openai_function(
+ function: Mapping[str, Any] | type | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a raw function/class to an OpenAI function.
+
+ Args:
+ function: A dictionary, Pydantic `BaseModel` class, `TypedDict` class, a
+ LangChain `Tool` object, or a Python function.
+
+ If a dictionary is passed in, it is assumed to already be a valid OpenAI
+ function, a JSON schema with top-level `title` key specified, an Anthropic
+ format tool, or an Amazon Bedrock Converse format tool.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in function definition.
+
+ Returns:
+ A dict version of the passed in function which is compatible with the OpenAI
+ function-calling API.
+
+ Raises:
+ ValueError: If function is not in a supported format.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.16"
+
+ `description` and `parameters` keys are now optional. Only `name` is
+ required and guaranteed to be part of the output.
+ """
+ # an Anthropic format tool
+ if isinstance(function, dict) and all(
+ k in function for k in ("name", "input_schema")
+ ):
+ oai_function = {
+ "name": function["name"],
+ "parameters": function["input_schema"],
+ }
+ if "description" in function:
+ oai_function["description"] = function["description"]
+ # an Amazon Bedrock Converse format tool
+ elif isinstance(function, dict) and "toolSpec" in function:
+ oai_function = {
+ "name": function["toolSpec"]["name"],
+ "parameters": function["toolSpec"]["inputSchema"]["json"],
+ }
+ if "description" in function["toolSpec"]:
+ oai_function["description"] = function["toolSpec"]["description"]
+ # already in OpenAI function format
+ elif isinstance(function, dict) and "name" in function:
+ oai_function = {
+ k: v
+ for k, v in function.items()
+ if k in {"name", "description", "parameters", "strict"}
+ }
+ # a JSON schema with title and description
+ elif isinstance(function, dict) and "title" in function:
+ function_copy = function.copy()
+ oai_function = {"name": function_copy.pop("title")}
+ if "description" in function_copy:
+ oai_function["description"] = function_copy.pop("description")
+ if function_copy and "properties" in function_copy:
+ oai_function["parameters"] = function_copy
+ elif isinstance(function, type) and is_basemodel_subclass(function):
+ oai_function = cast("dict", _convert_pydantic_to_openai_function(function))
+ elif is_typeddict(function):
+ oai_function = cast(
+ "dict", _convert_typed_dict_to_openai_function(cast("type", function))
+ )
+ elif isinstance(function, langchain_core.tools.base.BaseTool):
+ oai_function = cast("dict", _format_tool_to_openai_function(function))
+ elif callable(function):
+ oai_function = cast(
+ "dict", _convert_python_function_to_openai_function(function)
+ )
+ else:
+ if isinstance(function, dict) and (
+ "type" in function or "properties" in function
+ ):
+ msg = (
+ f"Unsupported function\n\n{function}\n\nTo use a JSON schema as a "
+ "function, it must have a top-level 'title' key to be used as the "
+ "function name."
+ )
+ raise ValueError(msg)
+ msg = (
+ f"Unsupported function\n\n{function}\n\nFunctions must be passed in"
+ " as Dict, pydantic.BaseModel, or Callable. If they're a dict they must"
+ " either be in OpenAI function format or valid JSON schema with top-level"
+ " 'title' key."
+ )
+ raise ValueError(msg)
+
+ if strict is not None:
+ if "strict" in oai_function and oai_function["strict"] != strict:
+ msg = (
+ f"Tool/function already has a 'strict' key with value "
+ f"{oai_function['strict']} which is different from the explicit "
+ f"`strict` arg received {strict=}."
+ )
+ raise ValueError(msg)
+ oai_function["strict"] = strict
+ if strict:
+ # All fields must be `required`
+ parameters = oai_function.get("parameters")
+ if isinstance(parameters, dict):
+ fields = parameters.get("properties")
+ if isinstance(fields, dict) and fields:
+ parameters = dict(parameters)
+ parameters["required"] = list(fields.keys())
+ oai_function["parameters"] = parameters
+
+ # As of 08/06/24, OpenAI requires that additionalProperties be supplied and
+ # set to False if strict is True.
+ # All properties layer needs 'additionalProperties=False'
+ oai_function["parameters"] = _recursive_set_additional_properties_false(
+ oai_function["parameters"]
+ )
+ return oai_function
+
+
+# List of well known tools supported by OpenAI's chat models or responses API.
+# These tools are not expected to be supported by other chat model providers
+# that conform to the OpenAI function-calling API.
+_WellKnownOpenAITools = (
+ "function",
+ "file_search",
+ "computer",
+ "computer_use_preview",
+ "code_interpreter",
+ "mcp",
+ "image_generation",
+ "web_search_preview",
+ "web_search",
+ "tool_search",
+ "namespace",
+)
+
+
+def convert_to_openai_tool(
+ tool: Mapping[str, Any] | type[BaseModel] | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a tool-like object to an OpenAI tool schema.
+
+ [OpenAI tool schema reference](https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools)
+
+ Args:
+ tool: Either a dictionary, a `pydantic.BaseModel` class, Python function, or
+ `BaseTool`.
+
+ If a dictionary is passed in, it is assumed to already be a valid OpenAI
+ function, a JSON schema with top-level `title` key specified, an Anthropic
+ format tool, or an Amazon Bedrock Converse format tool.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in tool definition.
+
+ Returns:
+ A dict version of the passed in tool which is compatible with the OpenAI
+ tool-calling API.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.16"
+
+ `description` and `parameters` keys are now optional. Only `name` is
+ required and guaranteed to be part of the output.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.44"
+
+ Return OpenAI Responses API-style tools unchanged. This includes
+ any dict with `"type"` in `"file_search"`, `"function"`,
+ `"computer_use_preview"`, `"web_search_preview"`.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.63"
+
+ Added support for OpenAI's image generation built-in tool.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.tools import Tool # noqa: PLC0415
+
+ if isinstance(tool, dict):
+ if tool.get("type") in _WellKnownOpenAITools:
+ return tool
+ # As of 03.12.25 can be "web_search_preview" or "web_search_preview_2025_03_11"
+ if (tool.get("type") or "").startswith("web_search_preview"):
+ return tool
+ if isinstance(tool, Tool) and (tool.metadata or {}).get("type") == "custom_tool":
+ oai_tool = {
+ "type": "custom",
+ "name": tool.name,
+ "description": tool.description,
+ }
+ if tool.metadata is not None and "format" in tool.metadata:
+ oai_tool["format"] = tool.metadata["format"]
+ return oai_tool
+ oai_function = convert_to_openai_function(tool, strict=strict)
+ return {"type": "function", "function": oai_function}
+
+
+def convert_to_json_schema(
+ schema: dict[str, Any] | type[BaseModel] | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a schema representation to a JSON schema.
+
+ Args:
+ schema: The schema to convert.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in function definition.
+
+ Raises:
+ ValueError: If the input is not a valid OpenAI-format tool.
+
+ Returns:
+ A JSON schema representation of the input schema.
+ """
+ openai_tool = convert_to_openai_tool(schema, strict=strict)
+ if (
+ not isinstance(openai_tool, dict)
+ or "function" not in openai_tool
+ or "name" not in openai_tool["function"]
+ ):
+ error_message = "Input must be a valid OpenAI-format tool."
+ raise ValueError(error_message)
+
+ openai_function = openai_tool["function"]
+ json_schema = {}
+ json_schema["title"] = openai_function["name"]
+
+ if "description" in openai_function:
+ json_schema["description"] = openai_function["description"]
+
+ if "parameters" in openai_function:
+ parameters = openai_function["parameters"].copy()
+ json_schema.update(parameters)
+
+ return json_schema
+
+
+@beta()
+def tool_example_to_messages(
+ input: str,
+ tool_calls: list[BaseModel],
+ tool_outputs: list[str] | None = None,
+ *,
+ ai_response: str | None = None,
+) -> list[BaseMessage]:
+ """Convert an example into a list of messages that can be fed into an LLM.
+
+ This code is an adapter that converts a single example to a list of messages
+ that can be fed into a chat model.
+
+ The list of messages per example by default corresponds to:
+
+ 1. `HumanMessage`: contains the content from which content should be extracted.
+ 2. `AIMessage`: contains the extracted information from the model
+ 3. `ToolMessage`: contains confirmation to the model that the model requested a
+ tool correctly.
+
+ If `ai_response` is specified, there will be a final `AIMessage` with that
+ response.
+
+ The `ToolMessage` is required because some chat models are hyper-optimized for
+ agents rather than for an extraction use case.
+
+ Args:
+ input: The user input
+ tool_calls: Tool calls represented as Pydantic BaseModels
+ tool_outputs: Tool call outputs.
+
+ Does not need to be provided.
+
+ If not provided, a placeholder value will be inserted.
+ ai_response: If provided, content for a final `AIMessage`.
+
+ Returns:
+ A list of messages
+
+ Examples:
+ ```python
+ from typing import Optional
+ from pydantic import BaseModel, Field
+ from langchain_openai import ChatOpenAI
+
+
+ class Person(BaseModel):
+ '''Information about a person.'''
+
+ name: str | None = Field(..., description="The name of the person")
+ hair_color: str | None = Field(
+ ..., description="The color of the person's hair if known"
+ )
+ height_in_meters: str | None = Field(..., description="Height in METERS")
+
+
+ examples = [
+ (
+ "The ocean is vast and blue. It's more than 20,000 feet deep.",
+ Person(name=None, height_in_meters=None, hair_color=None),
+ ),
+ (
+ "Fiona traveled far from France to Spain.",
+ Person(name="Fiona", height_in_meters=None, hair_color=None),
+ ),
+ ]
+
+
+ messages = []
+
+ for txt, tool_call in examples:
+ messages.extend(tool_example_to_messages(txt, [tool_call]))
+ ```
+ """
+ messages: list[BaseMessage] = [HumanMessage(content=input)]
+
+ openai_tool_calls = [
+ {
+ "id": str(uuid.uuid4()),
+ "type": "function",
+ "function": {
+ # The name of the function right now corresponds to the name
+ # of the Pydantic model. This is implicit in the API right now,
+ # and will be improved over time.
+ "name": tool_call.__class__.__name__,
+ "arguments": tool_call.model_dump_json(),
+ },
+ }
+ for tool_call in tool_calls
+ ]
+
+ messages.append(
+ AIMessage(content="", additional_kwargs={"tool_calls": openai_tool_calls})
+ )
+ tool_outputs = tool_outputs or ["You have correctly called this tool."] * len(
+ openai_tool_calls
+ )
+ for output, tool_call_dict in zip(tool_outputs, openai_tool_calls, strict=False):
+ messages.append(ToolMessage(content=output, tool_call_id=tool_call_dict["id"]))
+
+ if ai_response:
+ messages.append(AIMessage(content=ai_response))
+ return messages
+
+
+_MIN_DOCSTRING_BLOCKS = 2
+
+
+def _parse_google_docstring(
+ docstring: str | None,
+ args: list[str],
+ *,
+ error_on_invalid_docstring: bool = False,
+) -> tuple[str, dict]:
+ """Parse the function and argument descriptions from the docstring of a function.
+
+ Assumes the function docstring follows Google Python style guide.
+
+ Args:
+ docstring: The docstring to parse.
+ args: The list of argument names to extract descriptions for.
+ error_on_invalid_docstring: Whether to raise an error if the docstring is
+ invalid.
+
+ Returns:
+ A tuple of the function description and a dictionary of argument descriptions.
+ """
+ if docstring:
+ docstring_blocks = docstring.split("\n\n")
+ if error_on_invalid_docstring:
+ filtered_annotations = {
+ arg
+ for arg in args
+ if arg not in {"run_manager", "callbacks", "runtime", "return"}
+ }
+ if filtered_annotations and (
+ len(docstring_blocks) < _MIN_DOCSTRING_BLOCKS
+ or not any(block.startswith("Args:") for block in docstring_blocks[1:])
+ ):
+ msg = "Found invalid Google-Style docstring."
+ raise ValueError(msg)
+ descriptors = []
+ args_block = None
+ past_descriptors = False
+ for block in docstring_blocks:
+ if block.startswith("Args:"):
+ args_block = block
+ break
+ if block.startswith(("Returns:", "Example:")):
+ # Don't break in case Args come after
+ past_descriptors = True
+ elif not past_descriptors:
+ descriptors.append(block)
+ else:
+ continue
+ description = " ".join(descriptors).strip()
+ else:
+ if error_on_invalid_docstring:
+ msg = "Found invalid Google-Style docstring."
+ raise ValueError(msg)
+ description = ""
+ args_block = None
+ arg_descriptions = {}
+ if args_block:
+ arg = None
+ for line in args_block.split("\n")[1:]:
+ if ":" in line:
+ arg, desc = line.split(":", maxsplit=1)
+ arg = arg.strip()
+ arg_name, _, annotations_ = arg.partition(" ")
+ if annotations_.startswith("(") and annotations_.endswith(")"):
+ arg = arg_name
+ arg_descriptions[arg] = desc.strip()
+ elif arg:
+ arg_descriptions[arg] += " " + line.strip()
+ return description, arg_descriptions
+
+
+def _py_38_safe_origin(origin: type) -> type:
+ return cast("type", _ORIGIN_MAP.get(origin, origin))
+
+
+def _recursive_set_additional_properties_false(
+ schema: dict[str, Any],
+) -> dict[str, Any]:
+ if isinstance(schema, dict):
+ # Check if 'required' is a key at the current level or if the schema is empty,
+ # in which case additionalProperties still needs to be specified.
+ if (
+ "required" in schema
+ or ("properties" in schema and not schema["properties"])
+ # Since Pydantic 2.11, it will always add `additionalProperties: True`
+ # for arbitrary dictionary schemas
+ # See: https://pydantic.dev/articles/pydantic-v2-11-release#changes
+ # If it is already set to True, we need override it to False
+ or "additionalProperties" in schema
+ ):
+ schema["additionalProperties"] = False
+
+ # Recursively check 'properties' and 'items' if they exist
+ if "anyOf" in schema:
+ for sub_schema in schema["anyOf"]:
+ _recursive_set_additional_properties_false(sub_schema)
+ if "properties" in schema:
+ for sub_schema in schema["properties"].values():
+ _recursive_set_additional_properties_false(sub_schema)
+ if "items" in schema:
+ _recursive_set_additional_properties_false(schema["items"])
+
+ return schema
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/html.py b/python/user_packages/Python313/site-packages/langchain_core/utils/html.py
new file mode 100644
index 0000000000000000000000000000000000000000..4798b02ce78388c371fca0c59e5b30154e140397
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/html.py
@@ -0,0 +1,132 @@
+"""Utilities for working with HTML."""
+
+import logging
+import re
+from collections.abc import Sequence
+from urllib.parse import urljoin, urlparse
+
+logger = logging.getLogger(__name__)
+
+PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#")
+
+SUFFIXES_TO_IGNORE = (
+ ".css",
+ ".js",
+ ".ico",
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".svg",
+ ".csv",
+ ".bz2",
+ ".zip",
+ ".epub",
+ ".webp",
+ ".pdf",
+ ".docx",
+ ".xlsx",
+ ".pptx",
+ ".pptm",
+)
+
+SUFFIXES_TO_IGNORE_REGEX = (
+ "(?!" + "|".join([re.escape(s) + r"[\#'\"]" for s in SUFFIXES_TO_IGNORE]) + ")"
+)
+
+PREFIXES_TO_IGNORE_REGEX = (
+ "(?!" + "|".join([re.escape(s) for s in PREFIXES_TO_IGNORE]) + ")"
+)
+
+DEFAULT_LINK_REGEX = (
+ rf"href=[\"']{PREFIXES_TO_IGNORE_REGEX}((?:{SUFFIXES_TO_IGNORE_REGEX}.)*?)[\#'\"]"
+)
+
+
+def find_all_links(
+ raw_html: str, *, pattern: str | re.Pattern | None = None
+) -> list[str]:
+ """Extract all links from a raw HTML string.
+
+ Args:
+ raw_html: original HTML.
+ pattern: Regex to use for extracting links from raw HTML.
+
+ Returns:
+ A list of all links found in the HTML.
+ """
+ pattern = pattern or DEFAULT_LINK_REGEX
+ return list(set(re.findall(pattern, raw_html)))
+
+
+def extract_sub_links(
+ raw_html: str,
+ url: str,
+ *,
+ base_url: str | None = None,
+ pattern: str | re.Pattern | None = None,
+ prevent_outside: bool = True,
+ exclude_prefixes: Sequence[str] = (),
+ continue_on_failure: bool = False,
+) -> list[str]:
+ """Extract all links from a raw HTML string and convert into absolute paths.
+
+ Args:
+ raw_html: Original HTML.
+ url: The url of the HTML.
+ base_url: the base URL to check for outside links against.
+ pattern: Regex to use for extracting links from raw HTML.
+ prevent_outside: If `True`, ignore external links which are not children
+ of the base URL.
+ exclude_prefixes: Exclude any URLs that start with one of these prefixes.
+ continue_on_failure: If `True`, continue if parsing a specific link raises an
+ exception. Otherwise, raise the exception.
+
+ Returns:
+ A list of absolute paths to sub links.
+ """
+ base_url_to_use = base_url if base_url is not None else url
+ parsed_base_url = urlparse(base_url_to_use)
+ parsed_url = urlparse(url)
+ all_links = find_all_links(raw_html, pattern=pattern)
+ absolute_paths = set()
+ for link in all_links:
+ try:
+ parsed_link = urlparse(link)
+ # Some may be absolute links like https://to/path
+ if parsed_link.scheme in {"http", "https"}:
+ absolute_path = link
+ # Some may have omitted the protocol like //to/path
+ elif link.startswith("//"):
+ absolute_path = f"{parsed_url.scheme}:{link}"
+ else:
+ absolute_path = urljoin(url, parsed_link.path)
+ if parsed_link.query:
+ absolute_path += f"?{parsed_link.query}"
+ absolute_paths.add(absolute_path)
+ except Exception as e:
+ if continue_on_failure:
+ logger.warning(
+ "Unable to load link %s. Raised exception:\n\n%s", link, e
+ )
+ continue
+ raise
+
+ results = []
+ for path in absolute_paths:
+ if any(path.startswith(exclude_prefix) for exclude_prefix in exclude_prefixes):
+ continue
+
+ if prevent_outside:
+ parsed_path = urlparse(path)
+
+ if parsed_base_url.netloc != parsed_path.netloc:
+ continue
+
+ # Will take care of verifying rest of path after netloc
+ # if it's more specific
+ if not path.startswith(base_url_to_use):
+ continue
+
+ results.append(path)
+ return results
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/image.py b/python/user_packages/Python313/site-packages/langchain_core/utils/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f2cce4ee1f4ea152f7e282ef674f3690d476555
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/image.py
@@ -0,0 +1,15 @@
+"""Utilities for image processing."""
+
+from typing import Any
+
+
+def __getattr__(name: str) -> Any:
+ if name in {"encode_image", "image_to_data_url"}:
+ msg = (
+ f"'{name}' has been removed for security reasons.\n\n"
+ f"Usage of this utility in environments with user-input paths is a "
+ f"security vulnerability. Out of an abundance of caution, the utility "
+ f"has been removed to prevent possible misuse."
+ )
+ raise ValueError(msg)
+ raise AttributeError(name)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/input.py b/python/user_packages/Python313/site-packages/langchain_core/utils/input.py
new file mode 100644
index 0000000000000000000000000000000000000000..d97d4006d33b18db65ad42a07c9722590898cb3e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/input.py
@@ -0,0 +1,82 @@
+"""Handle chained inputs."""
+
+from typing import TextIO
+
+_TEXT_COLOR_MAPPING = {
+ "blue": "36;1",
+ "yellow": "33;1",
+ "pink": "38;5;200",
+ "green": "32;1",
+ "red": "31;1",
+}
+
+
+def get_color_mapping(
+ items: list[str], excluded_colors: list | None = None
+) -> dict[str, str]:
+ """Get mapping for items to a support color.
+
+ Args:
+ items: The items to map to colors.
+ excluded_colors: The colors to exclude.
+
+ Returns:
+ The mapping of items to colors.
+
+ Raises:
+ ValueError: If no colors are available after applying exclusions.
+ """
+ colors = list(_TEXT_COLOR_MAPPING.keys())
+ if excluded_colors is not None:
+ colors = [c for c in colors if c not in excluded_colors]
+ if not colors:
+ msg = "No colors available after applying exclusions."
+ raise ValueError(msg)
+ return {item: colors[i % len(colors)] for i, item in enumerate(items)}
+
+
+def get_colored_text(text: str, color: str) -> str:
+ """Get colored text.
+
+ Args:
+ text: The text to color.
+ color: The color to use.
+
+ Returns:
+ The colored text.
+ """
+ color_str = _TEXT_COLOR_MAPPING[color]
+ return f"\u001b[{color_str}m\033[1;3m{text}\u001b[0m"
+
+
+def get_bolded_text(text: str) -> str:
+ """Get bolded text.
+
+ Args:
+ text: The text to bold.
+
+ Returns:
+ The bolded text.
+ """
+ return f"\033[1m{text}\033[0m"
+
+
+def print_text(
+ text: str, color: str | None = None, end: str = "", file: TextIO | None = None
+) -> None:
+ """Print text with highlighting and no end characters.
+
+ If a color is provided, the text will be printed in that color.
+
+ If a file is provided, the text will be written to that file.
+
+ Args:
+ text: The text to print.
+ color: The color to use.
+ end: The end character to use.
+ file: The file to write to.
+ """
+ text_to_print = get_colored_text(text, color) if color else text
+ print(text_to_print, end=end, file=file)
+ if file:
+ file.flush() # ensure all printed content are written to file
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/interactive_env.py b/python/user_packages/Python313/site-packages/langchain_core/utils/interactive_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0e7ea8b202af472e81b97ff8e44355ee21c5f96
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/interactive_env.py
@@ -0,0 +1,12 @@
+"""Utilities for working with interactive environments."""
+
+import sys
+
+
+def is_interactive_env() -> bool:
+ """Determine if running within IPython or Jupyter.
+
+ Returns:
+ `True` if running in an interactive environment, `False` otherwise.
+ """
+ return hasattr(sys, "ps2")
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/iter.py b/python/user_packages/Python313/site-packages/langchain_core/utils/iter.py
new file mode 100644
index 0000000000000000000000000000000000000000..b24c5f213ad62160bdd9ec04c878c68331b12e2e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/iter.py
@@ -0,0 +1,223 @@
+"""Utilities for working with iterators."""
+
+from collections import deque
+from collections.abc import Generator, Iterable, Iterator
+from contextlib import AbstractContextManager
+from itertools import islice
+from types import TracebackType
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ TypeVar,
+ overload,
+)
+
+T = TypeVar("T")
+
+
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection."""
+
+ def __enter__(self) -> None:
+ """Do nothing."""
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> Literal[False]:
+ """Return False (exception not suppressed)."""
+ return False
+
+
+def tee_peer(
+ iterator: Iterator[T],
+ # the buffer specific to this peer
+ buffer: deque[T],
+ # the buffers of all peers, including our own
+ peers: list[deque[T]],
+ lock: AbstractContextManager[Any],
+) -> Generator[T, None, None]:
+ """An individual iterator of a `.tee`.
+
+ This function is a generator that yields items from the shared iterator `iterator`.
+ It buffers items until the least advanced iterator has yielded them as well. The
+ buffer is shared with all other peers.
+
+ Args:
+ iterator: The shared iterator.
+ buffer: The buffer for this peer.
+ peers: The buffers of all peers.
+ lock: The lock to synchronise access to the shared buffers.
+
+ Yields:
+ The next item from the shared iterator.
+ """
+ try:
+ while True:
+ if not buffer:
+ with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = next(iterator)
+ except StopIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
+ yield buffer.popleft()
+ finally:
+ with lock:
+ # this peer is done - remove its buffer
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
+ if peer_buffer is buffer:
+ peers.pop(idx)
+ break
+ # if we are the last peer, try and close the iterator
+ if not peers and hasattr(iterator, "close"):
+ iterator.close()
+
+
+class Tee(Generic[T]):
+ """Create `n` separate asynchronous iterators over `iterable`.
+
+ This splits a single `iterable` into multiple iterators, each providing the same
+ items in the same order.
+
+ All child iterators may advance separately but share the same items from `iterable`
+ -- when the most advanced iterator retrieves an item, it is buffered until the least
+ advanced iterator has yielded it as well. A `tee` works lazily and can handle an
+ infinite `iterable`, provided that all iterators advance.
+
+ ```python
+ async def derivative(sensor_data):
+ previous, current = a.tee(sensor_data, n=2)
+ await a.anext(previous) # advance one iterator
+ return a.map(operator.sub, previous, current)
+ ```
+
+ Unlike `itertools.tee`, `.tee` returns a custom type instead of a `tuple`. Like a
+ tuple, it can be indexed, iterated and unpacked to get the child iterators. In
+ addition, its `.tee.aclose` method immediately closes all children, and it can be
+ used in an `async with` context for the same effect.
+
+ If `iterable` is an iterator and read elsewhere, `tee` will *not* provide these
+ items. Also, `tee` must internally buffer each item until the last iterator has
+ yielded it; if the most and least advanced iterator differ by most data, using a
+ `list` is more efficient (but not lazy).
+
+ If the underlying iterable is concurrency safe (`anext` may be awaited concurrently)
+ the resulting iterators are concurrency safe as well. Otherwise, the iterators are
+ safe if there is only ever one single "most advanced" iterator. To enforce
+ sequential use of `anext`, provide a `lock`
+
+ - e.g., an `asyncio.Lock` instance in an `asyncio` application - and access is
+ automatically synchronised.
+
+ """
+
+ def __init__(
+ self,
+ iterable: Iterator[T],
+ n: int = 2,
+ *,
+ lock: AbstractContextManager[Any] | None = None,
+ ):
+ """Create a `tee`.
+
+ Args:
+ iterable: The iterable to split.
+ n: The number of iterators to create.
+ lock: The lock to synchronise access to the shared buffers.
+
+ """
+ self._iterator = iter(iterable)
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
+ self._children = tuple(
+ tee_peer(
+ iterator=self._iterator,
+ buffer=buffer,
+ peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
+ )
+ for buffer in self._buffers
+ )
+
+ def __len__(self) -> int:
+ """Return the number of child iterators."""
+ return len(self._children)
+
+ @overload
+ def __getitem__(self, item: int) -> Iterator[T]: ...
+
+ @overload
+ def __getitem__(self, item: slice) -> tuple[Iterator[T], ...]: ...
+
+ def __getitem__(self, item: int | slice) -> Iterator[T] | tuple[Iterator[T], ...]:
+ """Return the child iterator(s) at the given index or slice."""
+ return self._children[item]
+
+ def __iter__(self) -> Iterator[Iterator[T]]:
+ """Return an iterator over the child iterators.
+
+ Yields:
+ The child iterators.
+ """
+ yield from self._children
+
+ def __enter__(self) -> "Tee[T]":
+ """Return `Tee` instance."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> Literal[False]:
+ """Close all child iterators.
+
+ Returns:
+ `False` (exception not suppressed).
+ """
+ self.close()
+ return False
+
+ def close(self) -> None:
+ """Close all child iterators."""
+ for child in self._children:
+ child.close()
+
+
+# Why this is needed https://stackoverflow.com/a/44638570
+safetee = Tee
+
+
+def batch_iterate(size: int | None, iterable: Iterable[T]) -> Iterator[list[T]]:
+ """Utility batching function.
+
+ Args:
+ size: The size of the batch.
+
+ If `None`, returns a single batch.
+ iterable: The iterable to batch.
+
+ Yields:
+ The batches of the iterable.
+ """
+ it = iter(iterable)
+ while True:
+ chunk = list(islice(it, size))
+ if not chunk:
+ return
+ yield chunk
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/json.py b/python/user_packages/Python313/site-packages/langchain_core/utils/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..a836ffc4e61ef8e6723fcb9147a2305d0d7a5c63
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/json.py
@@ -0,0 +1,228 @@
+"""Utilities for JSON."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.exceptions import OutputParserException
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+
+def _replace_new_line(match: re.Match[str]) -> str:
+ """Replace newline characters in a regex match with escaped sequences.
+
+ Args:
+ match: Regex match object containing the string to process.
+
+ Returns:
+ String with newlines, carriage returns, tabs, and quotes properly escaped.
+ """
+ value = match.group(2)
+ value = re.sub(r"\n", r"\\n", value)
+ value = re.sub(r"\r", r"\\r", value)
+ value = re.sub(r"\t", r"\\t", value)
+ value = re.sub(r'(? str:
+ r"""Custom parser for multiline strings.
+
+ The LLM response for `action_input` may be a multiline string containing unescaped
+ newlines, tabs or quotes. This function replaces those characters with their escaped
+ counterparts. (newlines in JSON must be double-escaped: `\\n`).
+
+ Returns:
+ The modified string with escaped newlines, tabs and quotes.
+ """
+ if isinstance(multiline_string, (bytes, bytearray)):
+ multiline_string = multiline_string.decode()
+
+ return re.sub(
+ r'("action_input"\:\s*")(.*?)(")',
+ _replace_new_line,
+ multiline_string,
+ flags=re.DOTALL,
+ )
+
+
+# Adapted from https://github.com/KillianLucas/open-interpreter/blob/5b6080fae1f8c68938a1e4fa8667e3744084ee21/interpreter/utils/parse_partial_json.py
+# MIT License
+
+
+def parse_partial_json(s: str, *, strict: bool = False) -> Any:
+ """Parse a JSON string that may be missing closing braces.
+
+ Args:
+ s: The JSON string to parse.
+ strict: Whether to use strict parsing.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+ """
+ # Attempt to parse the string as-is.
+ try:
+ return json.loads(s, strict=strict)
+ except json.JSONDecodeError:
+ pass
+
+ # Initialize variables.
+ new_chars = []
+ stack = []
+ is_inside_string = False
+ escaped = False
+
+ # Process each character in the string one at a time.
+ for char in s:
+ new_char = char
+ if is_inside_string:
+ if char == '"' and not escaped:
+ is_inside_string = False
+ elif char == "\n" and not escaped:
+ new_char = (
+ "\\n" # Replace the newline character with the escape sequence.
+ )
+ elif char == "\\":
+ escaped = not escaped
+ else:
+ escaped = False
+ elif char == '"':
+ is_inside_string = True
+ escaped = False
+ elif char == "{":
+ stack.append("}")
+ elif char == "[":
+ stack.append("]")
+ elif char in {"}", "]"}:
+ if stack and stack[-1] == char:
+ stack.pop()
+ else:
+ # Mismatched closing character; the input is malformed.
+ return None
+
+ # Append the processed character to the new string.
+ new_chars.append(new_char)
+
+ # If we're still inside a string at the end of processing,
+ # we need to close the string.
+ if is_inside_string:
+ if escaped: # Remove unterminated escape character
+ new_chars.pop()
+ new_chars.append('"')
+
+ # Reverse the stack to get the closing characters.
+ stack.reverse()
+
+ # Try to parse mods of string until we succeed or run out of characters.
+ while new_chars:
+ # Close any remaining open structures in the reverse
+ # order that they were opened.
+ # Attempt to parse the modified string as JSON.
+ try:
+ return json.loads("".join(new_chars + stack), strict=strict)
+ except json.JSONDecodeError:
+ # If we still can't parse the string as JSON,
+ # try removing the last character
+ new_chars.pop()
+
+ # If we got here, we ran out of characters to remove
+ # and still couldn't parse the string as JSON, so return the parse error
+ # for the original string.
+ return json.loads(s, strict=strict)
+
+
+_json_markdown_re = re.compile(r"```(json)?(.*)", re.DOTALL)
+
+
+def parse_json_markdown(
+ json_string: str, *, parser: Callable[[str], Any] = parse_partial_json
+) -> Any:
+ """Parse a JSON string from a Markdown string.
+
+ Args:
+ json_string: The Markdown string.
+ parser: The parser to use.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+ """
+ try:
+ return _parse_json(json_string, parser=parser)
+ except json.JSONDecodeError:
+ # Try to find JSON string within triple backticks
+ match = _json_markdown_re.search(json_string)
+
+ # If no match found, assume the entire string is a JSON string
+ # Else, use the content within the backticks
+ json_str = json_string if match is None else match.group(2)
+ return _parse_json(json_str, parser=parser)
+
+
+_json_strip_chars = " \n\r\t`"
+
+
+def _parse_json(
+ json_str: str, *, parser: Callable[[str], Any] = parse_partial_json
+) -> Any:
+ """Parse a JSON string, handling special characters and whitespace.
+
+ Strips whitespace, newlines, and backticks from the start and end of the string,
+ then processes special characters before parsing.
+
+ Args:
+ json_str: The JSON string to parse.
+ parser: Optional custom parser function.
+
+ Returns:
+ Parsed JSON object.
+ """
+ # Strip whitespace,newlines,backtick from the start and end
+ json_str = json_str.strip(_json_strip_chars)
+
+ # handle newlines and other special characters inside the returned value
+ json_str = _custom_parser(json_str)
+
+ # Parse the JSON string into a Python dictionary
+ return parser(json_str)
+
+
+def parse_and_check_json_markdown(text: str, expected_keys: list[str]) -> dict:
+ """Parse and check a JSON string from a Markdown string.
+
+ Checks that it contains the expected keys.
+
+ Args:
+ text: The Markdown string.
+ expected_keys: The expected keys in the JSON string.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+
+ Raises:
+ OutputParserException: If the JSON string is invalid or does not contain
+ the expected keys.
+ """
+ try:
+ json_obj = parse_json_markdown(text)
+ except json.JSONDecodeError as e:
+ msg = f"Got invalid JSON object. Error: {e}"
+ raise OutputParserException(msg) from e
+ if not isinstance(json_obj, dict):
+ error_message = (
+ f"Expected JSON object (dict), but got: {type(json_obj).__name__}. "
+ )
+ raise OutputParserException(error_message, llm_output=text)
+
+ for key in expected_keys:
+ if key not in json_obj:
+ msg = (
+ f"Got invalid return object. Expected key `{key}` "
+ f"to be present, but got {json_obj}"
+ )
+ raise OutputParserException(msg)
+ return json_obj
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/json_schema.py b/python/user_packages/Python313/site-packages/langchain_core/utils/json_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1ff1de5fcb19c8552ea6b3d9b64968c59541abb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/json_schema.py
@@ -0,0 +1,273 @@
+"""Utilities for JSON Schema."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, cast
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+def _retrieve_ref(path: str, schema: dict) -> list | dict:
+ """Retrieve a referenced object from a JSON schema using a path.
+
+ Resolves JSON schema references (e.g., `'#/definitions/MyType'`) by traversing the
+ schema structure.
+
+ Args:
+ path: Reference path starting with `'#'` (e.g., `'#/definitions/MyType'`).
+ schema: The JSON schema dictionary to search in.
+
+ Returns:
+ A deep copy of the referenced object (dict or list).
+
+ Raises:
+ ValueError: If the path does not start with `'#'`.
+ KeyError: If the reference path is not found in the schema.
+ """
+ components = path.split("/")
+ if components[0] != "#":
+ msg = (
+ "ref paths are expected to be URI fragments, meaning they should start "
+ "with #."
+ )
+ raise ValueError(msg)
+ out: list | dict = schema
+ for component in components[1:]:
+ if component in out:
+ if isinstance(out, list):
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ out = out[component]
+ elif component.isdigit():
+ index = int(component)
+ if (isinstance(out, list) and 0 <= index < len(out)) or (
+ isinstance(out, dict) and index in out
+ ):
+ out = out[index]
+ else:
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ else:
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ return deepcopy(out)
+
+
+def _process_dict_properties(
+ properties: dict[str, Any],
+ full_schema: dict[str, Any],
+ processed_refs: set[str],
+ skip_keys: Sequence[str],
+ *,
+ shallow_refs: bool,
+) -> dict[str, Any]:
+ """Process dictionary properties, recursing into nested structures."""
+ result: dict[str, Any] = {}
+ for key, value in properties.items():
+ if key in skip_keys:
+ # Skip recursion for specified keys, just copy the value as-is
+ result[key] = deepcopy(value)
+ elif isinstance(value, (dict, list)):
+ # Recursively process nested objects and arrays
+ result[key] = _dereference_refs_helper(
+ value, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+ else:
+ # Copy primitive values directly
+ result[key] = value
+ return result
+
+
+def _dereference_refs_helper(
+ obj: Any,
+ full_schema: dict[str, Any],
+ processed_refs: set[str] | None,
+ skip_keys: Sequence[str],
+ *,
+ shallow_refs: bool,
+) -> Any:
+ """Dereference JSON Schema $ref objects, handling both pure and mixed references.
+
+ This function processes JSON Schema objects containing $ref properties by resolving
+ the references and merging any additional properties. It handles:
+
+ - Pure `$ref` objects: `{"$ref": "#/path/to/definition"}`
+ - Mixed `$ref` objects: `{"$ref": "#/path", "title": "Custom Title", ...}`
+ - Circular references by breaking cycles and preserving non-ref properties
+
+ Args:
+ obj: The object to process (can be dict, list, or primitive)
+ full_schema: The complete schema containing all definitions
+ processed_refs: Set tracking currently processing refs (for cycle detection)
+ skip_keys: Keys under which to skip recursion
+ shallow_refs: If `True`, only break cycles; if `False`, deep-inline all refs
+
+ Returns:
+ The object with `$ref` properties resolved and merged with other properties.
+ """
+ if processed_refs is None:
+ processed_refs = set()
+
+ # Case 1: Object contains a $ref property (pure or mixed with additional properties)
+ if isinstance(obj, dict) and "$ref" in obj:
+ ref_path = obj["$ref"]
+ additional_properties = {
+ key: value for key, value in obj.items() if key != "$ref"
+ }
+
+ # Detect circular reference: if we're already processing this $ref,
+ # return only the additional properties to break the cycle
+ if ref_path in processed_refs:
+ return _process_dict_properties(
+ additional_properties,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+
+ # Mark this reference as being processed (for cycle detection)
+ processed_refs.add(ref_path)
+
+ # Fetch and recursively resolve the referenced object
+ referenced_object = deepcopy(_retrieve_ref(ref_path, full_schema))
+ resolved_reference = _dereference_refs_helper(
+ referenced_object,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+
+ # Clean up: remove from processing set before returning
+ processed_refs.remove(ref_path)
+
+ # Pure $ref case: no additional properties, return resolved reference directly
+ if not additional_properties:
+ return resolved_reference
+
+ # Mixed $ref case: merge resolved reference with additional properties
+ # Additional properties take precedence over resolved properties
+ merged_result = {}
+ if isinstance(resolved_reference, dict):
+ merged_result.update(resolved_reference)
+
+ # Process additional properties and merge them (they override resolved ones)
+ processed_additional = _process_dict_properties(
+ additional_properties,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+ merged_result.update(processed_additional)
+
+ return merged_result
+
+ # Case 2: Regular dictionary without $ref - process all properties
+ if isinstance(obj, dict):
+ return _process_dict_properties(
+ obj, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+
+ # Case 3: List - recursively process each item
+ if isinstance(obj, list):
+ return [
+ _dereference_refs_helper(
+ item, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+ for item in obj
+ ]
+
+ # Case 4: Primitive value (string, number, boolean, null) - return unchanged
+ return obj
+
+
+def dereference_refs(
+ schema_obj: dict,
+ *,
+ full_schema: dict | None = None,
+ skip_keys: Sequence[str] | None = None,
+) -> dict:
+ """Resolve and inline JSON Schema `$ref` references in a schema object.
+
+ This function processes a JSON Schema and resolves all `$ref` references by
+ replacing them with the actual referenced content.
+
+ Handles both simple references and complex cases like circular references and mixed
+ `$ref` objects that contain additional properties alongside the `$ref`.
+
+ Args:
+ schema_obj: The JSON Schema object or fragment to process.
+
+ This can be a complete schema or just a portion of one.
+ full_schema: The complete schema containing all definitions that `$refs` might
+ point to.
+
+ If not provided, defaults to `schema_obj` (useful when the schema is
+ self-contained).
+ skip_keys: Controls recursion behavior and reference resolution depth.
+
+ - If `None` (Default): Only recurse under `'$defs'` and use shallow
+ reference resolution (break cycles but don't deep-inline nested refs)
+ - If provided (even as `[]`): Recurse under all keys and use deep reference
+ resolution (fully inline all nested references)
+
+ Returns:
+ A new dictionary with all $ref references resolved and inlined.
+
+ The original `schema_obj` is not modified.
+
+ Examples:
+ Basic reference resolution:
+ >>> schema = {
+ ... "type": "object",
+ ... "properties": {"name": {"$ref": "#/$defs/string_type"}},
+ ... "$defs": {"string_type": {"type": "string"}},
+ ... }
+ >>> result = dereference_refs(schema)
+ >>> result["properties"]["name"] # {"type": "string"}
+
+ Mixed `$ref` with additional properties:
+
+ >>> schema = {
+ ... "properties": {
+ ... "name": {"$ref": "#/$defs/base", "description": "User name"}
+ ... },
+ ... "$defs": {"base": {"type": "string", "minLength": 1}},
+ ... }
+ >>> result = dereference_refs(schema)
+ >>> result["properties"]["name"]
+ # {"type": "string", "minLength": 1, "description": "User name"}
+
+ Handling circular references:
+
+ >>> schema = {
+ ... "properties": {"user": {"$ref": "#/$defs/User"}},
+ ... "$defs": {
+ ... "User": {
+ ... "type": "object",
+ ... "properties": {"friend": {"$ref": "#/$defs/User"}},
+ ... }
+ ... },
+ ... }
+ >>> result = dereference_refs(schema) # Won't cause infinite recursion
+
+ !!! note
+
+ - Circular references are handled gracefully by breaking cycles
+ - Mixed `$ref` objects (with both `$ref` and other properties) are supported
+ - Additional properties in mixed `$refs` override resolved properties
+ - The `$defs` section is preserved in the output by default
+ """
+ full = full_schema or schema_obj
+ keys_to_skip = list(skip_keys) if skip_keys is not None else ["$defs"]
+ shallow = skip_keys is None
+ return cast(
+ "dict",
+ _dereference_refs_helper(
+ schema_obj, full, None, keys_to_skip, shallow_refs=shallow
+ ),
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/mustache.py b/python/user_packages/Python313/site-packages/langchain_core/utils/mustache.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8282b0f38454cff37bdc66bcc5b0e9138bf1077
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/mustache.py
@@ -0,0 +1,704 @@
+"""Adapted from https://github.com/noahmorrison/chevron.
+
+MIT License.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterator, Mapping, Sequence
+from types import MappingProxyType
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+
+if TYPE_CHECKING:
+ from typing import TypeAlias
+
+logger = logging.getLogger(__name__)
+
+
+Scopes: TypeAlias = list[Literal[False, 0] | Mapping[str, Any]]
+
+
+# Globals
+_CURRENT_LINE = 1
+_LAST_TAG_LINE = None
+
+
+class ChevronError(SyntaxError):
+ """Custom exception for Chevron errors."""
+
+
+#
+# Helper functions
+#
+
+
+def grab_literal(template: str, l_del: str) -> tuple[str, str]:
+ """Parse a literal from the template.
+
+ Args:
+ template: The template to parse.
+ l_del: The left delimiter.
+
+ Returns:
+ The literal and the template.
+ """
+ global _CURRENT_LINE
+
+ try:
+ # Look for the next tag and move the template to it
+ literal, template = template.split(l_del, 1)
+ _CURRENT_LINE += literal.count("\n")
+
+ # There are no more tags in the template?
+ except ValueError:
+ # Then the rest of the template is a literal
+ return (template, "")
+
+ return (literal, template)
+
+
+def l_sa_check(
+ template: str, # noqa: ARG001
+ literal: str,
+ is_standalone: bool, # noqa: FBT001
+) -> bool:
+ """Do a preliminary check to see if a tag could be a standalone.
+
+ Args:
+ template: The template. (Not used.)
+ literal: The literal.
+ is_standalone: Whether the tag is standalone.
+
+ Returns:
+ Whether the tag could be a standalone.
+ """
+ # If there is a newline, or the previous tag was a standalone
+ if literal.find("\n") != -1 or is_standalone:
+ padding = literal.rsplit("\n", maxsplit=1)[-1]
+
+ # If all the characters since the last newline are spaces
+ # Then the next tag could be a standalone
+ # Otherwise it can't be
+ return padding.isspace() or not padding
+ return False
+
+
+def r_sa_check(
+ template: str,
+ tag_type: str,
+ is_standalone: bool, # noqa: FBT001
+) -> bool:
+ """Do a final check to see if a tag could be a standalone.
+
+ Args:
+ template: The template.
+ tag_type: The type of the tag.
+ is_standalone: Whether the tag is standalone.
+
+ Returns:
+ Whether the tag could be a standalone.
+ """
+ # Check right side if we might be a standalone
+ if is_standalone and tag_type not in {"variable", "no escape"}:
+ on_newline = template.split("\n", 1)
+
+ # If the stuff to the right of us are spaces we're a standalone
+ return on_newline[0].isspace() or not on_newline[0]
+
+ # If we're a tag can't be a standalone
+ return False
+
+
+def parse_tag(template: str, l_del: str, r_del: str) -> tuple[tuple[str, str], str]:
+ """Parse a tag from a template.
+
+ Args:
+ template: The template.
+ l_del: The left delimiter.
+ r_del: The right delimiter.
+
+ Returns:
+ The tag and the template.
+
+ Raises:
+ ChevronError: If the tag is unclosed.
+ ChevronError: If the set delimiter tag is unclosed.
+ """
+ tag_types = {
+ "!": "comment",
+ "#": "section",
+ "^": "inverted section",
+ "/": "end",
+ ">": "partial",
+ "=": "set delimiter?",
+ "{": "no escape?",
+ "&": "no escape",
+ }
+
+ # Get the tag
+ try:
+ tag, template = template.split(r_del, 1)
+ except ValueError as e:
+ msg = f"unclosed tag at line {_CURRENT_LINE}"
+ raise ChevronError(msg) from e
+
+ # Check for empty tags
+ if not tag.strip():
+ msg = f"empty tag at line {_CURRENT_LINE}"
+ raise ChevronError(msg)
+
+ # Find the type meaning of the first character
+ tag_type = tag_types.get(tag[0], "variable")
+
+ # If the type is not a variable
+ if tag_type != "variable":
+ # Then that first character is not needed
+ tag = tag[1:]
+
+ # If we might be a set delimiter tag
+ if tag_type == "set delimiter?":
+ # Double check to make sure we are
+ if tag.endswith("="):
+ tag_type = "set delimiter"
+ # Remove the equal sign
+ tag = tag[:-1]
+
+ # Otherwise we should complain
+ else:
+ msg = f"unclosed set delimiter tag\nat line {_CURRENT_LINE}"
+ raise ChevronError(msg)
+
+ elif (
+ # If we might be a no html escape tag
+ tag_type == "no escape?"
+ # And we have a third curly brace
+ # (And are using curly braces as delimiters)
+ and l_del == "{{"
+ and r_del == "}}"
+ and template.startswith("}")
+ ):
+ # Then we are a no html escape tag
+ template = template[1:]
+ tag_type = "no escape"
+
+ # Strip the whitespace off the key and return
+ return ((tag_type, tag.strip()), template)
+
+
+#
+# The main tokenizing function
+#
+
+
+def tokenize(
+ template: str, def_ldel: str = "{{", def_rdel: str = "}}"
+) -> Iterator[tuple[str, str]]:
+ """Tokenize a mustache template.
+
+ Tokenizes a mustache template in a generator fashion, using file-like objects. It
+ also accepts a string containing the template.
+
+ Args:
+ template: a file-like object, or a string of a mustache template
+ def_ldel: The default left delimiter
+ (`'{{'` by default, as in spec compliant mustache)
+ def_rdel: The default right delimiter
+ (`'}}'` by default, as in spec compliant mustache)
+
+ Yields:
+ Mustache tags in the form of a tuple `(tag_type, tag_key)` where `tag_type` is
+ one of:
+
+ * literal
+ * section
+ * inverted section
+ * end
+ * partial
+ * no escape
+
+ ...and `tag_key` is either the key or in the case of a literal tag, the
+ literal itself.
+
+ Raises:
+ ChevronError: If there is a syntax error in the template.
+ """
+ global _CURRENT_LINE, _LAST_TAG_LINE
+ _CURRENT_LINE = 1
+ _LAST_TAG_LINE = None
+
+ is_standalone = True
+ open_sections = []
+ l_del = def_ldel
+ r_del = def_rdel
+
+ while template:
+ literal, template = grab_literal(template, l_del)
+
+ # If the template is completed
+ if not template:
+ # Then yield the literal and leave
+ yield ("literal", literal)
+ break
+
+ # Do the first check to see if we could be a standalone
+ is_standalone = l_sa_check(template, literal, is_standalone)
+
+ # Parse the tag
+ tag, template = parse_tag(template, l_del, r_del)
+ tag_type, tag_key = tag
+
+ # Special tag logic
+
+ # If we are a set delimiter tag
+ if tag_type == "set delimiter":
+ # Then get and set the delimiters
+ dels = tag_key.strip().split(" ")
+ l_del, r_del = dels[0], dels[-1]
+
+ # If we are a section tag
+ elif tag_type in {"section", "inverted section"}:
+ # Then open a new section
+ open_sections.append(tag_key)
+ _LAST_TAG_LINE = _CURRENT_LINE
+
+ # If we are an end tag
+ elif tag_type == "end":
+ # Then check to see if the last opened section
+ # is the same as us
+ try:
+ last_section = open_sections.pop()
+ except IndexError as e:
+ msg = (
+ f'Trying to close tag "{tag_key}"\n'
+ "Looks like it was not opened.\n"
+ f"line {_CURRENT_LINE + 1}"
+ )
+ raise ChevronError(msg) from e
+ if tag_key != last_section:
+ # Otherwise we need to complain
+ msg = (
+ f'Trying to close tag "{tag_key}"\n'
+ f'last open tag is "{last_section}"\n'
+ f"line {_CURRENT_LINE + 1}"
+ )
+ raise ChevronError(msg)
+
+ # Do the second check to see if we're a standalone
+ is_standalone = r_sa_check(template, tag_type, is_standalone)
+
+ # Which if we are
+ if is_standalone:
+ # Remove the stuff before the newline
+ template = template.split("\n", 1)[-1]
+
+ # Partials need to keep the spaces on their left
+ if tag_type != "partial":
+ # But other tags don't
+ literal = literal.rstrip(" ")
+
+ # Start yielding
+ # Ignore literals that are empty
+ if literal:
+ yield ("literal", literal)
+
+ # Ignore comments and set delimiters
+ if tag_type not in {"comment", "set delimiter?"}:
+ yield (tag_type, tag_key)
+
+ # If there are any open sections when we're done
+ if open_sections:
+ # Then we need to complain
+ msg = (
+ "Unexpected EOF\n"
+ f'the tag "{open_sections[-1]}" was never closed\n'
+ f"was opened at line {_LAST_TAG_LINE}"
+ )
+ raise ChevronError(msg)
+
+
+#
+# Helper functions
+#
+
+
+def _html_escape(string: str) -> str:
+ """Return the HTML-escaped string with these characters escaped: `" & < >`."""
+ html_codes = {
+ '"': """,
+ "<": "<",
+ ">": ">",
+ }
+
+ # & must be handled first
+ string = string.replace("&", "&")
+ for char, code in html_codes.items():
+ string = string.replace(char, code)
+ return string
+
+
+def _get_key(
+ key: str,
+ scopes: Scopes,
+ *,
+ warn: bool,
+ keep: bool,
+ def_ldel: str,
+ def_rdel: str,
+) -> Any:
+ """Retrieve a value from the current scope using a dot-separated key path.
+
+ Traverses through nested dictionaries and lists using dot notation.
+
+ Supports special key `'.'` to return the current scope.
+
+ Args:
+ key: Dot-separated key path (e.g., `'user.name'` or `'.'` for current scope).
+ scopes: List of scope dictionaries to search through.
+ warn: Whether to log a warning when a key is not found.
+ keep: Whether to return the original template tag when key is not found.
+ def_ldel: Left delimiter for template (used when keep is `True`).
+ def_rdel: Right delimiter for template (used when keep is `True`).
+
+ Returns:
+ The value found at the key path.
+
+ If not found, returns the original template tag when keep is `True`,
+ otherwise returns an empty string.
+ """
+ # If the key is a dot
+ if key == ".":
+ # Then just return the current scope
+ return scopes[0]
+
+ # Loop through the scopes
+ for scope in scopes:
+ try:
+ # Return an empty string if falsy, with two exceptions
+ # 0 should return 0, and False should return False
+ if scope in (0, False):
+ return scope
+
+ resolved_scope = scope
+ # For every dot separated key
+ for child in key.split("."):
+ # Return an empty string if falsy, with two exceptions
+ # 0 should return 0, and False should return False
+ if resolved_scope in (0, False):
+ return resolved_scope
+ # Move into the scope
+ if isinstance(resolved_scope, dict):
+ try:
+ resolved_scope = resolved_scope[child]
+ except (KeyError, TypeError):
+ # Key not found - will be caught by outer try-except
+ msg = f"Key {child!r} not found in dict"
+ raise KeyError(msg) from None
+ elif isinstance(resolved_scope, (list, tuple)):
+ try:
+ resolved_scope = resolved_scope[int(child)]
+ except (ValueError, IndexError, TypeError):
+ # Invalid index - will be caught by outer try-except
+ msg = f"Invalid index {child!r} for list/tuple"
+ raise IndexError(msg) from None
+ else:
+ # Reject everything else for security
+ # This prevents traversing into arbitrary Python objects
+ msg = (
+ f"Cannot traverse into {type(resolved_scope).__name__}. "
+ "Mustache templates only support dict, list, and tuple. "
+ f"Got: {type(resolved_scope)}"
+ )
+ raise TypeError(msg) # noqa: TRY301
+
+ try:
+ # This allows for custom falsy data types
+ # https://github.com/noahmorrison/chevron/issues/35
+ if resolved_scope._CHEVRON_return_scope_when_falsy: # type: ignore[union-attr] # noqa: SLF001
+ return resolved_scope
+ except AttributeError:
+ if resolved_scope in (0, False):
+ return resolved_scope
+ return resolved_scope or ""
+ except (AttributeError, KeyError, IndexError, ValueError, TypeError):
+ # We couldn't find the key in the current scope
+ # TypeError: Attempted to traverse into non-dict/list type
+ # We'll try again on the next pass
+ pass
+
+ # We couldn't find the key in any of the scopes
+
+ if warn:
+ logger.warning("Could not find key '%s'", key)
+
+ if keep:
+ return f"{def_ldel} {key} {def_rdel}"
+
+ return ""
+
+
+def _get_partial(name: str, partials_dict: Mapping[str, str]) -> str:
+ """Load a partial.
+
+ Returns:
+ The partial.
+ """
+ try:
+ # Maybe the partial is in the dictionary
+ return partials_dict[name]
+ except KeyError:
+ return ""
+
+
+#
+# The main rendering function
+#
+g_token_cache: dict[str, list[tuple[str, str]]] = {}
+
+EMPTY_DICT: MappingProxyType[str, str] = MappingProxyType({})
+
+
+def render(
+ template: str | list[tuple[str, str]] = "",
+ data: Mapping[str, Any] = EMPTY_DICT,
+ partials_dict: Mapping[str, str] = EMPTY_DICT,
+ padding: str = "",
+ def_ldel: str = "{{",
+ def_rdel: str = "}}",
+ scopes: Scopes | None = None,
+ warn: bool = False, # noqa: FBT001,FBT002
+ keep: bool = False, # noqa: FBT001,FBT002
+) -> str:
+ """Render a mustache template.
+
+ Renders a mustache template with a data scope and inline partial capability.
+
+ Args:
+ template: A file-like object or a string containing the template.
+ data: A python dictionary with your data scope.
+ partials_dict: A python dictionary which will be search for partials
+ before the filesystem is.
+
+ `{'include': 'foo'}` is the same as a file called include.mustache
+ (defaults to `{}`).
+ padding: This is for padding partials, and shouldn't be used
+ (but can be if you really want to).
+ def_ldel: The default left delimiter
+
+ (`'{{'` by default, as in spec compliant mustache).
+ def_rdel: The default right delimiter
+
+ (`'}}'` by default, as in spec compliant mustache).
+ scopes: The list of scopes that `get_key` will look through.
+ warn: Log a warning when a template substitution isn't found in the data
+ keep: Keep unreplaced tags when a substitution isn't found in the data.
+
+ Returns:
+ A string containing the rendered template.
+ """
+ # If the template is a sequence but not derived from a string
+ if isinstance(template, Sequence) and not isinstance(template, str):
+ # Then we don't need to tokenize it
+ # But it does need to be a generator
+ tokens: Iterator[tuple[str, str]] = (token for token in template)
+ elif template in g_token_cache:
+ tokens = (token for token in g_token_cache[template])
+ else:
+ # Otherwise make a generator
+ tokens = tokenize(template, def_ldel, def_rdel)
+
+ output = ""
+
+ if scopes is None:
+ scopes = [data]
+
+ # Run through the tokens
+ for tag, key in tokens:
+ # Set the current scope
+ current_scope = scopes[0]
+
+ # If we're an end tag
+ if tag == "end":
+ # Pop out of the latest scope
+ del scopes[0]
+
+ # If the current scope is falsy and not the only scope
+ elif not current_scope and len(scopes) != 1:
+ if tag in {"section", "inverted section"}:
+ # Set the most recent scope to a falsy value
+ scopes.insert(0, False)
+
+ # If we're a literal tag
+ elif tag == "literal":
+ # Add padding to the key and add it to the output
+ output += key.replace("\n", "\n" + padding)
+
+ # If we're a variable tag
+ elif tag == "variable":
+ # Add the html escaped key to the output
+ thing = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ if thing is True and key == ".":
+ # if we've coerced into a boolean by accident
+ # (inverted tags do this)
+ # then get the un-coerced object (next in the stack)
+ thing = scopes[1]
+ if not isinstance(thing, str):
+ thing = str(thing)
+ output += _html_escape(thing)
+
+ # If we're a no html escape tag
+ elif tag == "no escape":
+ # Just lookup the key and add it
+ thing = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ if not isinstance(thing, str):
+ thing = str(thing)
+ output += thing
+
+ # If we're a section tag
+ elif tag == "section":
+ # Get the sections scope
+ scope = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+
+ # If the scope is a callable (as described in
+ # https://mustache.github.io/mustache.5.html)
+ if callable(scope):
+ # Generate template text from tags
+ text = ""
+ tags: list[tuple[str, str]] = []
+ for token in tokens:
+ if token == ("end", key):
+ break
+
+ tags.append(token)
+ tag_type, tag_key = token
+ if tag_type == "literal":
+ text += tag_key
+ elif tag_type == "no escape":
+ text += f"{def_ldel}& {tag_key} {def_rdel}"
+ else:
+ text += "{}{} {}{}".format(
+ def_ldel,
+ {
+ "comment": "!",
+ "section": "#",
+ "inverted section": "^",
+ "end": "/",
+ "partial": ">",
+ "set delimiter": "=",
+ "no escape": "&",
+ "variable": "",
+ }[tag_type],
+ tag_key,
+ def_rdel,
+ )
+
+ g_token_cache[text] = tags
+
+ rend = scope(
+ text,
+ lambda template, data=None: render(
+ template,
+ data={},
+ partials_dict=partials_dict,
+ padding=padding,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ scopes=(data and [data, *scopes]) or scopes,
+ warn=warn,
+ keep=keep,
+ ),
+ )
+
+ output += rend
+
+ # If the scope is a sequence, an iterator or generator but not
+ # derived from a string
+ elif isinstance(scope, (Sequence, Iterator)) and not isinstance(scope, str):
+ # Then we need to do some looping
+
+ # Gather up all the tags inside the section
+ # (And don't be tricked by nested end tags with the same key)
+ # TODO: This feels like it still has edge cases, no?
+ tags = []
+ tags_with_same_key = 0
+ for token in tokens:
+ if token == ("section", key):
+ tags_with_same_key += 1
+ if token == ("end", key):
+ tags_with_same_key -= 1
+ if tags_with_same_key < 0:
+ break
+ tags.append(token)
+
+ # For every item in the scope
+ for thing in scope:
+ # Append it as the most recent scope and render
+ new_scope = [thing, *scopes]
+ rend = render(
+ template=tags,
+ scopes=new_scope,
+ padding=padding,
+ partials_dict=partials_dict,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ warn=warn,
+ keep=keep,
+ )
+
+ output += rend
+
+ else:
+ # Otherwise we're just a scope section
+ scopes.insert(0, scope)
+
+ # If we're an inverted section
+ elif tag == "inverted section":
+ # Add the flipped scope to the scopes
+ scope = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ scopes.insert(0, cast("Literal[False]", not scope))
+
+ # If we're a partial
+ elif tag == "partial":
+ # Load the partial
+ partial = _get_partial(key, partials_dict)
+
+ # Find what to pad the partial with
+ left = output.rpartition("\n")[2]
+ part_padding = padding
+ if left.isspace():
+ part_padding += left
+
+ # Render the partial
+ part_out = render(
+ template=partial,
+ partials_dict=partials_dict,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ padding=part_padding,
+ scopes=scopes,
+ warn=warn,
+ keep=keep,
+ )
+
+ # If the partial was indented
+ if left.isspace():
+ # then remove the spaces from the end
+ part_out = part_out.rstrip(" \t")
+
+ # Add the partials output to the output
+ output += part_out
+
+ return output
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/pydantic.py b/python/user_packages/Python313/site-packages/langchain_core/utils/pydantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1c152d8d53b13d8ca1709b8b84558691a82f796
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/pydantic.py
@@ -0,0 +1,589 @@
+"""Utilities for pydantic."""
+
+from __future__ import annotations
+
+import inspect
+import textwrap
+import warnings
+from contextlib import nullcontext
+from functools import lru_cache, wraps
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypeVar,
+ cast,
+ overload,
+)
+
+import pydantic
+from packaging import version
+
+# root_validator is deprecated but we need it for backward compatibility of @pre_init
+from pydantic import ( # type: ignore[deprecated]
+ BaseModel,
+ ConfigDict,
+ Field,
+ PydanticDeprecationWarning,
+ RootModel,
+ root_validator,
+)
+from pydantic import (
+ create_model as _create_model_base,
+)
+from pydantic.fields import FieldInfo as FieldInfoV2
+from pydantic.json_schema import (
+ DEFAULT_REF_TEMPLATE,
+ GenerateJsonSchema,
+ JsonSchemaMode,
+ JsonSchemaValue,
+)
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import create_model as create_model_v1
+from typing_extensions import deprecated, override
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from pydantic.v1.fields import ModelField
+ from pydantic_core import core_schema
+
+PYDANTIC_VERSION = version.parse(pydantic.__version__)
+
+
+@deprecated("Use PYDANTIC_VERSION.major instead.")
+def get_pydantic_major_version() -> int:
+ """DEPRECATED - Get the major version of Pydantic.
+
+ Use `PYDANTIC_VERSION.major` instead.
+
+ Returns:
+ The major version of Pydantic.
+ """
+ return PYDANTIC_VERSION.major
+
+
+PYDANTIC_MAJOR_VERSION = PYDANTIC_VERSION.major
+PYDANTIC_MINOR_VERSION = PYDANTIC_VERSION.minor
+
+IS_PYDANTIC_V1 = False
+IS_PYDANTIC_V2 = True
+
+PydanticBaseModel = BaseModel
+TypeBaseModel = type[BaseModel]
+
+TBaseModel = TypeVar("TBaseModel", bound=PydanticBaseModel)
+
+
+def is_pydantic_v1_subclass(cls: type) -> bool:
+ """Check if the given class is Pydantic v1-like.
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel` 1.x.
+ """
+ return issubclass(cls, BaseModelV1)
+
+
+def is_pydantic_v2_subclass(cls: type) -> bool:
+ """Check if the given class is Pydantic v2-like.
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel` 2.x.
+ """
+ return issubclass(cls, BaseModel)
+
+
+def is_basemodel_subclass(cls: type) -> bool:
+ """Check if the given class is a subclass of Pydantic `BaseModel`.
+
+ Check if the given class is a subclass of any of the following:
+
+ * `pydantic.BaseModel` in Pydantic 2.x
+ * `pydantic.v1.BaseModel` in Pydantic 2.x
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel`.
+ """
+ # Before we can use issubclass on the cls we need to check if it is a class
+ if not inspect.isclass(cls) or isinstance(cls, GenericAlias):
+ return False
+
+ return issubclass(cls, (BaseModel, BaseModelV1))
+
+
+def is_basemodel_instance(obj: Any) -> bool:
+ """Check if the given class is an instance of Pydantic `BaseModel`.
+
+ Check if the given class is an instance of any of the following:
+
+ * `pydantic.BaseModel` in Pydantic 2.x
+ * `pydantic.v1.BaseModel` in Pydantic 2.x
+
+ Returns:
+ `True` if the given class is an instance of Pydantic `BaseModel`.
+ """
+ return isinstance(obj, (BaseModel, BaseModelV1))
+
+
+# How to type hint this?
+def pre_init(func: Callable) -> Any:
+ """Decorator to run a function before model initialization.
+
+ Args:
+ func: The function to run before model initialization.
+
+ Returns:
+ The decorated function.
+ """
+ with warnings.catch_warnings():
+ warnings.filterwarnings(action="ignore", category=PydanticDeprecationWarning)
+
+ # Ideally we would use @model_validator(mode="before") but this would change the
+ # order of the validators. See https://github.com/pydantic/pydantic/discussions/7434.
+ # So we keep root_validator for backward compatibility.
+ @root_validator(pre=True) # type: ignore[deprecated]
+ @wraps(func)
+ def wrapper(cls: type[BaseModel], values: dict[str, Any]) -> Any:
+ """Decorator to run a function before model initialization.
+
+ Args:
+ cls: The model class.
+ values: The values to initialize the model with.
+
+ Returns:
+ The values to initialize the model with.
+ """
+ # Insert default values
+ fields = cls.model_fields
+ for name, field_info in fields.items():
+ # Check if allow_population_by_field_name is enabled
+ # If yes, then set the field name to the alias
+ if (
+ hasattr(cls, "Config")
+ and hasattr(cls.Config, "allow_population_by_field_name")
+ and cls.Config.allow_population_by_field_name
+ and field_info.alias in values
+ ):
+ values[name] = values.pop(field_info.alias)
+ if (
+ hasattr(cls, "model_config")
+ and cls.model_config.get("populate_by_name")
+ and field_info.alias in values
+ ):
+ values[name] = values.pop(field_info.alias)
+
+ if (
+ name not in values or values[name] is None
+ ) and not field_info.is_required():
+ if field_info.default_factory is not None:
+ values[name] = field_info.default_factory() # type: ignore[call-arg]
+ else:
+ values[name] = field_info.default
+
+ # Call the decorated function
+ return func(cls, values)
+
+ return wrapper
+
+
+class _IgnoreUnserializable(GenerateJsonSchema):
+ """A JSON schema generator that ignores unknown types.
+
+ https://docs.pydantic.dev/latest/concepts/json_schema/#customizing-the-json-schema-generation-process
+ """
+
+ @override
+ def handle_invalid_for_json_schema(
+ self, schema: core_schema.CoreSchema, error_info: str
+ ) -> JsonSchemaValue:
+ return {}
+
+
+def _create_subset_model_v1(
+ name: str,
+ model: type[BaseModelV1],
+ field_names: list,
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModelV1]:
+ """Create a Pydantic model with only a subset of model's fields."""
+ fields = {}
+
+ for field_name in field_names:
+ # Using pydantic v1 so can access __fields__ as a dict.
+ field = model.__fields__[field_name]
+ t = (
+ # this isn't perfect but should work for most functions
+ field.outer_type_
+ if field.required and not field.allow_none
+ else field.outer_type_ | None
+ )
+ if descriptions and field_name in descriptions:
+ field.field_info.description = descriptions[field_name]
+ fields[field_name] = (t, field.field_info)
+
+ rtn = cast("type[BaseModelV1]", create_model_v1(name, **fields)) # type: ignore[call-overload]
+ rtn.__doc__ = textwrap.dedent(fn_description or model.__doc__ or "")
+ return rtn
+
+
+def _create_subset_model_v2(
+ name: str,
+ model: type[BaseModel],
+ field_names: list[str],
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModel]:
+ """Create a Pydantic model with a subset of the model fields."""
+ descriptions_ = descriptions or {}
+ fields = {}
+ for field_name in field_names:
+ field = model.model_fields[field_name]
+ description = descriptions_.get(field_name, field.description)
+ field_kwargs: dict[str, Any] = {"description": description}
+ if field.default_factory is not None:
+ field_kwargs["default_factory"] = field.default_factory
+ else:
+ field_kwargs["default"] = field.default
+ field_info = FieldInfoV2(**field_kwargs)
+ if field.metadata:
+ field_info.metadata = field.metadata
+ fields[field_name] = (field.annotation, field_info)
+
+ rtn = cast(
+ "type[BaseModel]",
+ _create_model_base( # type: ignore[call-overload]
+ name, **fields, __config__=ConfigDict(arbitrary_types_allowed=True)
+ ),
+ )
+
+ # TODO(0.3): Determine if there is a more "pydantic" way to preserve annotations.
+ # This is done to preserve __annotations__ when working with pydantic 2.x
+ # and using the Annotated type with TypedDict.
+ # Comment out the following line, to trigger the relevant test case.
+ selected_annotations = [
+ (name, annotation)
+ for name, annotation in model.__annotations__.items()
+ if name in field_names
+ ]
+
+ rtn.__annotations__ = dict(selected_annotations)
+ rtn.__doc__ = textwrap.dedent(fn_description or model.__doc__ or "")
+ return rtn
+
+
+# Private functionality to create a subset model that's compatible across
+# different versions of pydantic.
+# Handles pydantic versions 2.x. including v1 of pydantic in 2.x.
+# However, can't find a way to type hint this.
+def _create_subset_model(
+ name: str,
+ model: TypeBaseModel,
+ field_names: list[str],
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModel]:
+ """Create subset model using the same pydantic version as the input model.
+
+ Returns:
+ The created subset model.
+ """
+ if issubclass(model, BaseModelV1):
+ return _create_subset_model_v1(
+ name,
+ model,
+ field_names,
+ descriptions=descriptions,
+ fn_description=fn_description,
+ )
+ return _create_subset_model_v2(
+ name,
+ model,
+ field_names,
+ descriptions=descriptions,
+ fn_description=fn_description,
+ )
+
+
+@overload
+def get_fields(model: type[BaseModel]) -> dict[str, FieldInfoV2]: ...
+
+
+@overload
+def get_fields(model: BaseModel) -> dict[str, FieldInfoV2]: ...
+
+
+@overload
+def get_fields(model: type[BaseModelV1]) -> dict[str, ModelField]: ...
+
+
+@overload
+def get_fields(model: BaseModelV1) -> dict[str, ModelField]: ...
+
+
+def get_fields(
+ model: type[BaseModel | BaseModelV1] | BaseModel | BaseModelV1,
+) -> dict[str, FieldInfoV2] | dict[str, ModelField]:
+ """Return the field names of a Pydantic model.
+
+ Args:
+ model: The Pydantic model or instance.
+
+ Raises:
+ TypeError: If the model is not a Pydantic model.
+ """
+ if not isinstance(model, type):
+ model = type(model)
+ if issubclass(model, BaseModel):
+ return model.model_fields
+ if issubclass(model, BaseModelV1):
+ return model.__fields__
+ msg = f"Expected a Pydantic model. Got {model}"
+ raise TypeError(msg)
+
+
+_SchemaConfig = ConfigDict(
+ arbitrary_types_allowed=True, frozen=True, protected_namespaces=()
+)
+
+NO_DEFAULT = object()
+
+
+def _create_root_model(
+ name: str,
+ type_: Any,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ """Create a base class."""
+
+ def schema(
+ cls: type[BaseModelV1],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ ) -> dict[str, Any]:
+ super_cls = cast("type[BaseModelV1]", super(cls, cls))
+ schema_ = super_cls.schema(by_alias=by_alias, ref_template=ref_template)
+ schema_["title"] = name
+ return schema_
+
+ def model_json_schema(
+ cls: type[BaseModel],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+ mode: JsonSchemaMode = "validation",
+ ) -> dict[str, Any]:
+ super_cls = cast("type[BaseModel]", super(cls, cls))
+ schema_ = super_cls.model_json_schema(
+ by_alias=by_alias,
+ ref_template=ref_template,
+ schema_generator=schema_generator,
+ mode=mode,
+ )
+ schema_["title"] = name
+ return schema_
+
+ base_class_attributes = {
+ "__annotations__": {"root": type_},
+ "model_config": ConfigDict(arbitrary_types_allowed=True),
+ "schema": classmethod(schema),
+ "model_json_schema": classmethod(model_json_schema),
+ "__module__": module_name or "langchain_core.runnables.utils",
+ }
+
+ if default_ is not NO_DEFAULT:
+ base_class_attributes["root"] = default_
+ with warnings.catch_warnings():
+ try:
+ if (
+ isinstance(type_, type)
+ and not isinstance(type_, GenericAlias)
+ and issubclass(type_, BaseModelV1)
+ ):
+ warnings.filterwarnings(
+ action="ignore", category=PydanticDeprecationWarning
+ )
+ except TypeError:
+ pass
+ custom_root_type = type(name, (RootModel,), base_class_attributes)
+ return cast("type[BaseModel]", custom_root_type)
+
+
+@lru_cache(maxsize=256)
+def _create_root_model_cached(
+ model_name: str,
+ type_: Any,
+ *,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ return _create_root_model(
+ model_name, type_, default_=default_, module_name=module_name
+ )
+
+
+@lru_cache(maxsize=256)
+def _create_model_cached(
+ model_name: str,
+ /,
+ **field_definitions: Any,
+) -> type[BaseModel]:
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
+
+
+def create_model(
+ model_name: str,
+ module_name: str | None = None,
+ /,
+ **field_definitions: Any,
+) -> type[BaseModel]:
+ """Create a Pydantic model with the given field definitions.
+
+ Please use `create_model_v2` instead of this function.
+
+ Args:
+ model_name: The name of the model.
+ module_name: The name of the module where the model is defined.
+
+ This is used by Pydantic to resolve any forward references.
+ **field_definitions: The field definitions for the model.
+
+ Returns:
+ The created model.
+ """
+ kwargs = {}
+ if "__root__" in field_definitions:
+ kwargs["root"] = field_definitions.pop("__root__")
+
+ return create_model_v2(
+ model_name,
+ module_name=module_name,
+ field_definitions=field_definitions,
+ **kwargs,
+ )
+
+
+# Reserved names should capture all the `public` names / methods that are
+# used by BaseModel internally. This will keep the reserved names up-to-date.
+# For reference, the reserved names are:
+# "construct", "copy", "dict", "from_orm", "json", "parse_file", "parse_obj",
+# "parse_raw", "schema", "schema_json", "update_forward_refs", "validate",
+# "model_computed_fields", "model_config", "model_construct", "model_copy",
+# "model_dump", "model_dump_json", "model_extra", "model_fields",
+# "model_fields_set", "model_json_schema", "model_parametrized_name",
+# "model_post_init", "model_rebuild", "model_validate", "model_validate_json",
+# "model_validate_strings"
+_RESERVED_NAMES = {key for key in dir(BaseModel) if not key.startswith("_")}
+
+
+def _remap_field_definitions(field_definitions: dict[str, Any]) -> dict[str, Any]:
+ """This remaps fields to avoid colliding with internal pydantic fields."""
+ remapped = {}
+ for key, value in field_definitions.items():
+ if key.startswith("_") or key in _RESERVED_NAMES:
+ # Let's add a prefix to avoid colliding with internal pydantic fields
+ if isinstance(value, FieldInfoV2):
+ msg = (
+ f"Remapping for fields starting with '_' or fields with a name "
+ f"matching a reserved name {_RESERVED_NAMES} is not supported if "
+ f" the field is a pydantic Field instance. Got {key}."
+ )
+ raise NotImplementedError(msg)
+ type_, default_ = value
+ remapped[f"private_{key}"] = (
+ type_,
+ Field(
+ default=default_,
+ alias=key,
+ serialization_alias=key,
+ title=key.lstrip("_").replace("_", " ").title(),
+ ),
+ )
+ else:
+ remapped[key] = value
+ return remapped
+
+
+def create_model_v2(
+ model_name: str,
+ *,
+ module_name: str | None = None,
+ field_definitions: dict[str, Any] | None = None,
+ root: Any | None = None,
+) -> type[BaseModel]:
+ """Create a Pydantic model with the given field definitions.
+
+ !!! warning
+
+ Do not use outside of langchain packages. This API is subject to change at any
+ time.
+
+ Args:
+ model_name: The name of the model.
+ module_name: The name of the module where the model is defined.
+
+ This is used by Pydantic to resolve any forward references.
+ field_definitions: The field definitions for the model.
+ root: Type for a root model (`RootModel`)
+
+ Returns:
+ The created model.
+ """
+ field_definitions = field_definitions or {}
+
+ if root:
+ if field_definitions:
+ msg = (
+ "When specifying __root__ no other "
+ f"fields should be provided. Got {field_definitions}"
+ )
+ raise NotImplementedError(msg)
+
+ if isinstance(root, tuple):
+ kwargs = {"type_": root[0], "default_": root[1]}
+ else:
+ kwargs = {"type_": root}
+
+ try:
+ named_root_model = _create_root_model_cached(
+ model_name, module_name=module_name, **kwargs
+ )
+ except TypeError:
+ # something in the arguments into _create_root_model_cached is not hashable
+ named_root_model = _create_root_model(
+ model_name,
+ module_name=module_name,
+ **kwargs,
+ )
+ return named_root_model
+
+ # No root, just field definitions
+ names = set(field_definitions.keys())
+
+ capture_warnings = False
+
+ for name in names:
+ # Also if any non-reserved name is used (e.g., model_id or model_name)
+ if name.startswith("model"):
+ capture_warnings = True
+
+ with warnings.catch_warnings() if capture_warnings else nullcontext():
+ if capture_warnings:
+ warnings.filterwarnings(action="ignore")
+ try:
+ return _create_model_cached(model_name, **field_definitions)
+ except TypeError:
+ # something in field definitions is not hashable
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/strings.py b/python/user_packages/Python313/site-packages/langchain_core/utils/strings.py
new file mode 100644
index 0000000000000000000000000000000000000000..357b16f8e164b0bd61b6488f3bade77024d29fd8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/strings.py
@@ -0,0 +1,69 @@
+"""String utilities."""
+
+from collections.abc import Iterable
+from typing import Any
+
+
+def stringify_value(val: Any) -> str:
+ """Stringify a value.
+
+ Args:
+ val: The value to stringify.
+
+ Returns:
+ The stringified value.
+ """
+ if isinstance(val, str):
+ return val
+ if isinstance(val, dict):
+ return "\n" + stringify_dict(val)
+ if isinstance(val, list):
+ return "\n".join(stringify_value(v) for v in val)
+ return str(val)
+
+
+def stringify_dict(data: dict) -> str:
+ """Stringify a dictionary.
+
+ Args:
+ data: The dictionary to stringify.
+
+ Returns:
+ The stringified dictionary.
+ """
+ return "".join(f"{key}: {stringify_value(value)}\n" for key, value in data.items())
+
+
+def comma_list(items: Iterable[Any]) -> str:
+ """Convert an iterable to a comma-separated string.
+
+ Args:
+ items: The iterable to convert.
+
+ Returns:
+ The comma-separated string.
+ """
+ return ", ".join(str(item) for item in items)
+
+
+def sanitize_for_postgres(text: str, replacement: str = "") -> str:
+ r"""Sanitize text by removing NUL bytes that are incompatible with PostgreSQL.
+
+ PostgreSQL text fields cannot contain `NUL (0x00)` bytes, which can cause
+ `psycopg.DataError` when inserting documents. This function removes or replaces
+ such characters to ensure compatibility.
+
+ Args:
+ text: The text to sanitize.
+ replacement: String to replace `NUL` bytes with.
+
+ Returns:
+ The sanitized text with `NUL` bytes removed or replaced.
+
+ Example:
+ >>> sanitize_for_postgres("Hello\\x00world")
+ 'Helloworld'
+ >>> sanitize_for_postgres("Hello\\x00world", " ")
+ 'Hello world'
+ """
+ return text.replace("\x00", replacement)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/usage.py b/python/user_packages/Python313/site-packages/langchain_core/utils/usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..47e483a5555cd0cc64d0a21f9cca43ce4148ff31
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/usage.py
@@ -0,0 +1,60 @@
+"""Usage utilities."""
+
+from collections.abc import Callable
+
+
+def _dict_int_op(
+ left: dict,
+ right: dict,
+ op: Callable[[int, int], int],
+ *,
+ default: int = 0,
+ depth: int = 0,
+ max_depth: int = 100,
+) -> dict:
+ """Apply an integer operation to corresponding values in two dictionaries.
+
+ Recursively combines two dictionaries by applying the given operation to integer
+ values at matching keys.
+
+ Supports nested dictionaries.
+
+ Args:
+ left: First dictionary to combine.
+ right: Second dictionary to combine.
+ op: Binary operation function to apply to integer values.
+ default: Default value to use when a key is missing from a dictionary.
+ depth: Current recursion depth (used internally).
+ max_depth: Maximum recursion depth (to prevent infinite loops).
+
+ Returns:
+ A new dictionary with combined values.
+
+ Raises:
+ ValueError: If `max_depth` is exceeded or if value types are not supported.
+ """
+ if depth >= max_depth:
+ msg = f"{max_depth=} exceeded, unable to combine dicts."
+ raise ValueError(msg)
+ combined: dict = {}
+ for k in set(left).union(right):
+ if isinstance(left.get(k, default), int) and isinstance(
+ right.get(k, default), int
+ ):
+ combined[k] = op(left.get(k, default), right.get(k, default))
+ elif isinstance(left.get(k, {}), dict) and isinstance(right.get(k, {}), dict):
+ combined[k] = _dict_int_op(
+ left.get(k, {}),
+ right.get(k, {}),
+ op,
+ default=default,
+ depth=depth + 1,
+ max_depth=max_depth,
+ )
+ else:
+ types = [type(d[k]) for d in (left, right) if k in d]
+ msg = (
+ f"Unknown value types: {types}. Only dict and int values are supported."
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return combined
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/utils.py b/python/user_packages/Python313/site-packages/langchain_core/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a5ed999a28f8c9c56276d8aa60ecfd3f3f1d89
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/utils.py
@@ -0,0 +1,521 @@
+"""Generic utility functions."""
+
+import contextlib
+import datetime
+import functools
+import importlib
+import os
+import warnings
+from collections.abc import Callable, Iterator, Sequence
+from importlib.metadata import version
+from typing import Any, overload
+from uuid import uuid4
+
+from packaging.version import parse
+from pydantic import SecretStr
+from requests import HTTPError, Response
+from typing_extensions import override
+
+from langchain_core.utils.pydantic import (
+ is_pydantic_v1_subclass,
+)
+
+
+def xor_args(*arg_groups: tuple[str, ...]) -> Callable:
+ """Validate specified keyword args are mutually exclusive.
+
+ Args:
+ *arg_groups: Groups of mutually exclusive keyword args.
+
+ Returns:
+ Decorator that validates the specified keyword args are mutually exclusive.
+ """
+
+ def decorator(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Validate exactly one arg in each group is not None."""
+ counts = [
+ sum(1 for arg in arg_group if kwargs.get(arg) is not None)
+ for arg_group in arg_groups
+ ]
+ invalid_groups = [i for i, count in enumerate(counts) if count != 1]
+ if invalid_groups:
+ invalid_group_names = [", ".join(arg_groups[i]) for i in invalid_groups]
+ msg = (
+ "Exactly one argument in each of the following"
+ " groups must be defined:"
+ f" {', '.join(invalid_group_names)}"
+ )
+ raise ValueError(msg)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
+
+
+def raise_for_status_with_text(response: Response) -> None:
+ """Raise an error with the response text.
+
+ Args:
+ response: The response to check for errors.
+
+ Raises:
+ ValueError: If the response has an error status code.
+ """
+ try:
+ response.raise_for_status()
+ except HTTPError as e:
+ raise ValueError(response.text) from e
+
+
+@contextlib.contextmanager
+def mock_now(dt_value: datetime.datetime) -> Iterator[type]:
+ """Context manager for mocking out datetime.now() in unit tests.
+
+ Args:
+ dt_value: The datetime value to use for datetime.now().
+
+ Yields:
+ The mocked datetime class.
+
+ Example:
+ ```python
+ with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):
+ assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)
+ ```
+ """
+
+ class MockDateTime(datetime.datetime):
+ """Mock datetime.datetime.now() with a fixed datetime."""
+
+ @classmethod
+ @override
+ def now(cls, tz: datetime.tzinfo | None = None) -> "MockDateTime":
+ # Create a copy of dt_value.
+ return MockDateTime(
+ dt_value.year,
+ dt_value.month,
+ dt_value.day,
+ dt_value.hour,
+ dt_value.minute,
+ dt_value.second,
+ dt_value.microsecond,
+ dt_value.tzinfo,
+ )
+
+ real_datetime = datetime.datetime
+ datetime.datetime = MockDateTime # type: ignore[misc]
+ try:
+ yield datetime.datetime
+ finally:
+ datetime.datetime = real_datetime # type: ignore[misc]
+
+
+def guard_import(
+ module_name: str, *, pip_name: str | None = None, package: str | None = None
+) -> Any:
+ """Dynamically import a module.
+
+ Raise an exception if the module is not installed.
+
+ Args:
+ module_name: The name of the module to import.
+ pip_name: The name of the module to install with pip.
+ package: The package to import the module from.
+
+ Returns:
+ The imported module.
+
+ Raises:
+ ImportError: If the module is not installed.
+ """
+ try:
+ module = importlib.import_module(module_name, package)
+ except (ImportError, ModuleNotFoundError) as e:
+ pip_name = pip_name or module_name.split(".", maxsplit=1)[0].replace("_", "-")
+ msg = (
+ f"Could not import {module_name} python package. "
+ f"Please install it with `pip install {pip_name}`."
+ )
+ raise ImportError(msg) from e
+ return module
+
+
+def check_package_version(
+ package: str,
+ lt_version: str | None = None,
+ lte_version: str | None = None,
+ gt_version: str | None = None,
+ gte_version: str | None = None,
+) -> None:
+ """Check the version of a package.
+
+ Args:
+ package: The name of the package.
+ lt_version: The version must be less than this.
+ lte_version: The version must be less than or equal to this.
+ gt_version: The version must be greater than this.
+ gte_version: The version must be greater than or equal to this.
+
+
+ Raises:
+ ValueError: If the package version does not meet the requirements.
+ """
+ imported_version = parse(version(package))
+ if lt_version is not None and imported_version >= parse(lt_version):
+ msg = (
+ f"Expected {package} version to be < {lt_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if lte_version is not None and imported_version > parse(lte_version):
+ msg = (
+ f"Expected {package} version to be <= {lte_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if gt_version is not None and imported_version <= parse(gt_version):
+ msg = (
+ f"Expected {package} version to be > {gt_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if gte_version is not None and imported_version < parse(gte_version):
+ msg = (
+ f"Expected {package} version to be >= {gte_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+
+
+def get_pydantic_field_names(pydantic_cls: Any) -> set[str]:
+ """Get field names, including aliases, for a pydantic class.
+
+ Args:
+ pydantic_cls: Pydantic class.
+
+ Returns:
+ Field names.
+ """
+ all_required_field_names = set()
+ if is_pydantic_v1_subclass(pydantic_cls):
+ for field in pydantic_cls.__fields__.values():
+ all_required_field_names.add(field.name)
+ if field.has_alias:
+ all_required_field_names.add(field.alias)
+ else: # Assuming pydantic 2 for now
+ for name, field in pydantic_cls.model_fields.items():
+ all_required_field_names.add(name)
+ if field.alias:
+ all_required_field_names.add(field.alias)
+ return all_required_field_names
+
+
+def _build_model_kwargs(
+ values: dict[str, Any],
+ all_required_field_names: set[str],
+) -> dict[str, Any]:
+ """Build `model_kwargs` param from Pydantic constructor values.
+
+ Args:
+ values: All init args passed in by user.
+ all_required_field_names: All required field names for the pydantic class.
+
+ Returns:
+ Extra kwargs.
+
+ Raises:
+ ValueError: If a field is specified in both `values` and `extra_kwargs`.
+ ValueError: If a field is specified in `model_kwargs`.
+ """
+ extra_kwargs = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra_kwargs:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ warnings.warn(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended.""",
+ stacklevel=7,
+ )
+ extra_kwargs[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra_kwargs.keys())
+ if invalid_model_kwargs:
+ warnings.warn(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter.",
+ stacklevel=7,
+ )
+ for k in invalid_model_kwargs:
+ values[k] = extra_kwargs.pop(k)
+
+ values["model_kwargs"] = extra_kwargs
+ return values
+
+
+# DON'T USE! Kept for backwards-compatibility but should never have been public.
+def build_extra_kwargs(
+ extra_kwargs: dict[str, Any],
+ values: dict[str, Any],
+ all_required_field_names: set[str],
+) -> dict[str, Any]:
+ """Build extra kwargs from values and extra_kwargs.
+
+ !!! danger "DON'T USE"
+
+ Kept for backwards-compatibility but should never have been public. Use the
+ internal `_build_model_kwargs` function instead.
+
+ Args:
+ extra_kwargs: Extra kwargs passed in by user.
+ values: Values passed in by user.
+ all_required_field_names: All required field names for the pydantic class.
+
+ Returns:
+ Extra kwargs.
+
+ Raises:
+ ValueError: If a field is specified in both `values` and `extra_kwargs`.
+ ValueError: If a field is specified in `model_kwargs`.
+ """
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ for field_name in list(values):
+ if field_name in extra_kwargs:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ warnings.warn(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended.""",
+ stacklevel=7,
+ )
+ extra_kwargs[field_name] = values.pop(field_name)
+
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ invalid_model_kwargs = all_required_field_names.intersection(extra_kwargs.keys())
+ if invalid_model_kwargs:
+ msg = (
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+ raise ValueError(msg)
+
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ return extra_kwargs
+
+
+def convert_to_secret_str(value: SecretStr | str) -> SecretStr:
+ """Convert a string to a `SecretStr` if needed.
+
+ Args:
+ value: The value to convert.
+
+ Returns:
+ The `SecretStr` value.
+ """
+ if isinstance(value, SecretStr):
+ return value
+ return SecretStr(value)
+
+
+class _NoDefaultType:
+ """Type to indicate no default value is provided."""
+
+
+_NoDefault = _NoDefaultType()
+
+
+@overload
+def from_env(key: str, /) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: str, /, *, default: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: Sequence[str], /, *, default: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: str, /, *, error_message: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(
+ key: str | Sequence[str], /, *, default: str, error_message: str | None
+) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(
+ key: str, /, *, default: None, error_message: str | None
+) -> Callable[[], str | None]: ...
+
+
+@overload
+def from_env(
+ key: str | Sequence[str], /, *, default: None
+) -> Callable[[], str | None]: ...
+
+
+def from_env(
+ key: str | Sequence[str],
+ /,
+ *,
+ default: str | _NoDefaultType | None = _NoDefault,
+ error_message: str | None = None,
+) -> Callable[[], str] | Callable[[], str | None]:
+ """Create a factory method that gets a value from an environment variable.
+
+ Args:
+ key: The environment variable to look up.
+
+ If a list of keys is provided, the first key found in the environment will
+ be used. If no key is found, the default value will be used if set,
+ otherwise an error will be raised.
+ default: The default value to return if the environment variable is not set.
+ error_message: The error message which will be raised if the key is not found
+ and no default value is provided.
+
+ This will be raised as a ValueError.
+
+ Returns:
+ Factory method that will look up the value from the environment.
+ """
+
+ def get_from_env_fn() -> str | None:
+ """Get a value from an environment variable.
+
+ Raises:
+ ValueError: If the environment variable is not set and no default is
+ provided.
+
+ Returns:
+ The value from the environment.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if k in os.environ:
+ return os.environ[k]
+ if isinstance(key, str) and key in os.environ:
+ return os.environ[key]
+
+ if isinstance(default, (str, type(None))):
+ return default
+ if error_message:
+ raise ValueError(error_message)
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
+
+ return get_from_env_fn
+
+
+@overload
+def secret_from_env(key: str | Sequence[str], /) -> Callable[[], SecretStr]: ...
+
+
+@overload
+def secret_from_env(key: str, /, *, default: str) -> Callable[[], SecretStr]: ...
+
+
+@overload
+def secret_from_env(
+ key: str | Sequence[str], /, *, default: None
+) -> Callable[[], SecretStr | None]: ...
+
+
+@overload
+def secret_from_env(key: str, /, *, error_message: str) -> Callable[[], SecretStr]: ...
+
+
+def secret_from_env(
+ key: str | Sequence[str],
+ /,
+ *,
+ default: str | _NoDefaultType | None = _NoDefault,
+ error_message: str | None = None,
+) -> Callable[[], SecretStr | None] | Callable[[], SecretStr]:
+ """Secret from env.
+
+ Args:
+ key: The environment variable to look up.
+ default: The default value to return if the environment variable is not set.
+ error_message: The error message which will be raised if the key is not found
+ and no default value is provided.
+
+ This will be raised as a `ValueError`.
+
+ Returns:
+ Factory method that will look up the secret from the environment.
+ """
+
+ def get_secret_from_env() -> SecretStr | None:
+ """Get a value from an environment variable.
+
+ Raises:
+ ValueError: If the environment variable is not set and no default is
+ provided.
+
+ Returns:
+ The secret from the environment.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if k in os.environ:
+ return SecretStr(os.environ[k])
+ if isinstance(key, str) and key in os.environ:
+ return SecretStr(os.environ[key])
+ if isinstance(default, str):
+ return SecretStr(default)
+ if default is None:
+ return None
+ if error_message:
+ raise ValueError(error_message)
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
+
+ return get_secret_from_env
+
+
+LC_AUTO_PREFIX = "lc_"
+"""LangChain auto-generated ID prefix for messages and content blocks."""
+
+LC_ID_PREFIX = "lc_run-"
+"""Internal tracing/callback system identifier.
+
+Used for:
+
+- Tracing. Every LangChain operation (LLM call, chain execution, tool use, etc.)
+ gets a unique run_id (UUID)
+- Enables tracking parent-child relationships between operations
+"""
+
+
+def ensure_id(id_val: str | None) -> str:
+ """Ensure the ID is a valid string, generating a new UUID if not provided.
+
+ Auto-generated UUIDs are prefixed by `'lc_'` to indicate they are
+ LangChain-generated IDs.
+
+ Args:
+ id_val: Optional string ID value to validate.
+
+ Returns:
+ A string ID, either the validated provided value or a newly generated UUID4.
+ """
+ return id_val or f"{LC_AUTO_PREFIX}{uuid4()}"
diff --git a/python/user_packages/Python313/site-packages/langchain_core/utils/uuid.py b/python/user_packages/Python313/site-packages/langchain_core/utils/uuid.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d895edabaa22b839c6100af1813ba5f7ae63fb1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/utils/uuid.py
@@ -0,0 +1,57 @@
+"""UUID utility functions.
+
+This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
+for tracing and similar operations.
+"""
+
+from __future__ import annotations
+
+import typing
+from uuid import UUID
+
+from uuid_utils.compat import uuid7 as _uuid_utils_uuid7
+
+if typing.TYPE_CHECKING:
+ from uuid import UUID
+
+_NANOS_PER_SECOND: typing.Final = 1_000_000_000
+
+
+def _to_timestamp_and_nanos(nanoseconds: int) -> tuple[int, int]:
+ """Split a nanosecond timestamp into seconds and remaining nanoseconds."""
+ seconds, nanos = divmod(nanoseconds, _NANOS_PER_SECOND)
+ return seconds, nanos
+
+
+def uuid7(nanoseconds: int | None = None) -> UUID:
+ """Generate a UUID from a Unix timestamp in nanoseconds and random bits.
+
+ UUIDv7 objects feature monotonicity within a millisecond.
+
+ Args:
+ nanoseconds: Optional ns timestamp. If not provided, uses current time.
+
+ Returns:
+ A UUIDv7 object.
+ """
+ # --- 48 --- -- 4 -- --- 12 --- -- 2 -- --- 30 --- - 32 -
+ # unix_ts_ms | version | counter_hi | variant | counter_lo | random
+ #
+ # 'counter = counter_hi | counter_lo' is a 42-bit counter constructed
+ # with Method 1 of RFC 9562, §6.2, and its MSB is set to 0.
+ #
+ # 'random' is a 32-bit random value regenerated for every new UUID.
+ #
+ # If multiple UUIDs are generated within the same millisecond, the LSB
+ # of 'counter' is incremented by 1. When overflowing, the timestamp is
+ # advanced and the counter is reset to a random 42-bit integer with MSB
+ # set to 0.
+
+ # For now, just delegate to the uuid_utils implementation
+ if nanoseconds is None:
+ return _uuid_utils_uuid7()
+ seconds, nanos = _to_timestamp_and_nanos(nanoseconds)
+ return _uuid_utils_uuid7(timestamp=seconds, nanos=nanos)
+
+
+__all__ = ["uuid7"]
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__init__.py b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da27459d6bb8a831c4109aac36ba1b971594245
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__init__.py
@@ -0,0 +1,53 @@
+"""Vector stores."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.vectorstores.base import VST, VectorStore, VectorStoreRetriever
+ from langchain_core.vectorstores.in_memory import InMemoryVectorStore
+
+__all__ = (
+ "VST",
+ "InMemoryVectorStore",
+ "VectorStore",
+ "VectorStoreRetriever",
+)
+
+_dynamic_imports = {
+ "VectorStore": "base",
+ "VST": "base",
+ "VectorStoreRetriever": "base",
+ "InMemoryVectorStore": "in_memory",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ """Dynamically import and return an attribute from a submodule.
+
+ This function enables lazy loading of vectorstore classes from submodules, reducing
+ initial import time and circular dependency issues.
+
+ Args:
+ attr_name: Name of the attribute to import.
+
+ Returns:
+ The imported attribute object.
+
+ Raises:
+ AttributeError: If the attribute is not found in `_dynamic_imports`.
+ """
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ """Return a list of available attributes for this module.
+
+ Returns:
+ List of attribute names that can be imported from this module.
+ """
+ return list(__all__)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e31cfbd25258266cbefe93e231b978e17c9dc0a5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..281cc4800c1406192f7037869dcdfd3b472982d7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d821bdf3daa01b6fd0df36a01a23ee40c09f404
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee0eb2f2ead507d07856ca940d6c68d250cd4a9b
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/base.py b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..827a05cc90dbc3f50c7224d5ec7a1d340c70e380
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/base.py
@@ -0,0 +1,1111 @@
+"""A vector store stores embedded data and performs vector search.
+
+One of the most common ways to store and search over unstructured data is to
+embed it and store the resulting embedding vectors, and then query the store
+and retrieve the data that are 'most similar' to the embedded query.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import warnings
+from abc import ABC, abstractmethod
+from itertools import cycle
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ClassVar,
+ TypeVar,
+)
+
+from pydantic import ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core.documents import Document
+from langchain_core.embeddings import Embeddings
+from langchain_core.retrievers import BaseRetriever, LangSmithRetrieverParams
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
+
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForRetrieverRun,
+ CallbackManagerForRetrieverRun,
+ )
+
+logger = logging.getLogger(__name__)
+
+VST = TypeVar("VST", bound="VectorStore")
+
+
+class VectorStore(ABC):
+ """Interface for vector store."""
+
+ def add_texts(
+ self,
+ texts: Iterable[str],
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ """Run more texts through the embeddings and add to the `VectorStore`.
+
+ Args:
+ texts: Iterable of strings to add to the `VectorStore`.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: `VectorStore` specific parameters.
+
+ One of the kwargs should be `ids` which is a list of ids
+ associated with the texts.
+
+ Returns:
+ List of IDs from adding the texts into the `VectorStore`.
+
+ Raises:
+ ValueError: If the number of metadatas does not match the number of texts.
+ ValueError: If the number of IDs does not match the number of texts.
+ """
+ if type(self).add_documents != VectorStore.add_documents:
+ # This condition is triggered if the subclass has provided
+ # an implementation of the upsert method.
+ # The existing add_texts
+ texts_: Sequence[str] = (
+ texts if isinstance(texts, (list, tuple)) else list(texts)
+ )
+ if metadatas and len(metadatas) != len(texts_):
+ msg = (
+ "The number of metadatas must match the number of texts."
+ f"Got {len(metadatas)} metadatas and {len(texts_)} texts."
+ )
+ raise ValueError(msg)
+ metadatas_ = iter(metadatas) if metadatas else cycle([{}])
+ ids_: Iterator[str | None] = iter(ids) if ids else cycle([None])
+ docs = [
+ Document(id=id_, page_content=text, metadata=metadata_)
+ for text, metadata_, id_ in zip(texts, metadatas_, ids_, strict=False)
+ ]
+ if ids is not None:
+ # For backward compatibility
+ kwargs["ids"] = ids
+
+ return self.add_documents(docs, **kwargs)
+ msg = f"`add_texts` has not been implemented for {self.__class__.__name__} "
+ raise NotImplementedError(msg)
+
+ @property
+ def embeddings(self) -> Embeddings | None:
+ """Access the query embedding object if available."""
+ logger.debug(
+ "The embeddings property has not been implemented for %s",
+ self.__class__.__name__,
+ )
+ return None
+
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:
+ """Delete by vector ID or other criteria.
+
+ Args:
+ ids: List of IDs to delete. If `None`, delete all.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ `True` if deletion is successful, `False` otherwise, `None` if not
+ implemented.
+ """
+ msg = "delete method must be implemented by subclass."
+ raise NotImplementedError(msg)
+
+ def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Get documents by their IDs.
+
+ The returned documents are expected to have the ID field set to the ID of the
+ document in the vector store.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to retrieve.
+
+ Returns:
+ List of `Document` objects.
+ """
+ msg = f"{self.__class__.__name__} does not yet support get_by_ids."
+ raise NotImplementedError(msg)
+
+ # Implementations should override this method to provide an async native version.
+ async def aget_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Async get documents by their IDs.
+
+ The returned documents are expected to have the ID field set to the ID of the
+ document in the vector store.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to retrieve.
+
+ Returns:
+ List of `Document` objects.
+ """
+ return await run_in_executor(None, self.get_by_ids, ids)
+
+ async def adelete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:
+ """Async delete by vector ID or other criteria.
+
+ Args:
+ ids: List of IDs to delete. If `None`, delete all.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ `True` if deletion is successful, `False` otherwise, `None` if not
+ implemented.
+ """
+ return await run_in_executor(None, self.delete, ids, **kwargs)
+
+ async def aadd_texts(
+ self,
+ texts: Iterable[str],
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ """Async run more texts through the embeddings and add to the `VectorStore`.
+
+ Args:
+ texts: Iterable of strings to add to the `VectorStore`.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list
+ **kwargs: `VectorStore` specific parameters.
+
+ Returns:
+ List of IDs from adding the texts into the `VectorStore`.
+
+ Raises:
+ ValueError: If the number of metadatas does not match the number of texts.
+ ValueError: If the number of IDs does not match the number of texts.
+ """
+ if ids is not None:
+ # For backward compatibility
+ kwargs["ids"] = ids
+ if type(self).aadd_documents != VectorStore.aadd_documents:
+ # This condition is triggered if the subclass has provided
+ # an implementation of the upsert method.
+ # The existing add_texts
+ texts_: Sequence[str] = (
+ texts if isinstance(texts, (list, tuple)) else list(texts)
+ )
+ if metadatas and len(metadatas) != len(texts_):
+ msg = (
+ "The number of metadatas must match the number of texts."
+ f"Got {len(metadatas)} metadatas and {len(texts_)} texts."
+ )
+ raise ValueError(msg)
+ metadatas_ = iter(metadatas) if metadatas else cycle([{}])
+ ids_: Iterator[str | None] = iter(ids) if ids else cycle([None])
+
+ docs = [
+ Document(id=id_, page_content=text, metadata=metadata_)
+ for text, metadata_, id_ in zip(texts, metadatas_, ids_, strict=False)
+ ]
+ return await self.aadd_documents(docs, **kwargs)
+ return await run_in_executor(None, self.add_texts, texts, metadatas, **kwargs)
+
+ def add_documents(self, documents: list[Document], **kwargs: Any) -> list[str]:
+ """Add or update documents in the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ If kwargs contains IDs and documents contain ids, the IDs in the kwargs
+ will receive precedence.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ if type(self).add_texts != VectorStore.add_texts:
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ texts = [doc.page_content for doc in documents]
+ metadatas = [doc.metadata for doc in documents]
+ return self.add_texts(texts, metadatas, **kwargs)
+ msg = (
+ f"`add_documents` and `add_texts` has not been implemented "
+ f"for {self.__class__.__name__} "
+ )
+ raise NotImplementedError(msg)
+
+ async def aadd_documents(
+ self, documents: list[Document], **kwargs: Any
+ ) -> list[str]:
+ """Async run more documents through the embeddings and add to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ # If the async method has been overridden, we'll use that.
+ if type(self).aadd_texts != VectorStore.aadd_texts:
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ texts = [doc.page_content for doc in documents]
+ metadatas = [doc.metadata for doc in documents]
+ return await self.aadd_texts(texts, metadatas, **kwargs)
+
+ return await run_in_executor(None, self.add_documents, documents, **kwargs)
+
+ def search(self, query: str, search_type: str, **kwargs: Any) -> list[Document]:
+ """Return docs most similar to query using a specified search type.
+
+ Args:
+ query: Input text.
+ search_type: Type of search to perform.
+
+ Can be `'similarity'`, `'mmr'`, or `'similarity_score_threshold'`.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+
+ Raises:
+ ValueError: If `search_type` is not one of `'similarity'`,
+ `'mmr'`, or `'similarity_score_threshold'`.
+ """
+ if search_type == "similarity":
+ return self.similarity_search(query, **kwargs)
+ if search_type == "similarity_score_threshold":
+ docs_and_similarities = self.similarity_search_with_relevance_scores(
+ query, **kwargs
+ )
+ return [doc for doc, _ in docs_and_similarities]
+ if search_type == "mmr":
+ return self.max_marginal_relevance_search(query, **kwargs)
+ msg = (
+ f"search_type of {search_type} not allowed. Expected "
+ "search_type to be 'similarity', 'similarity_score_threshold'"
+ " or 'mmr'."
+ )
+ raise ValueError(msg)
+
+ async def asearch(
+ self, query: str, search_type: str, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to query using a specified search type.
+
+ Args:
+ query: Input text.
+ search_type: Type of search to perform.
+
+ Can be `'similarity'`, `'mmr'`, or `'similarity_score_threshold'`.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+
+ Raises:
+ ValueError: If `search_type` is not one of `'similarity'`,
+ `'mmr'`, or `'similarity_score_threshold'`.
+ """
+ if search_type == "similarity":
+ return await self.asimilarity_search(query, **kwargs)
+ if search_type == "similarity_score_threshold":
+ docs_and_similarities = await self.asimilarity_search_with_relevance_scores(
+ query, **kwargs
+ )
+ return [doc for doc, _ in docs_and_similarities]
+ if search_type == "mmr":
+ return await self.amax_marginal_relevance_search(query, **kwargs)
+ msg = (
+ f"search_type of {search_type} not allowed. Expected "
+ "search_type to be 'similarity', 'similarity_score_threshold' or 'mmr'."
+ )
+ raise ValueError(msg)
+
+ @abstractmethod
+ def similarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Return docs most similar to query.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+ """
+
+ @staticmethod
+ def _euclidean_relevance_score_fn(distance: float) -> float:
+ """Return a similarity score on a scale [0, 1]."""
+ # The 'correct' relevance function
+ # may differ depending on a few things, including:
+ # - the distance / similarity metric used by the VectorStore
+ # - the scale of your embeddings (OpenAI's are unit normed. Many
+ # others are not!)
+ # - embedding dimensionality
+ # - etc.
+ # This function converts the Euclidean norm of normalized embeddings
+ # (0 is most similar, sqrt(2) most dissimilar)
+ # to a similarity function (0 to 1)
+ return 1.0 - distance / math.sqrt(2)
+
+ @staticmethod
+ def _cosine_relevance_score_fn(distance: float) -> float:
+ """Normalize the distance to a score on a scale [0, 1]."""
+ return 1.0 - distance
+
+ @staticmethod
+ def _max_inner_product_relevance_score_fn(distance: float) -> float:
+ """Normalize the distance to a score on a scale [0, 1]."""
+ if distance > 0:
+ return 1.0 - distance
+
+ return -1.0 * distance
+
+ def _select_relevance_score_fn(self) -> Callable[[float], float]:
+ """The 'correct' relevance function.
+
+ May differ depending on a few things, including:
+
+ - The distance / similarity metric used by the VectorStore
+ - The scale of your embeddings (OpenAI's are unit normed. Many others are not!)
+ - Embedding dimensionality
+ - etc.
+
+ Vectorstores should define their own selection-based method of relevance.
+ """
+ raise NotImplementedError
+
+ def similarity_search_with_score(
+ self, *args: Any, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ """Run similarity search with distance.
+
+ Args:
+ *args: Arguments to pass to the search method.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ raise NotImplementedError
+
+ async def asimilarity_search_with_score(
+ self, *args: Any, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ """Async run similarity search with distance.
+
+ Args:
+ *args: Arguments to pass to the search method.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None, self.similarity_search_with_score, *args, **kwargs
+ )
+
+ def _similarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
+ Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ relevance_score_fn = self._select_relevance_score_fn()
+ docs_and_scores = self.similarity_search_with_score(query, k, **kwargs)
+ return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]
+
+ async def _asimilarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
+ Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ relevance_score_fn = self._select_relevance_score_fn()
+ docs_and_scores = await self.asimilarity_search_with_score(query, k, **kwargs)
+ return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]
+
+ def similarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ score_threshold = kwargs.pop("score_threshold", None)
+
+ docs_and_similarities = self._similarity_search_with_relevance_scores(
+ query, k=k, **kwargs
+ )
+ if any(
+ similarity < 0.0 or similarity > 1.0
+ for _, similarity in docs_and_similarities
+ ):
+ warnings.warn(
+ "Relevance scores must be between"
+ f" 0 and 1, got {docs_and_similarities}",
+ stacklevel=2,
+ )
+
+ if score_threshold is not None:
+ docs_and_similarities = [
+ (doc, similarity)
+ for doc, similarity in docs_and_similarities
+ if similarity >= score_threshold
+ ]
+ if len(docs_and_similarities) == 0:
+ logger.warning(
+ "No relevant docs were retrieved using the "
+ "relevance score threshold %s",
+ score_threshold,
+ )
+ return docs_and_similarities
+
+ async def asimilarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Async return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ score_threshold = kwargs.pop("score_threshold", None)
+
+ docs_and_similarities = await self._asimilarity_search_with_relevance_scores(
+ query, k=k, **kwargs
+ )
+ if any(
+ similarity < 0.0 or similarity > 1.0
+ for _, similarity in docs_and_similarities
+ ):
+ warnings.warn(
+ "Relevance scores must be between"
+ f" 0 and 1, got {docs_and_similarities}",
+ stacklevel=2,
+ )
+
+ if score_threshold is not None:
+ docs_and_similarities = [
+ (doc, similarity)
+ for doc, similarity in docs_and_similarities
+ if similarity >= score_threshold
+ ]
+ if len(docs_and_similarities) == 0:
+ logger.warning(
+ "No relevant docs were retrieved using the "
+ "relevance score threshold %s",
+ score_threshold,
+ )
+ return docs_and_similarities
+
+ async def asimilarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to query.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(None, self.similarity_search, query, k=k, **kwargs)
+
+ def similarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Return docs most similar to embedding vector.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query vector.
+ """
+ raise NotImplementedError
+
+ async def asimilarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to embedding vector.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query vector.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None, self.similarity_search_by_vector, embedding, k=k, **kwargs
+ )
+
+ def max_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ query: Text to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ raise NotImplementedError
+
+ async def amax_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Async return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ query: Text to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None,
+ self.max_marginal_relevance_search,
+ query,
+ k=k,
+ fetch_k=fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ def max_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ raise NotImplementedError
+
+ async def amax_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Async return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ return await run_in_executor(
+ None,
+ self.max_marginal_relevance_search_by_vector,
+ embedding,
+ k=k,
+ fetch_k=fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @classmethod
+ def from_documents(
+ cls,
+ documents: list[Document],
+ embedding: Embeddings,
+ **kwargs: Any,
+ ) -> Self:
+ """Return `VectorStore` initialized from documents and embeddings.
+
+ Args:
+ documents: List of `Document` objects to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from documents and embeddings.
+ """
+ texts = [d.page_content for d in documents]
+ metadatas = [d.metadata for d in documents]
+
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
+
+ @classmethod
+ async def afrom_documents(
+ cls,
+ documents: list[Document],
+ embedding: Embeddings,
+ **kwargs: Any,
+ ) -> Self:
+ """Async return `VectorStore` initialized from documents and embeddings.
+
+ Args:
+ documents: List of `Document` objects to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from documents and embeddings.
+ """
+ texts = [d.page_content for d in documents]
+ metadatas = [d.metadata for d in documents]
+
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ return await cls.afrom_texts(texts, embedding, metadatas=metadatas, **kwargs)
+
+ @classmethod
+ @abstractmethod
+ def from_texts(
+ cls: type[VST],
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> VST:
+ """Return `VectorStore` initialized from texts and embeddings.
+
+ Args:
+ texts: Texts to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from texts and embeddings.
+ """
+
+ @classmethod
+ async def afrom_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Async return `VectorStore` initialized from texts and embeddings.
+
+ Args:
+ texts: Texts to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from texts and embeddings.
+ """
+ if ids is not None:
+ kwargs["ids"] = ids
+ return await run_in_executor(
+ None, cls.from_texts, texts, embedding, metadatas, **kwargs
+ )
+
+ def _get_retriever_tags(self) -> list[str]:
+ """Get tags for retriever."""
+ tags = [self.__class__.__name__]
+ if self.embeddings:
+ tags.append(self.embeddings.__class__.__name__)
+ return tags
+
+ def as_retriever(self, **kwargs: Any) -> VectorStoreRetriever:
+ """Return `VectorStoreRetriever` initialized from this `VectorStore`.
+
+ Args:
+ **kwargs: Keyword arguments to pass to the search function.
+
+ Can include:
+
+ * `search_type`: Defines the type of search that the Retriever should
+ perform. Can be `'similarity'` (default), `'mmr'`, or
+ `'similarity_score_threshold'`.
+ * `search_kwargs`: Keyword arguments to pass to the search function.
+
+ Can include things like:
+
+ * `k`: Amount of documents to return (Default: `4`)
+ * `score_threshold`: Minimum relevance threshold
+ for `similarity_score_threshold`
+ * `fetch_k`: Amount of documents to pass to MMR algorithm
+ (Default: `20`)
+ * `lambda_mult`: Diversity of results returned by MMR;
+ `1` for minimum diversity and 0 for maximum. (Default: `0.5`)
+ * `filter`: Filter by document metadata
+
+ Returns:
+ Retriever class for `VectorStore`.
+
+ Examples:
+ ```python
+ # Retrieve more documents with higher diversity
+ # Useful if your dataset has many similar documents
+ docsearch.as_retriever(
+ search_type="mmr", search_kwargs={"k": 6, "lambda_mult": 0.25}
+ )
+
+ # Fetch more documents for the MMR algorithm to consider
+ # But only return the top 5
+ docsearch.as_retriever(search_type="mmr", search_kwargs={"k": 5, "fetch_k": 50})
+
+ # Only retrieve documents that have a relevance score
+ # Above a certain threshold
+ docsearch.as_retriever(
+ search_type="similarity_score_threshold",
+ search_kwargs={"score_threshold": 0.8},
+ )
+
+ # Only get the single most similar document from the dataset
+ docsearch.as_retriever(search_kwargs={"k": 1})
+
+ # Use a filter to only retrieve documents from a specific paper
+ docsearch.as_retriever(
+ search_kwargs={"filter": {"paper_title": "GPT-4 Technical Report"}}
+ )
+ ```
+ """
+ tags = kwargs.pop("tags", None) or [*self._get_retriever_tags()]
+ return VectorStoreRetriever(vectorstore=self, tags=tags, **kwargs)
+
+
+class VectorStoreRetriever(BaseRetriever):
+ """Base Retriever class for VectorStore."""
+
+ vectorstore: VectorStore
+ """VectorStore to use for retrieval."""
+
+ search_type: str = "similarity"
+ """Type of search to perform."""
+
+ search_kwargs: dict = Field(default_factory=dict)
+ """Keyword arguments to pass to the search function."""
+
+ allowed_search_types: ClassVar[Collection[str]] = (
+ "similarity",
+ "similarity_score_threshold",
+ "mmr",
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_search_type(cls, values: dict) -> Any:
+ """Validate search type.
+
+ Args:
+ values: Values to validate.
+
+ Returns:
+ Validated values.
+
+ Raises:
+ ValueError: If `search_type` is not one of the allowed search types.
+ ValueError: If `score_threshold` is not specified with a float value(`0~1`)
+ """
+ search_type = values.get("search_type", "similarity")
+ if search_type not in cls.allowed_search_types:
+ msg = (
+ f"search_type of {search_type} not allowed. Valid values are: "
+ f"{cls.allowed_search_types}"
+ )
+ raise ValueError(msg)
+ if search_type == "similarity_score_threshold":
+ score_threshold = values.get("search_kwargs", {}).get("score_threshold")
+ if (score_threshold is None) or (not isinstance(score_threshold, float)):
+ msg = (
+ "`score_threshold` is not specified with a float value(0~1) "
+ "in `search_kwargs`."
+ )
+ raise ValueError(msg)
+ return values
+
+ def _get_ls_params(self, **kwargs: Any) -> LangSmithRetrieverParams:
+ """Get standard params for tracing."""
+ kwargs_ = self.search_kwargs | kwargs
+
+ ls_params = super()._get_ls_params(**kwargs_)
+
+ ls_params["ls_vector_store_provider"] = self.vectorstore.__class__.__name__
+
+ if self.vectorstore.embeddings:
+ ls_params["ls_embedding_provider"] = (
+ self.vectorstore.embeddings.__class__.__name__
+ )
+ elif hasattr(self.vectorstore, "embedding") and isinstance(
+ self.vectorstore.embedding, Embeddings
+ ):
+ ls_params["ls_embedding_provider"] = (
+ self.vectorstore.embedding.__class__.__name__
+ )
+
+ return ls_params
+
+ @override
+ def _get_relevant_documents(
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any
+ ) -> list[Document]:
+ kwargs_ = self.search_kwargs | kwargs
+ if self.search_type == "similarity":
+ docs = self.vectorstore.similarity_search(query, **kwargs_)
+ elif self.search_type == "similarity_score_threshold":
+ docs_and_similarities = (
+ self.vectorstore.similarity_search_with_relevance_scores(
+ query, **kwargs_
+ )
+ )
+ docs = [doc for doc, _ in docs_and_similarities]
+ elif self.search_type == "mmr":
+ docs = self.vectorstore.max_marginal_relevance_search(query, **kwargs_)
+ else:
+ msg = f"search_type of {self.search_type} not allowed."
+ raise ValueError(msg)
+ return docs
+
+ @override
+ async def _aget_relevant_documents(
+ self,
+ query: str,
+ *,
+ run_manager: AsyncCallbackManagerForRetrieverRun,
+ **kwargs: Any,
+ ) -> list[Document]:
+ kwargs_ = self.search_kwargs | kwargs
+ if self.search_type == "similarity":
+ docs = await self.vectorstore.asimilarity_search(query, **kwargs_)
+ elif self.search_type == "similarity_score_threshold":
+ docs_and_similarities = (
+ await self.vectorstore.asimilarity_search_with_relevance_scores(
+ query, **kwargs_
+ )
+ )
+ docs = [doc for doc, _ in docs_and_similarities]
+ elif self.search_type == "mmr":
+ docs = await self.vectorstore.amax_marginal_relevance_search(
+ query, **kwargs_
+ )
+ else:
+ msg = f"search_type of {self.search_type} not allowed."
+ raise ValueError(msg)
+ return docs
+
+ def add_documents(self, documents: list[Document], **kwargs: Any) -> list[str]:
+ """Add documents to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ return self.vectorstore.add_documents(documents, **kwargs)
+
+ async def aadd_documents(
+ self, documents: list[Document], **kwargs: Any
+ ) -> list[str]:
+ """Async add documents to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ return await self.vectorstore.aadd_documents(documents, **kwargs)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/in_memory.py b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef3c78ab603f6c00c2a6107f89e55487a6f626c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/in_memory.py
@@ -0,0 +1,546 @@
+"""In-memory vector store."""
+
+from __future__ import annotations
+
+import json
+import uuid
+from pathlib import Path
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.documents import Document
+from langchain_core.load import dumpd, load
+from langchain_core.vectorstores import VectorStore
+from langchain_core.vectorstores.utils import _cosine_similarity as cosine_similarity
+from langchain_core.vectorstores.utils import maximal_marginal_relevance
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Iterator, Sequence
+
+ from langchain_core.embeddings import Embeddings
+
+try:
+ import numpy as np
+
+ _HAS_NUMPY = True
+except ImportError:
+ _HAS_NUMPY = False
+
+
+class InMemoryVectorStore(VectorStore):
+ """In-memory vector store implementation.
+
+ Uses a dictionary, and computes cosine similarity for search using numpy.
+
+ Setup:
+ Install `langchain-core`.
+
+ ```bash
+ pip install -U langchain-core
+ ```
+
+ Key init args — indexing params:
+
+ * embedding_function: Embeddings
+ Embedding function to use.
+
+ Instantiate:
+ ```python
+ from langchain_core.vectorstores import InMemoryVectorStore
+ from langchain_openai import OpenAIEmbeddings
+
+ vector_store = InMemoryVectorStore(OpenAIEmbeddings())
+ ```
+
+ Add Documents:
+ ```python
+ from langchain_core.documents import Document
+
+ document_1 = Document(id="1", page_content="foo", metadata={"baz": "bar"})
+ document_2 = Document(id="2", page_content="thud", metadata={"bar": "baz"})
+ document_3 = Document(id="3", page_content="i will be deleted :(")
+
+ documents = [document_1, document_2, document_3]
+ vector_store.add_documents(documents=documents)
+ ```
+
+ Inspect documents:
+ ```python
+ top_n = 10
+ for index, (id, doc) in enumerate(vector_store.store.items()):
+ if index < top_n:
+ # docs have keys 'id', 'vector', 'text', 'metadata'
+ print(f"{id}: {doc['text']}")
+ else:
+ break
+ ```
+
+ Delete Documents:
+ ```python
+ vector_store.delete(ids=["3"])
+ ```
+
+ Search:
+ ```python
+ results = vector_store.similarity_search(query="thud", k=1)
+ for doc in results:
+ print(f"* {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * thud [{'bar': 'baz'}]
+ ```
+
+ Search with filter:
+ ```python
+ def _filter_function(doc: Document) -> bool:
+ return doc.metadata.get("bar") == "baz"
+
+
+ results = vector_store.similarity_search(
+ query="thud", k=1, filter=_filter_function
+ )
+ for doc in results:
+ print(f"* {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * thud [{'bar': 'baz'}]
+ ```
+
+ Search with score:
+ ```python
+ results = vector_store.similarity_search_with_score(query="qux", k=1)
+ for doc, score in results:
+ print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * [SIM=0.832268] foo [{'baz': 'bar'}]
+ ```
+
+ Async:
+ ```python
+ # add documents
+ # await vector_store.aadd_documents(documents=documents)
+
+ # delete documents
+ # await vector_store.adelete(ids=["3"])
+
+ # search
+ # results = vector_store.asimilarity_search(query="thud", k=1)
+
+ # search with score
+ results = await vector_store.asimilarity_search_with_score(query="qux", k=1)
+ for doc, score in results:
+ print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * [SIM=0.832268] foo [{'baz': 'bar'}]
+ ```
+
+ Use as Retriever:
+ ```python
+ retriever = vector_store.as_retriever(
+ search_type="mmr",
+ search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
+ )
+ retriever.invoke("thud")
+ ```
+
+ ```txt
+ [Document(id='2', metadata={'bar': 'baz'}, page_content='thud')]
+ ```
+ """
+
+ def __init__(self, embedding: Embeddings) -> None:
+ """Initialize with the given embedding function.
+
+ Args:
+ embedding: embedding function to use.
+ """
+ # TODO: would be nice to change to
+ # dict[str, Document] at some point (will be a breaking change)
+ self.store: dict[str, dict[str, Any]] = {}
+ self.embedding = embedding
+
+ @property
+ @override
+ def embeddings(self) -> Embeddings:
+ return self.embedding
+
+ @override
+ def delete(self, ids: Sequence[str] | None = None, **kwargs: Any) -> None:
+ if ids:
+ for id_ in ids:
+ self.store.pop(id_, None)
+
+ @override
+ async def adelete(self, ids: Sequence[str] | None = None, **kwargs: Any) -> None:
+ self.delete(ids)
+
+ @override
+ def add_documents(
+ self,
+ documents: list[Document],
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ texts = [doc.page_content for doc in documents]
+ vectors = self.embedding.embed_documents(texts)
+
+ if ids and len(ids) != len(texts):
+ msg = (
+ f"ids must be the same length as texts. "
+ f"Got {len(ids)} ids and {len(texts)} texts."
+ )
+ raise ValueError(msg)
+
+ id_iterator: Iterator[str | None] = (
+ iter(ids) if ids else iter(doc.id for doc in documents)
+ )
+
+ ids_ = []
+
+ for doc, vector in zip(documents, vectors, strict=False):
+ doc_id = next(id_iterator)
+ doc_id_ = doc_id or str(uuid.uuid4())
+ ids_.append(doc_id_)
+ self.store[doc_id_] = {
+ "id": doc_id_,
+ "vector": vector,
+ "text": doc.page_content,
+ "metadata": doc.metadata,
+ }
+
+ return ids_
+
+ @override
+ async def aadd_documents(
+ self, documents: list[Document], ids: list[str] | None = None, **kwargs: Any
+ ) -> list[str]:
+ texts = [doc.page_content for doc in documents]
+ vectors = await self.embedding.aembed_documents(texts)
+
+ if ids and len(ids) != len(texts):
+ msg = (
+ f"ids must be the same length as texts. "
+ f"Got {len(ids)} ids and {len(texts)} texts."
+ )
+ raise ValueError(msg)
+
+ id_iterator: Iterator[str | None] = (
+ iter(ids) if ids else iter(doc.id for doc in documents)
+ )
+ ids_: list[str] = []
+
+ for doc, vector in zip(documents, vectors, strict=False):
+ doc_id = next(id_iterator)
+ doc_id_ = doc_id or str(uuid.uuid4())
+ ids_.append(doc_id_)
+ self.store[doc_id_] = {
+ "id": doc_id_,
+ "vector": vector,
+ "text": doc.page_content,
+ "metadata": doc.metadata,
+ }
+
+ return ids_
+
+ @override
+ def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Get documents by their ids.
+
+ Args:
+ ids: The IDs of the documents to get.
+
+ Returns:
+ A list of `Document` objects.
+ """
+ documents = []
+
+ for doc_id in ids:
+ doc = self.store.get(doc_id)
+ if doc:
+ documents.append(
+ Document(
+ id=doc["id"],
+ page_content=doc["text"],
+ metadata=doc["metadata"],
+ )
+ )
+ return documents
+
+ @override
+ async def aget_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Async get documents by their ids.
+
+ Args:
+ ids: The IDs of the documents to get.
+
+ Returns:
+ A list of `Document` objects.
+ """
+ return self.get_by_ids(ids)
+
+ def _similarity_search_with_score_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ filter: Callable[[Document], bool] | None = None, # noqa: A002
+ ) -> list[tuple[Document, float, list[float]]]:
+ # Get all docs with fixed order in list
+ docs = list(self.store.values())
+
+ if filter is not None:
+ docs = [
+ doc
+ for doc in docs
+ if filter(
+ Document(
+ id=doc["id"], page_content=doc["text"], metadata=doc["metadata"]
+ )
+ )
+ ]
+
+ if not docs:
+ return []
+
+ similarity = cosine_similarity([embedding], [doc["vector"] for doc in docs])[0]
+
+ # Get the indices ordered by similarity score
+ top_k_idx = similarity.argsort()[::-1][:k]
+
+ return [
+ (
+ Document(
+ id=doc_dict["id"],
+ page_content=doc_dict["text"],
+ metadata=doc_dict["metadata"],
+ ),
+ float(similarity[idx].item()),
+ doc_dict["vector"],
+ )
+ for idx in top_k_idx
+ # Assign using walrus operator to avoid multiple lookups
+ if (doc_dict := docs[idx])
+ ]
+
+ def similarity_search_with_score_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ filter: Callable[[Document], bool] | None = None, # noqa: A002
+ **_kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Search for the most similar documents to the given embedding.
+
+ Args:
+ embedding: The embedding to search for.
+ k: The number of documents to return.
+ filter: A function to filter the documents.
+
+ Returns:
+ A list of tuples of `Document` objects and their similarity scores.
+ """
+ return [
+ (doc, similarity)
+ for doc, similarity, _ in self._similarity_search_with_score_by_vector(
+ embedding=embedding, k=k, filter=filter
+ )
+ ]
+
+ @override
+ def similarity_search_with_score(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ embedding = self.embedding.embed_query(query)
+ return self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+
+ @override
+ async def asimilarity_search_with_score(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ embedding = await self.embedding.aembed_query(query)
+ return self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+
+ @override
+ def similarity_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[Document]:
+ docs_and_scores = self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+ return [doc for doc, _ in docs_and_scores]
+
+ @override
+ async def asimilarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return self.similarity_search_by_vector(embedding, k, **kwargs)
+
+ @override
+ def similarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return [doc for doc, _ in self.similarity_search_with_score(query, k, **kwargs)]
+
+ @override
+ async def asimilarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return [
+ doc
+ for doc, _ in await self.asimilarity_search_with_score(query, k, **kwargs)
+ ]
+
+ @override
+ def max_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ *,
+ filter: Callable[[Document], bool] | None = None,
+ **kwargs: Any,
+ ) -> list[Document]:
+ prefetch_hits = self._similarity_search_with_score_by_vector(
+ embedding=embedding,
+ k=fetch_k,
+ filter=filter,
+ )
+
+ if not _HAS_NUMPY:
+ msg = (
+ "numpy must be installed to use max_marginal_relevance_search "
+ "pip install numpy"
+ )
+ raise ImportError(msg)
+
+ mmr_chosen_indices = maximal_marginal_relevance(
+ np.array(embedding, dtype=np.float32),
+ [vector for _, _, vector in prefetch_hits],
+ k=k,
+ lambda_mult=lambda_mult,
+ )
+ return [prefetch_hits[idx][0] for idx in mmr_chosen_indices]
+
+ @override
+ def max_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ embedding_vector = self.embedding.embed_query(query)
+ return self.max_marginal_relevance_search_by_vector(
+ embedding_vector,
+ k,
+ fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @override
+ async def amax_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ embedding_vector = await self.embedding.aembed_query(query)
+ return self.max_marginal_relevance_search_by_vector(
+ embedding_vector,
+ k,
+ fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @classmethod
+ @override
+ def from_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> InMemoryVectorStore:
+ store = cls(
+ embedding=embedding,
+ )
+ store.add_texts(texts=texts, metadatas=metadatas, **kwargs)
+ return store
+
+ @classmethod
+ @override
+ async def afrom_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> InMemoryVectorStore:
+ store = cls(
+ embedding=embedding,
+ )
+ await store.aadd_texts(texts=texts, metadatas=metadatas, **kwargs)
+ return store
+
+ @classmethod
+ def load(
+ cls, path: str, embedding: Embeddings, **kwargs: Any
+ ) -> InMemoryVectorStore:
+ """Load a vector store from a file.
+
+ Args:
+ path: The path to load the vector store from.
+ embedding: The embedding to use.
+ **kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ A `VectorStore` object.
+ """
+ path_: Path = Path(path)
+ with path_.open("r", encoding="utf-8") as f:
+ store = load(json.load(f), allowed_objects=[Document])
+ vectorstore = cls(embedding=embedding, **kwargs)
+ vectorstore.store = store
+ return vectorstore
+
+ def dump(self, path: str) -> None:
+ """Dump the vector store to a file.
+
+ Args:
+ path: The path to dump the vector store to.
+ """
+ path_: Path = Path(path)
+ path_.parent.mkdir(exist_ok=True, parents=True)
+ with path_.open("w", encoding="utf-8") as f:
+ json.dump(dumpd(self.store), f, indent=2)
diff --git a/python/user_packages/Python313/site-packages/langchain_core/vectorstores/utils.py b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..551524beb3bfbcfcf0cd7c7154100926d802ac29
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_core/vectorstores/utils.py
@@ -0,0 +1,157 @@
+"""Internal utilities for the in memory implementation of `VectorStore`.
+
+!!! warning
+
+ These are part of a private API, and users should not use them directly as they can
+ change without notice.
+"""
+
+from __future__ import annotations
+
+import logging
+import warnings
+from typing import TYPE_CHECKING, cast
+
+try:
+ import numpy as np
+
+ _HAS_NUMPY = True
+except ImportError:
+ _HAS_NUMPY = False
+
+try:
+ import simsimd as simd # type: ignore[import-not-found]
+
+ _HAS_SIMSIMD = True
+except ImportError:
+ _HAS_SIMSIMD = False
+
+if TYPE_CHECKING:
+ Matrix = list[list[float]] | list[np.ndarray] | np.ndarray
+
+logger = logging.getLogger(__name__)
+
+
+def _cosine_similarity(x: Matrix, y: Matrix) -> np.ndarray:
+ """Row-wise cosine similarity between two equal-width matrices.
+
+ Args:
+ x: A matrix of shape `(n, m)`.
+ y: A matrix of shape `(k, m)`.
+
+ Returns:
+ A matrix of shape `(n, k)` where each element `(i, j)` is the cosine similarity
+ between the `i`th row of `x` and the `j`th row of `y`.
+
+ Raises:
+ ValueError: If the number of columns in `x` and `y` are not the same.
+ ImportError: If numpy is not installed.
+ """
+ if not _HAS_NUMPY:
+ msg = (
+ "cosine_similarity requires numpy to be installed. "
+ "Please install numpy with `pip install numpy`."
+ )
+ raise ImportError(msg)
+
+ if len(x) == 0 or len(y) == 0:
+ return np.array([[]])
+
+ x = np.array(x)
+ y = np.array(y)
+
+ # Check for NaN
+ if np.any(np.isnan(x)) or np.any(np.isnan(y)):
+ warnings.warn(
+ "NaN found in input arrays, unexpected return might follow",
+ category=RuntimeWarning,
+ stacklevel=2,
+ )
+
+ # Check for Inf
+ if np.any(np.isinf(x)) or np.any(np.isinf(y)):
+ warnings.warn(
+ "Inf found in input arrays, unexpected return might follow",
+ category=RuntimeWarning,
+ stacklevel=2,
+ )
+
+ if x.shape[1] != y.shape[1]:
+ msg = (
+ f"Number of columns in X and Y must be the same. X has shape {x.shape} "
+ f"and Y has shape {y.shape}."
+ )
+ raise ValueError(msg)
+ if not _HAS_SIMSIMD:
+ logger.debug(
+ "Unable to import simsimd, defaulting to NumPy implementation. If you want "
+ "to use simsimd please install with `pip install simsimd`."
+ )
+ x_norm = np.linalg.norm(x, axis=1)
+ y_norm = np.linalg.norm(y, axis=1)
+ # Ignore divide by zero errors run time warnings as those are handled below.
+ with np.errstate(divide="ignore", invalid="ignore"):
+ similarity = np.dot(x, y.T) / np.outer(x_norm, y_norm)
+ if np.isnan(similarity).all():
+ msg = "NaN values found, please remove the NaN values and try again"
+ raise ValueError(msg) from None
+ similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
+ return cast("np.ndarray", similarity)
+
+ x = np.array(x, dtype=np.float32)
+ y = np.array(y, dtype=np.float32)
+ return 1 - np.array(simd.cdist(x, y, metric="cosine"))
+
+
+def maximal_marginal_relevance(
+ query_embedding: np.ndarray,
+ embedding_list: list,
+ lambda_mult: float = 0.5,
+ k: int = 4,
+) -> list[int]:
+ """Calculate maximal marginal relevance.
+
+ Args:
+ query_embedding: The query embedding.
+ embedding_list: A list of embeddings.
+ lambda_mult: The lambda parameter for MMR.
+ k: The number of embeddings to return.
+
+ Returns:
+ A list of indices of the embeddings to return.
+
+ Raises:
+ ImportError: If numpy is not installed.
+ """
+ if not _HAS_NUMPY:
+ msg = (
+ "maximal_marginal_relevance requires numpy to be installed. "
+ "Please install numpy with `pip install numpy`."
+ )
+ raise ImportError(msg)
+
+ if min(k, len(embedding_list)) <= 0:
+ return []
+ if query_embedding.ndim == 1:
+ query_embedding = np.expand_dims(query_embedding, axis=0)
+ similarity_to_query = _cosine_similarity(query_embedding, embedding_list)[0]
+ most_similar = int(np.argmax(similarity_to_query))
+ idxs = [most_similar]
+ selected = np.array([embedding_list[most_similar]])
+ while len(idxs) < min(k, len(embedding_list)):
+ best_score = -np.inf
+ idx_to_add = -1
+ similarity_to_selected = _cosine_similarity(embedding_list, selected)
+ for i, query_score in enumerate(similarity_to_query):
+ if i in idxs:
+ continue
+ redundant_score = max(similarity_to_selected[i])
+ equation_score = (
+ lambda_mult * query_score - (1 - lambda_mult) * redundant_score
+ )
+ if equation_score > best_score:
+ best_score = equation_score
+ idx_to_add = i
+ idxs.append(idx_to_add)
+ selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
+ return idxs
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..426b65090341f37bc64935cdc681cc8a8fb02a32
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2a14c84224fc629b03e717c242f0999d140fdb3
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a01a77ac5cf6d9777be83fa7dcd7e86c439a4cdb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__init__.py
@@ -0,0 +1,8 @@
+from langchain_huggingface.chat_models.huggingface import ( # type: ignore[import-not-found]
+ TGI_MESSAGE,
+ TGI_RESPONSE,
+ ChatHuggingFace,
+ _convert_dict_to_message,
+)
+
+__all__ = ["TGI_MESSAGE", "TGI_RESPONSE", "ChatHuggingFace", "_convert_dict_to_message"]
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d26f67a2b314885cf4a4fd6da02ea8e3b7b4d812
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fb6bd89f529de597a2c45e9df0c23173bc78d5e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/huggingface.py b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..52e9df5d34340da0d1bf7485cb1664992d9a4c5b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/chat_models/huggingface.py
@@ -0,0 +1,1245 @@
+"""Hugging Face Chat Wrapper."""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from dataclasses import dataclass
+from operator import itemgetter
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+if TYPE_CHECKING:
+ from langchain_huggingface.llms.huggingface_endpoint import HuggingFaceEndpoint
+ from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import (
+ LanguageModelInput,
+ ModelProfile,
+ ModelProfileRegistry,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ InvalidToolCall,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolCall,
+ ToolMessage,
+ ToolMessageChunk,
+)
+from langchain_core.messages.tool import ToolCallChunk
+from langchain_core.messages.tool import tool_call_chunk as create_tool_call_chunk
+from langchain_core.output_parsers import JsonOutputParser
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ LLMResult,
+)
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import (
+ convert_to_json_schema,
+ convert_to_openai_tool,
+)
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import Self
+
+from langchain_huggingface.data._profiles import _PROFILES
+from langchain_huggingface.llms.huggingface_endpoint import HuggingFaceEndpoint
+from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+_MODEL_PROFILES = cast("ModelProfileRegistry", _PROFILES)
+
+
+def _get_default_model_profile(model_name: str) -> ModelProfile:
+ default = _MODEL_PROFILES.get(model_name) or {}
+ return default.copy()
+
+
+@dataclass
+class TGI_RESPONSE:
+ """Response from the TextGenInference API."""
+
+ choices: list[Any]
+ usage: dict
+
+
+@dataclass
+class TGI_MESSAGE:
+ """Message to send to the TextGenInference API."""
+
+ role: str
+ content: str
+ tool_calls: list[dict]
+
+
+def _lc_tool_call_to_hf_tool_call(tool_call: ToolCall) -> dict:
+ return {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ },
+ }
+
+
+def _lc_invalid_tool_call_to_hf_tool_call(
+ invalid_tool_call: InvalidToolCall,
+) -> dict:
+ return {
+ "type": "function",
+ "id": invalid_tool_call["id"],
+ "function": {
+ "name": invalid_tool_call["name"],
+ "arguments": invalid_tool_call["args"],
+ },
+ }
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+
+ """
+ message_dict: dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ # If function call only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ if message.tool_calls or message.invalid_tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_hf_tool_call(tc) for tc in message.tool_calls
+ ] + [
+ _lc_invalid_tool_call_to_hf_tool_call(tc)
+ for tc in message.invalid_tool_calls
+ ]
+ elif "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ # If tool calls only, content is None not empty string
+ if "tool_calls" in message_dict and message_dict["content"] == "":
+ message_dict["content"] = None
+ else:
+ pass
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "content": message.content,
+ "name": message.name,
+ }
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ }
+ else:
+ msg = f"Got unknown type {message}"
+ raise TypeError(msg)
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ """Convert a dictionary to a LangChain message.
+
+ Args:
+ _dict: The dictionary.
+
+ Returns:
+ The LangChain message.
+
+ """
+ role = _dict.get("role")
+ if role == "user":
+ return HumanMessage(content=_dict.get("content", ""))
+ if role == "assistant":
+ content = _dict.get("content", "") or ""
+ additional_kwargs: dict = {}
+ if function_call := _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(function_call)
+ tool_calls = []
+ invalid_tool_calls = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
+ except Exception as e:
+ invalid_tool_calls.append(
+ dict(make_invalid_tool_call(raw_tool_call, str(e)))
+ )
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ if role == "system":
+ return SystemMessage(content=_dict.get("content", ""))
+ if role == "function":
+ return FunctionMessage(
+ content=_dict.get("content", ""), name=_dict.get("name", "")
+ )
+ if role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return ToolMessage(
+ content=_dict.get("content", ""),
+ tool_call_id=_dict.get("tool_call_id", ""),
+ additional_kwargs=additional_kwargs,
+ )
+ return ChatMessage(content=_dict.get("content", ""), role=role or "")
+
+
+def _is_huggingface_hub(llm: Any) -> bool:
+ try:
+ from langchain_community.llms.huggingface_hub import (
+ HuggingFaceHub, # type: ignore[import-not-found]
+ )
+
+ return isinstance(llm, HuggingFaceHub)
+ except ImportError:
+ # if no langchain community, it is not a HuggingFaceHub
+ return False
+
+
+def _convert_chunk_to_message_chunk(
+ chunk: Mapping[str, Any], default_class: type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ choice = chunk["choices"][0]
+ _dict = choice["delta"]
+ role = cast(str, _dict.get("role"))
+ content = cast(str, _dict.get("content") or "")
+ additional_kwargs: dict = {}
+ tool_call_chunks: list[ToolCallChunk] = []
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for rtc in raw_tool_calls:
+ with contextlib.suppress(KeyError):
+ tool_call_chunks.append(
+ create_tool_call_chunk(
+ name=rtc["function"].get("name"),
+ args=rtc["function"].get("arguments"),
+ id=rtc.get("id"),
+ index=rtc.get("index"),
+ )
+ )
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ if role == "assistant" or default_class == AIMessageChunk:
+ if usage := chunk.get("usage"):
+ input_tokens = usage.get("prompt_tokens", 0)
+ output_tokens = usage.get("completion_tokens", 0)
+ usage_metadata = {
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": usage.get("total_tokens", input_tokens + output_tokens),
+ }
+ else:
+ usage_metadata = None
+ return AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_call_chunks,
+ usage_metadata=usage_metadata, # type: ignore[arg-type]
+ )
+ if role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ if role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ if role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
+ if role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _is_huggingface_textgen_inference(llm: Any) -> bool:
+ try:
+ from langchain_community.llms.huggingface_text_gen_inference import (
+ HuggingFaceTextGenInference, # type: ignore[import-not-found]
+ )
+
+ return isinstance(llm, HuggingFaceTextGenInference)
+ except ImportError:
+ # if no langchain community, it is not a HuggingFaceTextGenInference
+ return False
+
+
+def _is_huggingface_endpoint(llm: Any) -> bool:
+ return isinstance(llm, HuggingFaceEndpoint)
+
+
+def _is_huggingface_pipeline(llm: Any) -> bool:
+ return isinstance(llm, HuggingFacePipeline)
+
+
+class ChatHuggingFace(BaseChatModel):
+ r"""Hugging Face LLM's as ChatModels.
+
+ Works with `HuggingFaceTextGenInference`, `HuggingFaceEndpoint`,
+ `HuggingFaceHub`, and `HuggingFacePipeline` LLMs.
+
+ Upon instantiating this class, the model_id is resolved from the url
+ provided to the LLM, and the appropriate tokenizer is loaded from
+ the HuggingFace Hub.
+
+ Setup:
+ Install `langchain-huggingface` and ensure your Hugging Face token
+ is saved.
+
+ ```bash
+ pip install langchain-huggingface
+ ```
+
+ ```python
+ from huggingface_hub import login
+
+ login() # You will be prompted for your HF key, which will then be saved locally
+ ```
+
+ Key init args — completion params:
+ llm:
+ LLM to be used.
+
+ Key init args — client params:
+ custom_get_token_ids:
+ Optional encoder to use for counting tokens.
+ metadata:
+ Metadata to add to the run trace.
+ tags:
+ Tags to add to the run trace.
+ verbose:
+ Whether to print out response text.
+
+ See full list of supported init args and their descriptions in the params
+ section.
+
+ Instantiate:
+ ```python
+ from langchain_huggingface import HuggingFaceEndpoint,
+ ChatHuggingFace
+
+ model = HuggingFaceEndpoint(
+ repo_id="microsoft/Phi-3-mini-4k-instruct",
+ task="text-generation",
+ max_new_tokens=512,
+ do_sample=False,
+ repetition_penalty=1.03,
+ )
+
+ chat = ChatHuggingFace(llm=model, verbose=True)
+ ```
+
+ Invoke:
+ ```python
+ messages = [
+ ("system", "You are a helpful translator. Translate the user
+ sentence to French."),
+ ("human", "I love programming."),
+ ]
+
+ chat(...).invoke(messages)
+ ```
+
+ ```python
+ AIMessage(content='Je ai une passion pour le programme.\n\nIn
+ French, we use "ai" for masculine subjects and "a" for feminine
+ subjects. Since "programming" is gender-neutral in English, we
+ will go with the masculine "programme".\n\nConfirmation: "J\'aime
+ le programme." is more commonly used. The sentence above is
+ technically accurate, but less commonly used in spoken French as
+ "ai" is used less frequently in everyday speech.',
+ response_metadata={'token_usage': ChatCompletionOutputUsage
+ (completion_tokens=100, prompt_tokens=55, total_tokens=155),
+ 'model': '', 'finish_reason': 'length'},
+ id='run-874c24b7-0272-4c99-b259-5d6d7facbc56-0')
+ ```
+
+ Stream:
+ ```python
+ for chunk in chat.stream(messages):
+ print(chunk)
+ ```
+
+ ```python
+ content='Je ai une passion pour le programme.\n\nIn French, we use
+ "ai" for masculine subjects and "a" for feminine subjects.
+ Since "programming" is gender-neutral in English,
+ we will go with the masculine "programme".\n\nConfirmation:
+ "J\'aime le programme." is more commonly used. The sentence
+ above is technically accurate, but less commonly used in spoken
+ French as "ai" is used less frequently in everyday speech.'
+ response_metadata={'token_usage': ChatCompletionOutputUsage
+ (completion_tokens=100, prompt_tokens=55, total_tokens=155),
+ 'model': '', 'finish_reason': 'length'}
+ id='run-7d7b1967-9612-4f9a-911a-b2b5ca85046a-0'
+ ```
+
+ Async:
+ ```python
+ await chat.ainvoke(messages)
+ ```
+
+ ```python
+ AIMessage(content='Je déaime le programming.\n\nLittérale : Je
+ (j\'aime) déaime (le) programming.\n\nNote: "Programming" in
+ French is "programmation". But here, I used "programming" instead
+ of "programmation" because the user said "I love programming"
+ instead of "I love programming (in French)", which would be
+ "J\'aime la programmation". By translating the sentence
+ literally, I preserved the original meaning of the user\'s
+ sentence.', id='run-fd850318-e299-4735-b4c6-3496dc930b1d-0')
+ ```
+
+ Tool calling:
+ ```python
+ from pydantic import BaseModel, Field
+
+ class GetWeather(BaseModel):
+ '''Get the current weather in a given location'''
+
+ location: str = Field(..., description="The city and state,
+ e.g. San Francisco, CA")
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(..., description="The city and state,
+ e.g. San Francisco, CA")
+
+ chat_with_tools = chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke("Which city is hotter today and
+ which is bigger: LA or NY?")
+ ai_msg.tool_calls
+ ```
+
+ ```python
+ [
+ {
+ "name": "GetPopulation",
+ "args": {"location": "Los Angeles, CA"},
+ "id": "0",
+ }
+ ]
+ ```
+
+ Response metadata
+ ```python
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+ ```
+
+ ```python
+ {
+ "token_usage": ChatCompletionOutputUsage(
+ completion_tokens=100, prompt_tokens=8, total_tokens=108
+ ),
+ "model": "",
+ "finish_reason": "length",
+ }
+ ```
+ """ # noqa: E501
+
+ llm: Any
+ """LLM, must be of type HuggingFaceTextGenInference, HuggingFaceEndpoint,
+ HuggingFaceHub, or HuggingFacePipeline."""
+ tokenizer: Any = None
+ """Tokenizer for the model. Only used for HuggingFacePipeline."""
+ model_id: str | None = None
+ """Model ID for the model. Only used for HuggingFaceEndpoint."""
+ temperature: float | None = None
+ """What sampling temperature to use."""
+ stop: str | list[str] | None = Field(default=None, alias="stop_sequences")
+ """Default stop sequences."""
+ presence_penalty: float | None = None
+ """Penalizes repeated tokens."""
+ frequency_penalty: float | None = None
+ """Penalizes repeated tokens according to frequency."""
+ seed: int | None = None
+ """Seed for generation"""
+ logprobs: bool | None = None
+ """Whether to return logprobs."""
+ top_logprobs: int | None = None
+ """Number of most likely tokens to return at each token position, each with
+ an associated log probability. `logprobs` must be set to true
+ if this parameter is used."""
+ logit_bias: dict[int, int] | None = None
+ """Modify the likelihood of specified tokens appearing in the completion."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ stream_usage: bool | None = None
+ """Whether to include usage metadata in streaming output. If True, an additional
+ message chunk will be generated during the stream including usage metadata."""
+ n: int | None = None
+ """Number of chat completions to generate for each prompt."""
+ top_p: float | None = None
+ """Total probability mass of tokens to consider at each step."""
+ max_tokens: int | None = None
+ """Maximum number of tokens to generate."""
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+
+ # Inherit properties from the LLM if they weren't explicitly set
+ self._inherit_llm_properties()
+
+ self._resolve_model_id()
+
+ def _inherit_llm_properties(self) -> None:
+ """Inherit properties from the wrapped LLM instance if not explicitly set."""
+ if not hasattr(self, "llm") or self.llm is None:
+ return
+
+ # Map of ChatHuggingFace properties to LLM properties
+ property_mappings = {
+ "temperature": "temperature",
+ "max_tokens": "max_new_tokens", # Different naming convention
+ "top_p": "top_p",
+ "seed": "seed",
+ "streaming": "streaming",
+ "stop": "stop_sequences",
+ }
+
+ # Inherit properties from LLM and not explicitly set here
+ for chat_prop, llm_prop in property_mappings.items():
+ if hasattr(self.llm, llm_prop):
+ llm_value = getattr(self.llm, llm_prop)
+ chat_value = getattr(self, chat_prop, None)
+ if not chat_value and llm_value:
+ setattr(self, chat_prop, llm_value)
+
+ # Handle special cases for HuggingFaceEndpoint
+ if _is_huggingface_endpoint(self.llm):
+ # Inherit additional HuggingFaceEndpoint specific properties
+ endpoint_mappings = {
+ "frequency_penalty": "repetition_penalty",
+ }
+
+ for chat_prop, llm_prop in endpoint_mappings.items():
+ if hasattr(self.llm, llm_prop):
+ llm_value = getattr(self.llm, llm_prop)
+ chat_value = getattr(self, chat_prop, None)
+ if chat_value is None and llm_value is not None:
+ setattr(self, chat_prop, llm_value)
+
+ # Inherit model_kwargs if not explicitly set
+ if (
+ not self.model_kwargs
+ and hasattr(self.llm, "model_kwargs")
+ and isinstance(self.llm.model_kwargs, dict)
+ ):
+ self.model_kwargs = self.llm.model_kwargs.copy()
+
+ @model_validator(mode="after")
+ def validate_llm(self) -> Self:
+ if (
+ not _is_huggingface_hub(self.llm)
+ and not _is_huggingface_textgen_inference(self.llm)
+ and not _is_huggingface_endpoint(self.llm)
+ and not _is_huggingface_pipeline(self.llm)
+ ):
+ msg = (
+ "Expected llm to be one of HuggingFaceTextGenInference, "
+ "HuggingFaceEndpoint, HuggingFaceHub, HuggingFacePipeline "
+ f"received {type(self.llm)}"
+ )
+ raise TypeError(msg)
+ return self
+
+ def _resolve_model_profile(self) -> ModelProfile | None:
+ if self.model_id:
+ return _get_default_model_profile(self.model_id) or None
+ return None
+
+ @classmethod
+ def from_model_id(
+ cls,
+ model_id: str,
+ task: str | None = None,
+ backend: Literal["pipeline", "endpoint", "text-gen"] = "pipeline",
+ **kwargs: Any,
+ ) -> ChatHuggingFace:
+ """Construct a ChatHuggingFace model from a model_id.
+
+ Args:
+ model_id: The model ID of the Hugging Face model.
+ task: The task to perform (e.g., "text-generation").
+ backend: The backend to use. One of "pipeline", "endpoint", "text-gen".
+ **kwargs: Additional arguments to pass to the backend or ChatHuggingFace.
+ """
+ llm: (
+ Any # HuggingFacePipeline, HuggingFaceEndpoint, HuggingFaceTextGenInference
+ )
+ if backend == "pipeline":
+ from langchain_huggingface.llms.huggingface_pipeline import (
+ HuggingFacePipeline,
+ )
+
+ task = task if task is not None else "text-generation"
+
+ # Separate pipeline-specific kwargs from ChatHuggingFace kwargs
+ # Parameters that should go to HuggingFacePipeline.from_model_id
+ pipeline_specific_kwargs = {}
+
+ # Extract pipeline-specific parameters
+ pipeline_keys = [
+ "backend",
+ "device",
+ "device_map",
+ "model_kwargs",
+ "pipeline_kwargs",
+ "batch_size",
+ ]
+ for key in pipeline_keys:
+ if key in kwargs:
+ pipeline_specific_kwargs[key] = kwargs.pop(key)
+
+ # Remaining kwargs (temperature, max_tokens, etc.) should go to
+ # pipeline_kwargs for generation parameters, which ChatHuggingFace
+ # will inherit from the LLM
+ if "pipeline_kwargs" not in pipeline_specific_kwargs:
+ pipeline_specific_kwargs["pipeline_kwargs"] = {}
+
+ # Add generation parameters to pipeline_kwargs
+ # Map max_tokens to max_new_tokens for HuggingFace pipeline
+ generation_params = {}
+ for k, v in list(kwargs.items()):
+ if k == "max_tokens":
+ generation_params["max_new_tokens"] = v
+ kwargs.pop(k)
+ elif k in (
+ "temperature",
+ "max_new_tokens",
+ "top_p",
+ "top_k",
+ "repetition_penalty",
+ "do_sample",
+ ):
+ generation_params[k] = v
+ kwargs.pop(k)
+
+ pipeline_specific_kwargs["pipeline_kwargs"].update(generation_params)
+
+ # Create the HuggingFacePipeline
+ llm = HuggingFacePipeline.from_model_id(
+ model_id=model_id, task=task, **pipeline_specific_kwargs
+ )
+ elif backend == "endpoint":
+ from langchain_huggingface.llms.huggingface_endpoint import (
+ HuggingFaceEndpoint,
+ )
+
+ llm = HuggingFaceEndpoint(repo_id=model_id, task=task, **kwargs)
+ elif backend == "text-gen":
+ from langchain_community.llms.huggingface_text_gen_inference import ( # type: ignore[import-not-found]
+ HuggingFaceTextGenInference,
+ )
+
+ llm = HuggingFaceTextGenInference(inference_server_url=model_id, **kwargs)
+ else:
+ msg = f"Unknown backend: {backend}"
+ raise ValueError(msg)
+
+ return cls(llm=llm, **kwargs)
+
+ def _create_chat_result(self, response: dict) -> ChatResult:
+ generations = []
+ token_usage = response.get("usage", {})
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ if token_usage and isinstance(message, AIMessage):
+ message.usage_metadata = {
+ "input_tokens": token_usage.get("prompt_tokens", 0),
+ "output_tokens": token_usage.get("completion_tokens", 0),
+ "total_tokens": token_usage.get("total_tokens", 0),
+ }
+ generation_info = {"finish_reason": res.get("finish_reason")}
+ if "logprobs" in res:
+ generation_info["logprobs"] = res["logprobs"]
+ gen = ChatGeneration(
+ message=message,
+ generation_info=generation_info,
+ )
+ generations.append(gen)
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model_id,
+ "system_fingerprint": response.get("system_fingerprint", ""),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ stream: bool | None = None, # noqa: FBT001
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+
+ if _is_huggingface_textgen_inference(self.llm):
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ answer = self.llm.client.chat(messages=message_dicts, **kwargs)
+ return self._create_chat_result(answer)
+ if _is_huggingface_endpoint(self.llm):
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ "stop": stop,
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+ answer = self.llm.client.chat_completion(messages=message_dicts, **params)
+ return self._create_chat_result(answer)
+ llm_input = self._to_chat_prompt(messages)
+
+ if should_stream:
+ stream_iter = self.llm._stream(
+ llm_input, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ llm_result = self.llm._generate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ stream: bool | None = None, # noqa: FBT001
+ **kwargs: Any,
+ ) -> ChatResult:
+ if _is_huggingface_textgen_inference(self.llm):
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ answer = await self.llm.async_client.chat(messages=message_dicts, **kwargs)
+ return self._create_chat_result(answer)
+ if _is_huggingface_endpoint(self.llm):
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+
+ answer = await self.llm.async_client.chat_completion(
+ messages=message_dicts, **params
+ )
+ return self._create_chat_result(answer)
+ if _is_huggingface_pipeline(self.llm):
+ msg = "async generation is not supported with HuggingFacePipeline"
+ raise NotImplementedError(msg)
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = await self.llm._agenerate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ def _should_stream_usage(
+ self, *, stream_usage: bool | None = None, **kwargs: Any
+ ) -> bool | None:
+ """Determine whether to include usage metadata in streaming output.
+
+ For backwards compatibility, we check for `stream_options` passed
+ explicitly to kwargs or in the model_kwargs and override self.stream_usage.
+ """
+ stream_usage_sources = [ # order of precedence
+ stream_usage,
+ kwargs.get("stream_options", {}).get("include_usage"),
+ self.model_kwargs.get("stream_options", {}).get("include_usage"),
+ self.stream_usage,
+ ]
+ for source in stream_usage_sources:
+ if isinstance(source, bool):
+ return source
+ return self.stream_usage
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ if _is_huggingface_endpoint(self.llm):
+ stream_usage = self._should_stream_usage(
+ stream_usage=stream_usage, **kwargs
+ )
+ if stream_usage:
+ kwargs["stream_options"] = {"include_usage": stream_usage}
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.llm.client.chat_completion(
+ messages=message_dicts, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ if usage := chunk.get("usage"):
+ usage_msg = AIMessageChunk(
+ content="",
+ additional_kwargs={},
+ response_metadata={},
+ usage_metadata={
+ "input_tokens": usage.get("prompt_tokens", 0),
+ "output_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ )
+ yield ChatGenerationChunk(message=usage_msg)
+ continue
+
+ choice = chunk["choices"][0]
+ message_chunk = _convert_chunk_to_message_chunk(
+ chunk, default_chunk_class
+ )
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ generation_info["model_name"] = self.model_id
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = message_chunk.__class__
+ generation_chunk = ChatGenerationChunk(
+ message=message_chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ generation_chunk.text, chunk=generation_chunk, logprobs=logprobs
+ )
+ yield generation_chunk
+ else:
+ llm_input = self._to_chat_prompt(messages)
+ stream_iter = self.llm._stream(
+ llm_input, stop=stop, run_manager=run_manager, **kwargs
+ )
+ for chunk in stream_iter: # chunk is a GenerationChunk
+ chat_chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=chunk.text),
+ generation_info=chunk.generation_info,
+ )
+ yield chat_chunk
+
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ stream_usage = self._should_stream_usage(stream_usage=stream_usage, **kwargs)
+ if stream_usage:
+ kwargs["stream_options"] = {"include_usage": stream_usage}
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: type[BaseMessageChunk] = AIMessageChunk
+
+ async for chunk in await self.llm.async_client.chat_completion(
+ messages=message_dicts, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ if usage := chunk.get("usage"):
+ usage_msg = AIMessageChunk(
+ content="",
+ additional_kwargs={},
+ response_metadata={},
+ usage_metadata={
+ "input_tokens": usage.get("prompt_tokens", 0),
+ "output_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ )
+ yield ChatGenerationChunk(message=usage_msg)
+ continue
+
+ choice = chunk["choices"][0]
+ message_chunk = _convert_chunk_to_message_chunk(chunk, default_chunk_class)
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ generation_info["model_name"] = self.model_id
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = message_chunk.__class__
+ generation_chunk = ChatGenerationChunk(
+ message=message_chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=generation_chunk.text,
+ chunk=generation_chunk,
+ logprobs=logprobs,
+ )
+ yield generation_chunk
+
+ def _to_chat_prompt(
+ self,
+ messages: list[BaseMessage],
+ ) -> str:
+ """Convert a list of messages into a prompt format expected by wrapped LLM."""
+ if not messages:
+ msg = "At least one HumanMessage must be provided!"
+ raise ValueError(msg)
+
+ if not isinstance(messages[-1], HumanMessage):
+ msg = "Last message must be a HumanMessage!"
+ raise ValueError(msg)
+
+ messages_dicts = [self._to_chatml_format(m) for m in messages]
+
+ return self.tokenizer.apply_chat_template(
+ messages_dicts, tokenize=False, add_generation_prompt=True
+ )
+
+ def _to_chatml_format(self, message: BaseMessage) -> dict:
+ """Convert LangChain message to ChatML format."""
+ if isinstance(message, SystemMessage):
+ role = "system"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ else:
+ msg = f"Unknown message type: {type(message)}"
+ raise ValueError(msg)
+
+ return {"role": role, "content": message.content}
+
+ @staticmethod
+ def _to_chat_result(llm_result: LLMResult) -> ChatResult:
+ chat_generations = []
+
+ for g in llm_result.generations[0]:
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=g.text), generation_info=g.generation_info
+ )
+ chat_generations.append(chat_generation)
+
+ return ChatResult(
+ generations=chat_generations, llm_output=llm_result.llm_output
+ )
+
+ def _resolve_model_id(self) -> None:
+ """Resolve the model_id from the LLM's inference_server_url."""
+ from huggingface_hub import list_inference_endpoints # type: ignore[import]
+
+ if _is_huggingface_hub(self.llm) or (
+ hasattr(self.llm, "repo_id") and self.llm.repo_id
+ ):
+ self.model_id = self.llm.repo_id
+ return
+ if _is_huggingface_textgen_inference(self.llm):
+ endpoint_url: str | None = self.llm.inference_server_url
+ if _is_huggingface_pipeline(self.llm):
+ from transformers import AutoTokenizer # type: ignore[import]
+
+ self.model_id = self.model_id or self.llm.model_id
+ self.tokenizer = (
+ AutoTokenizer.from_pretrained(self.model_id)
+ if self.tokenizer is None
+ else self.tokenizer
+ )
+ return
+ if _is_huggingface_endpoint(self.llm):
+ self.model_id = self.llm.repo_id or self.llm.model
+ return
+ endpoint_url = self.llm.endpoint_url
+ available_endpoints = list_inference_endpoints("*")
+ for endpoint in available_endpoints:
+ if endpoint.url == endpoint_url:
+ self.model_id = endpoint.repository
+
+ if not self.model_id:
+ msg = (
+ "Failed to resolve model_id:"
+ f"Could not find model id for inference server: {endpoint_url}"
+ "Make sure that your Hugging Face token has access to the endpoint."
+ )
+ raise ValueError(msg)
+
+ def bind_tools(
+ self,
+ tools: Sequence[dict[str, Any] | type | Callable | BaseTool],
+ *,
+ tool_choice: dict | str | bool | None = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+
+ Supports any tool definition handled by [`convert_to_openai_tool`][langchain_core.utils.function_calling.convert_to_openai_tool].
+ tool_choice: Which tool to require the model to call.
+ Must be the name of the single provided function or
+ `'auto'` to automatically determine which function to call
+ (if any), or a dict of the form:
+ {"type": "function", "function": {"name": <>}}.
+ **kwargs: Any additional parameters to pass to the
+ `langchain.runnable.Runnable` constructor.
+ """ # noqa: E501
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ if tool_choice is not None and tool_choice:
+ if len(formatted_tools) != 1:
+ msg = (
+ "When specifying `tool_choice`, you must provide exactly one "
+ f"tool. Received {len(formatted_tools)} tools."
+ )
+ raise ValueError(msg)
+ if isinstance(tool_choice, str):
+ if tool_choice not in ("auto", "none", "required"):
+ tool_choice = {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ elif isinstance(tool_choice, bool):
+ tool_choice = formatted_tools[0]
+ elif isinstance(tool_choice, dict):
+ if (
+ formatted_tools[0]["function"]["name"]
+ != tool_choice["function"]["name"]
+ ):
+ msg = (
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tool was {formatted_tools[0]['function']['name']}."
+ )
+ raise ValueError(msg)
+ else:
+ msg = (
+ f"Unrecognized tool_choice type. Expected str, bool or dict. "
+ f"Received: {tool_choice}"
+ )
+ raise ValueError(msg)
+ kwargs["tool_choice"] = tool_choice
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: dict | type[BaseModel] | None = None,
+ *,
+ method: Literal[
+ "function_calling", "json_mode", "json_schema"
+ ] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, dict | BaseModel]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema. Can be passed in as:
+
+ - An OpenAI function/tool schema,
+ - A JSON Schema,
+ - A `TypedDict` class
+
+ Pydantic class is currently supported.
+
+ method: The method for steering model generation, one of:
+
+ - `'function_calling'`: uses tool-calling features.
+ - `'json_schema'`: uses dedicated structured output features.
+ - `'json_mode'`: uses JSON mode.
+
+ include_raw:
+ If `False` then only the parsed structured output is returned.
+
+ If an error occurs during model output parsing it will be raised.
+
+ If `True` then both the raw model response (a `BaseMessage`) and the
+ parsed model response will be returned.
+
+ If an error occurs during output parsing it will be caught and returned
+ as well.
+
+ The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
+ `'parsing_error'`.
+
+ kwargs:
+ Additional parameters to pass to the underlying LLM's
+ `langchain_core.language_models.chat.BaseChatModel.bind`
+ method, such as `response_format` or `ls_structured_output_format`.
+
+ Returns:
+ A `Runnable` that takes same inputs as a
+ `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
+ `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
+ of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
+ `False` then `Runnable` outputs a `dict`.
+
+ If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:
+
+ - `'raw'`: `BaseMessage`
+ - `'parsed'`: `None` if there was a parsing error, otherwise the type
+ depends on the `schema` as described above.
+ - `'parsing_error'`: `BaseException | None`
+ """
+ _ = kwargs.pop("strict", None)
+ if kwargs:
+ msg = f"Received unsupported arguments {kwargs}"
+ raise ValueError(msg)
+ is_pydantic_schema = isinstance(schema, type) and is_basemodel_subclass(schema)
+ if method == "function_calling":
+ if schema is None:
+ msg = (
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ raise ValueError(msg)
+ formatted_tool = convert_to_openai_tool(schema)
+ tool_name = formatted_tool["function"]["name"]
+ llm = self.bind_tools(
+ [schema],
+ tool_choice=tool_name,
+ ls_structured_output_format={
+ "kwargs": {"method": "function_calling"},
+ "schema": formatted_tool,
+ },
+ )
+ if is_pydantic_schema:
+ msg = "Pydantic schema is not supported for function calling"
+ raise NotImplementedError(msg)
+ output_parser: JsonOutputKeyToolsParser | JsonOutputParser = (
+ JsonOutputKeyToolsParser(key_name=tool_name, first_tool_only=True)
+ )
+ elif method == "json_schema":
+ if schema is None:
+ msg = (
+ "schema must be specified when method is 'json_schema'. "
+ "Received None."
+ )
+ raise ValueError(msg)
+ formatted_schema = convert_to_json_schema(schema)
+ llm = self.bind(
+ response_format={"type": "json_object", "schema": formatted_schema},
+ ls_structured_output_format={
+ "kwargs": {"method": "json_schema"},
+ "schema": schema,
+ },
+ )
+ output_parser = JsonOutputParser() # type: ignore[arg-type]
+ elif method == "json_mode":
+ llm = self.bind(
+ response_format={"type": "json_object"},
+ ls_structured_output_format={
+ "kwargs": {"method": "json_mode"},
+ "schema": schema,
+ },
+ )
+ output_parser = JsonOutputParser() # type: ignore[arg-type]
+ else:
+ msg = (
+ f"Unrecognized method argument. Expected one of 'function_calling' or "
+ f"'json_mode'. Received: '{method}'"
+ )
+ raise ValueError(msg)
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ return llm | output_parser
+
+ def _create_message_dicts(
+ self, messages: list[BaseMessage], stop: list[str] | None
+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ params = self._default_params
+ if stop is not None:
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ @property
+ def _default_params(self) -> dict[str, Any]:
+ """Get default parameters for calling Hugging Face Inference Providers API."""
+ params = {
+ "model": self.model_id,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ "stop": self.stop,
+ **(self.model_kwargs if self.model_kwargs else {}),
+ }
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+ return params
+
+ @property
+ def _llm_type(self) -> str:
+ return "huggingface-chat-wrapper"
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/data/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..07c24b14111f538c866a6e7769b1933a3d5b9165
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__init__.py
@@ -0,0 +1 @@
+"""Model profile data. All edits should be made in profile_augmentations.toml."""
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66fab61ec9188ad87ef73b60c50af1b02c3f5096
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96822bc1143292c905c429d43bb8367bf4a7f086
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/data/_profiles.py b/python/user_packages/Python313/site-packages/langchain_huggingface/data/_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b78dc6ac610808f34c868a7b4213e943e4ede66
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/data/_profiles.py
@@ -0,0 +1,460 @@
+"""Auto-generated model profiles.
+
+DO NOT EDIT THIS FILE MANUALLY.
+This file is generated by the langchain-profiles CLI tool.
+
+It contains data derived from the models.dev project.
+
+Source: https://github.com/sst/models.dev
+License: MIT License
+
+To update these data, refer to the instructions here:
+
+https://docs.langchain.com/oss/python/langchain/models#updating-or-overwriting-profile-data
+"""
+
+from typing import Any
+
+_PROFILES: dict[str, dict[str, Any]] = {
+ "MiniMaxAI/MiniMax-M2.1": {
+ "name": "MiniMax-M2.1",
+ "release_date": "2025-12-23",
+ "last_updated": "2025-12-23",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "MiniMaxAI/MiniMax-M2.5": {
+ "name": "MiniMax-M2.5",
+ "release_date": "2026-02-12",
+ "last_updated": "2026-02-12",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "MiniMaxAI/MiniMax-M2.7": {
+ "name": "MiniMax-M2.7",
+ "release_date": "2026-03-18",
+ "last_updated": "2026-03-18",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "structured_output": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-235B-A22B-Thinking-2507": {
+ "name": "Qwen3-235B-A22B-Thinking-2507",
+ "release_date": "2025-07-25",
+ "last_updated": "2025-07-25",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct": {
+ "name": "Qwen3-Coder-480B-A35B-Instruct",
+ "release_date": "2025-07-23",
+ "last_updated": "2025-07-23",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 66536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Coder-Next": {
+ "name": "Qwen3-Coder-Next",
+ "release_date": "2026-02-03",
+ "last_updated": "2026-02-03",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 65536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Embedding-4B": {
+ "name": "Qwen 3 Embedding 4B",
+ "release_date": "2025-01-01",
+ "last_updated": "2025-01-01",
+ "open_weights": True,
+ "max_input_tokens": 32000,
+ "max_output_tokens": 2048,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": False,
+ "attachment": False,
+ "temperature": False,
+ },
+ "Qwen/Qwen3-Embedding-8B": {
+ "name": "Qwen 3 Embedding 8B",
+ "release_date": "2025-01-01",
+ "last_updated": "2025-01-01",
+ "open_weights": True,
+ "max_input_tokens": 32000,
+ "max_output_tokens": 4096,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": False,
+ "attachment": False,
+ "temperature": False,
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Instruct": {
+ "name": "Qwen3-Next-80B-A3B-Instruct",
+ "release_date": "2025-09-11",
+ "last_updated": "2025-09-11",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 66536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Thinking": {
+ "name": "Qwen3-Next-80B-A3B-Thinking",
+ "release_date": "2025-09-11",
+ "last_updated": "2025-09-11",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3.5-397B-A17B": {
+ "name": "Qwen3.5-397B-A17B",
+ "release_date": "2026-02-01",
+ "last_updated": "2026-02-01",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 32768,
+ "text_inputs": True,
+ "image_inputs": True,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": True,
+ "temperature": True,
+ },
+ "XiaomiMiMo/MiMo-V2-Flash": {
+ "name": "MiMo-V2-Flash",
+ "release_date": "2025-12-16",
+ "last_updated": "2025-12-16",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 4096,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "deepseek-ai/DeepSeek-R1-0528": {
+ "name": "DeepSeek-R1-0528",
+ "release_date": "2025-05-28",
+ "last_updated": "2025-05-28",
+ "open_weights": True,
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "deepseek-ai/DeepSeek-V3.2": {
+ "name": "DeepSeek-V3.2",
+ "release_date": "2025-12-01",
+ "last_updated": "2025-12-01",
+ "open_weights": True,
+ "max_input_tokens": 163840,
+ "max_output_tokens": 65536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Instruct": {
+ "name": "Kimi-K2-Instruct",
+ "release_date": "2025-07-14",
+ "last_updated": "2025-07-14",
+ "open_weights": True,
+ "max_input_tokens": 131072,
+ "max_output_tokens": 16384,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Instruct-0905": {
+ "name": "Kimi-K2-Instruct-0905",
+ "release_date": "2025-09-04",
+ "last_updated": "2025-09-04",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 16384,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Thinking": {
+ "name": "Kimi-K2-Thinking",
+ "release_date": "2025-11-06",
+ "last_updated": "2025-11-06",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2.5": {
+ "name": "Kimi-K2.5",
+ "release_date": "2026-01-01",
+ "last_updated": "2026-01-01",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "text_inputs": True,
+ "image_inputs": True,
+ "audio_inputs": False,
+ "video_inputs": True,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": True,
+ "temperature": True,
+ },
+ "zai-org/GLM-4.7": {
+ "name": "GLM-4.7",
+ "release_date": "2025-12-22",
+ "last_updated": "2025-12-22",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-4.7-Flash": {
+ "name": "GLM-4.7-Flash",
+ "release_date": "2025-08-08",
+ "last_updated": "2025-08-08",
+ "open_weights": True,
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-5": {
+ "name": "GLM-5",
+ "release_date": "2026-02-11",
+ "last_updated": "2026-02-11",
+ "open_weights": True,
+ "max_input_tokens": 202752,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-5.1": {
+ "name": "GLM-5.1",
+ "release_date": "2026-04-03",
+ "last_updated": "2026-04-03",
+ "open_weights": True,
+ "max_input_tokens": 202752,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+}
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..746d1c31ca7c75034ef7bf31e354fcf11ef6a26f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__init__.py
@@ -0,0 +1,11 @@
+from langchain_huggingface.embeddings.huggingface import (
+ HuggingFaceEmbeddings, # type: ignore[import-not-found]
+)
+from langchain_huggingface.embeddings.huggingface_endpoint import (
+ HuggingFaceEndpointEmbeddings,
+)
+
+__all__ = [
+ "HuggingFaceEmbeddings",
+ "HuggingFaceEndpointEmbeddings",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd90ab6c768ce4bb5bf5becca9233eb7184e4263
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04d5cdd4d6ee36a1cf5c82f603399108f71d2f97
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9e36b2bdbc88034dc0e3e3cac0423caa7fab8b1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface.py b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c55348cee1aa56f4a2aa3f10377456bde5c466e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface.py
@@ -0,0 +1,172 @@
+from __future__ import annotations
+
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field
+
+from langchain_huggingface.utils.import_utils import (
+ IMPORT_ERROR,
+ is_ipex_available,
+ is_optimum_intel_available,
+ is_optimum_intel_version,
+)
+
+_MIN_OPTIMUM_VERSION = "1.22"
+
+
+class HuggingFaceEmbeddings(BaseModel, Embeddings):
+ """HuggingFace sentence_transformers embedding models.
+
+ To use, you should have the `sentence_transformers` python package installed.
+
+ Example:
+ ```python
+ from langchain_huggingface import HuggingFaceEmbeddings
+
+ model_name = "sentence-transformers/all-mpnet-base-v2"
+ model_kwargs = {"device": "cpu"}
+ encode_kwargs = {"normalize_embeddings": False}
+ hf = HuggingFaceEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs,
+ )
+ ```
+ """
+
+ model_name: str = Field(
+ default="sentence-transformers/all-mpnet-base-v2", alias="model"
+ )
+ """Model name to use."""
+ cache_folder: str | None = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the Sentence Transformer model, such as `device`,
+ `prompts`, `default_prompt_name`, `revision`, `trust_remote_code`, or `token`.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer"""
+ encode_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method for the documents of
+ the Sentence Transformer model, such as `prompt_name`, `prompt`, `batch_size`,
+ `precision`, `normalize_embeddings`, and more.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode"""
+ query_encode_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method for the query of
+ the Sentence Transformer model, such as `prompt_name`, `prompt`, `batch_size`,
+ `precision`, `normalize_embeddings`, and more.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode"""
+ multi_process: bool = False
+ """Run encode() on multiple GPUs."""
+ show_progress: bool = False
+ """Whether to show a progress bar."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+ try:
+ import sentence_transformers # type: ignore[import]
+ except ImportError as exc:
+ msg = (
+ "Could not import sentence_transformers python package. "
+ "Please install it with `pip install sentence-transformers`."
+ )
+ raise ImportError(msg) from exc
+
+ if self.model_kwargs.get("backend", "torch") == "ipex":
+ if not is_optimum_intel_available() or not is_ipex_available():
+ msg = f"Backend: ipex {IMPORT_ERROR.format('optimum[ipex]')}"
+ raise ImportError(msg)
+
+ if is_optimum_intel_version("<", _MIN_OPTIMUM_VERSION):
+ msg = (
+ f"Backend: ipex requires optimum-intel>="
+ f"{_MIN_OPTIMUM_VERSION}. You can install it with pip: "
+ "`pip install --upgrade --upgrade-strategy eager "
+ "`optimum[ipex]`."
+ )
+ raise ImportError(msg)
+
+ from optimum.intel import IPEXSentenceTransformer # type: ignore[import]
+
+ model_cls = IPEXSentenceTransformer
+
+ else:
+ model_cls = sentence_transformers.SentenceTransformer
+
+ self._client = model_cls(
+ self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
+ )
+
+ model_config = ConfigDict(
+ extra="forbid",
+ protected_namespaces=(),
+ populate_by_name=True,
+ )
+
+ def _embed(
+ self, texts: list[str], encode_kwargs: dict[str, Any]
+ ) -> list[list[float]]:
+ """Embed a text using the HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+ encode_kwargs: Keyword arguments to pass when calling the
+ `encode` method for the documents of the SentenceTransformer
+ encode method.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ import sentence_transformers # type: ignore[import]
+
+ texts = [x.replace("\n", " ") for x in texts]
+ if self.multi_process:
+ pool = self._client.start_multi_process_pool()
+ embeddings = self._client.encode_multi_process(texts, pool)
+ sentence_transformers.SentenceTransformer.stop_multi_process_pool(pool)
+ else:
+ embeddings = self._client.encode(
+ texts,
+ show_progress_bar=self.show_progress,
+ **encode_kwargs,
+ )
+
+ if isinstance(embeddings, list):
+ msg = (
+ "Expected embeddings to be a Tensor or a numpy array, "
+ "got a list instead."
+ )
+ raise TypeError(msg)
+
+ return embeddings.tolist() # type: ignore[return-type]
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Compute doc embeddings using a HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ return self._embed(texts, self.encode_kwargs)
+
+ def embed_query(self, text: str) -> list[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ embed_kwargs = (
+ self.query_encode_kwargs
+ if len(self.query_encode_kwargs) > 0
+ else self.encode_kwargs
+ )
+ return self._embed([text], embed_kwargs)[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..25dfd4fc753c25c0a85c75eb5eb4a106fd1174ab
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+import os
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import from_env
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self
+
+DEFAULT_MODEL = "sentence-transformers/all-mpnet-base-v2"
+VALID_TASKS = ("feature-extraction",)
+
+
+class HuggingFaceEndpointEmbeddings(BaseModel, Embeddings):
+ """HuggingFaceHub embedding models.
+
+ To use, you should have the `huggingface_hub` python package installed, and the
+ environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ ```python
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
+
+ model = "sentence-transformers/all-mpnet-base-v2"
+ hf = HuggingFaceEndpointEmbeddings(
+ model=model,
+ task="feature-extraction",
+ huggingfacehub_api_token="my-api-key",
+ )
+ ```
+ """
+
+ client: Any = None
+
+ async_client: Any = None
+
+ model: str | None = None
+ """Model name to use."""
+
+ provider: str | None = None
+ """Name of the provider to use for inference with the model specified in
+ `repo_id`. e.g. "sambanova". if not specified, defaults to HF Inference API.
+ available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
+
+ repo_id: str | None = None
+ """Huggingfacehub repository id, for backward compatibility."""
+
+ task: str | None = "feature-extraction"
+ """Task to call the model with."""
+
+ model_kwargs: dict | None = None
+ """Keyword arguments to pass to the model."""
+
+ huggingfacehub_api_token: str | None = Field(
+ default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
+ )
+
+ model_config = ConfigDict(
+ extra="forbid",
+ protected_namespaces=(),
+ )
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that api key and python package exists in environment."""
+ for field_name in ("model", "repo_id"):
+ value = getattr(self, field_name)
+ if value and value.startswith(("http://", "https://")):
+ msg = f"`{field_name}` must be a HuggingFace repo ID, not a URL."
+ raise ValueError(msg)
+
+ huggingfacehub_api_token = self.huggingfacehub_api_token or os.getenv(
+ "HF_TOKEN"
+ )
+
+ try:
+ from huggingface_hub import ( # type: ignore[import]
+ AsyncInferenceClient,
+ InferenceClient,
+ )
+
+ if self.model:
+ self.repo_id = self.model
+ elif self.repo_id:
+ self.model = self.repo_id
+ else:
+ self.model = DEFAULT_MODEL
+ self.repo_id = DEFAULT_MODEL
+
+ client = InferenceClient(
+ model=self.model,
+ token=huggingfacehub_api_token,
+ provider=self.provider, # type: ignore[arg-type]
+ )
+
+ async_client = AsyncInferenceClient(
+ model=self.model,
+ token=huggingfacehub_api_token,
+ provider=self.provider, # type: ignore[arg-type]
+ )
+
+ if self.task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {self.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ self.client = client
+ self.async_client = async_client
+
+ except ImportError as e:
+ msg = (
+ "Could not import huggingface_hub python package. "
+ "Please install it with `pip install huggingface_hub`."
+ )
+ raise ImportError(msg) from e
+ return self
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ # api doc: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/embed
+ responses = self.client.feature_extraction(text=texts, **_model_kwargs)
+ return responses.tolist()
+
+ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ responses = await self.async_client.feature_extraction(
+ text=texts, **_model_kwargs
+ )
+ return responses.tolist()
+
+ def embed_query(self, text: str) -> list[float]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ return self.embed_documents([text])[0]
+
+ async def aembed_query(self, text: str) -> list[float]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ return (await self.aembed_documents([text]))[0]
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c5acce55177b4adbd42cc17f7ebdf4e490be572
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__init__.py
@@ -0,0 +1,9 @@
+from langchain_huggingface.llms.huggingface_endpoint import (
+ HuggingFaceEndpoint, # type: ignore[import-not-found]
+)
+from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+__all__ = [
+ "HuggingFaceEndpoint",
+ "HuggingFacePipeline",
+]
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f9e6ebfc250b0ce7e4912a942b2803769ad5c69
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b059a5a8a9bdf2404be65a243a202a3d075f58f6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d03a9397e560d99d429e0b96b40c1eddcbf90b87
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_endpoint.py b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3a15b1c675c8ef35b8ac8c36ce4b3aff1a4354a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_endpoint.py
@@ -0,0 +1,481 @@
+from __future__ import annotations
+
+import inspect
+import logging
+import os
+from collections.abc import AsyncIterator, Iterator, Mapping
+from typing import Any
+from urllib.parse import urlparse
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.llms import LLM
+from langchain_core.outputs import GenerationChunk
+from langchain_core.utils import from_env, get_pydantic_field_names
+from pydantic import ConfigDict, Field, model_validator
+from typing_extensions import Self
+
+logger = logging.getLogger(__name__)
+
+
+def _is_huggingface_hosted_url(url: str | None) -> bool:
+ """True if url is HF-hosted (huggingface.co or hf.space)."""
+ if not url:
+ return False
+ hostname = (urlparse(url).hostname or "").lower()
+ return (
+ hostname == "huggingface.co"
+ or hostname == "hf.space"
+ or hostname.endswith((".huggingface.co", ".hf.space"))
+ )
+
+
+VALID_TASKS = (
+ "text2text-generation",
+ "text-generation",
+ "summarization",
+ "conversational",
+)
+
+
+class HuggingFaceEndpoint(LLM):
+ """Hugging Face Endpoint. This works with any model that supports text generation (i.e. text completion) task.
+
+ To use this class, you should have installed the `huggingface_hub` package, and
+ the environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token,
+ or given as a named parameter to the constructor.
+
+ Example:
+ ```python
+ # Basic Example (no streaming)
+ model = HuggingFaceEndpoint(
+ endpoint_url="http://localhost:8010/",
+ max_new_tokens=512,
+ top_k=10,
+ top_p=0.95,
+ typical_p=0.95,
+ temperature=0.01,
+ repetition_penalty=1.03,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+
+ # Streaming response example
+ from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
+
+ callbacks = [StreamingStdOutCallbackHandler()]
+ model = HuggingFaceEndpoint(
+ endpoint_url="http://localhost:8010/",
+ max_new_tokens=512,
+ top_k=10,
+ top_p=0.95,
+ typical_p=0.95,
+ temperature=0.01,
+ repetition_penalty=1.03,
+ callbacks=callbacks,
+ streaming=True,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+
+ # Basic Example (no streaming) with Mistral-Nemo-Base-2407 model using a third-party provider (Novita).
+ model = HuggingFaceEndpoint(
+ repo_id="mistralai/Mistral-Nemo-Base-2407",
+ provider="novita",
+ max_new_tokens=100,
+ do_sample=False,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+ ```
+ """ # noqa: E501
+
+ endpoint_url: str | None = None
+ """Endpoint URL to use. If repo_id is not specified then this needs to given or
+ should be pass as env variable in `HF_INFERENCE_ENDPOINT`"""
+
+ repo_id: str | None = None
+ """Repo to use. If endpoint_url is not specified then this needs to given"""
+
+ provider: str | None = None
+ """Name of the provider to use for inference with the model specified in `repo_id`.
+ e.g. "cerebras". if not specified, Defaults to "auto" i.e. the first of the
+ providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers.
+ available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
+
+ huggingfacehub_api_token: str | None = Field(
+ default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
+ )
+
+ max_new_tokens: int = 512
+ """Maximum number of generated tokens"""
+
+ top_k: int | None = None
+ """The number of highest probability vocabulary tokens to keep for
+ top-k-filtering."""
+
+ top_p: float | None = 0.95
+ """If set to < 1, only the smallest set of most probable tokens with probabilities
+ that add up to `top_p` or higher are kept for generation."""
+
+ typical_p: float | None = 0.95
+ """Typical Decoding mass. See [Typical Decoding for Natural Language
+ Generation](https://arxiv.org/abs/2202.00666) for more information."""
+
+ temperature: float | None = 0.8
+ """The value used to module the logits distribution."""
+
+ repetition_penalty: float | None = None
+ """The parameter for repetition penalty. 1.0 means no penalty.
+ See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details."""
+
+ return_full_text: bool = False
+ """Whether to prepend the prompt to the generated text"""
+
+ truncate: int | None = None
+ """Truncate inputs tokens to the given size"""
+
+ stop_sequences: list[str] = Field(default_factory=list)
+ """Stop generating tokens if a member of `stop_sequences` is generated"""
+
+ seed: int | None = None
+ """Random sampling seed"""
+
+ inference_server_url: str = ""
+ """text-generation-inference instance base url"""
+
+ timeout: int = 120
+ """Timeout in seconds"""
+
+ streaming: bool = False
+ """Whether to generate a stream of tokens asynchronously"""
+
+ do_sample: bool = False
+ """Activate logits sampling"""
+
+ watermark: bool = False
+ """Watermarking with [A Watermark for Large Language Models]
+ (https://arxiv.org/abs/2301.10226)"""
+
+ server_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any text-generation-inference server parameters not explicitly specified"""
+
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `call` not explicitly specified"""
+
+ model: str
+
+ client: Any = None
+
+ async_client: Any = None
+
+ task: str | None = None
+ """Task to call the model with. Should be a task that returns `generated_text`."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please make sure that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ msg = (
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+ raise ValueError(msg)
+
+ values["model_kwargs"] = extra
+
+ # to correctly create the InferenceClient and AsyncInferenceClient
+ # in validate_environment, we need to populate values["model"].
+ # from InferenceClient docstring:
+ # model (`str`, `optional`):
+ # The model to run inference with. Can be a model id hosted on the Hugging
+ # Face Hub, e.g. `bigcode/starcoder`
+ # or a URL to a deployed Inference Endpoint. Defaults to `None`, in which
+ # case a recommended model is
+ # automatically selected for the task.
+
+ # this string could be in 3 places of descending priority:
+ # 2. values["model"] or values["endpoint_url"] or values["repo_id"]
+ # (equal priority - don't allow both set)
+ # 3. values["HF_INFERENCE_ENDPOINT"] (if none above set)
+
+ model = values.get("model")
+ endpoint_url = values.get("endpoint_url")
+ repo_id = values.get("repo_id")
+
+ if repo_id and repo_id.startswith(("http://", "https://")):
+ msg = (
+ "`repo_id` must be a HuggingFace repo ID, not a URL. "
+ "Use `endpoint_url` for direct endpoints."
+ )
+ raise ValueError(msg)
+
+ if sum([bool(model), bool(endpoint_url), bool(repo_id)]) > 1:
+ msg = (
+ "Please specify either a `model` OR an `endpoint_url` OR a `repo_id`,"
+ "not more than one."
+ )
+ raise ValueError(msg)
+ values["model"] = (
+ model or endpoint_url or repo_id or os.environ.get("HF_INFERENCE_ENDPOINT")
+ )
+ if not values["model"]:
+ msg = (
+ "Please specify a `model` or an `endpoint_url` or a `repo_id` for the "
+ "model."
+ )
+ raise ValueError(msg)
+ return values
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that package is installed and that the API token is valid."""
+ huggingfacehub_api_token = self.huggingfacehub_api_token or os.getenv(
+ "HF_TOKEN"
+ )
+ # Local/custom endpoint URL -> don't pass HF token (avoids 401s and egress).
+ if self.endpoint_url and not _is_huggingface_hosted_url(self.endpoint_url):
+ client_api_key: str | None = None
+ else:
+ client_api_key = huggingfacehub_api_token
+
+ from huggingface_hub import ( # type: ignore[import]
+ AsyncInferenceClient, # type: ignore[import]
+ InferenceClient, # type: ignore[import]
+ )
+
+ # Instantiate clients with supported kwargs
+ sync_supported_kwargs = set(inspect.signature(InferenceClient).parameters)
+ self.client = InferenceClient(
+ model=self.model,
+ timeout=self.timeout,
+ api_key=client_api_key,
+ provider=self.provider, # type: ignore[arg-type]
+ **{
+ key: value
+ for key, value in self.server_kwargs.items()
+ if key in sync_supported_kwargs
+ },
+ )
+
+ async_supported_kwargs = set(inspect.signature(AsyncInferenceClient).parameters)
+ self.async_client = AsyncInferenceClient(
+ model=self.model,
+ timeout=self.timeout,
+ api_key=client_api_key,
+ provider=self.provider, # type: ignore[arg-type]
+ **{
+ key: value
+ for key, value in self.server_kwargs.items()
+ if key in async_supported_kwargs
+ },
+ )
+ ignored_kwargs = (
+ set(self.server_kwargs.keys())
+ - sync_supported_kwargs
+ - async_supported_kwargs
+ )
+ if len(ignored_kwargs) > 0:
+ logger.warning(
+ f"Ignoring following parameters as they are not supported by the "
+ f"InferenceClient or AsyncInferenceClient: {ignored_kwargs}."
+ )
+
+ return self
+
+ @property
+ def _default_params(self) -> dict[str, Any]:
+ """Get the default parameters for calling text generation inference API."""
+ return {
+ "max_new_tokens": self.max_new_tokens,
+ "top_k": self.top_k,
+ "top_p": self.top_p,
+ "typical_p": self.typical_p,
+ "temperature": self.temperature,
+ "repetition_penalty": self.repetition_penalty,
+ "return_full_text": self.return_full_text,
+ "truncate": self.truncate,
+ "stop": self.stop_sequences,
+ "seed": self.seed,
+ "do_sample": self.do_sample,
+ "watermark": self.watermark,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ _model_kwargs = self.model_kwargs or {}
+ return {
+ "endpoint_url": self.endpoint_url,
+ "task": self.task,
+ "provider": self.provider,
+ "model_kwargs": _model_kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "huggingface_endpoint"
+
+ def _invocation_params(
+ self, runtime_stop: list[str] | None, **kwargs: Any
+ ) -> dict[str, Any]:
+ params = {**self._default_params, **kwargs}
+ params["stop"] = params["stop"] + (runtime_stop or [])
+ return params
+
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Call out to HuggingFace Hub's inference endpoint."""
+ invocation_params = self._invocation_params(stop, **kwargs)
+ if self.streaming:
+ completion = ""
+ for chunk in self._stream(
+ prompt, run_manager=run_manager, **invocation_params
+ ):
+ completion += chunk.text
+ return completion
+
+ response_text = self.client.text_generation(
+ prompt=prompt,
+ model=self.model,
+ **invocation_params,
+ )
+
+ # Maybe the generation has stopped at one of the stop sequences:
+ # then we remove this stop sequence from the end of the generated text
+ for stop_seq in invocation_params["stop"]:
+ if response_text[-len(stop_seq) :] == stop_seq:
+ response_text = response_text[: -len(stop_seq)]
+ return response_text
+
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ invocation_params = self._invocation_params(stop, **kwargs)
+ if self.streaming:
+ completion = ""
+ async for chunk in self._astream(
+ prompt, run_manager=run_manager, **invocation_params
+ ):
+ completion += chunk.text
+ return completion
+
+ response_text = await self.async_client.text_generation(
+ prompt=prompt,
+ **invocation_params,
+ model=self.model,
+ stream=False,
+ )
+
+ # Maybe the generation has stopped at one of the stop sequences:
+ # then remove this stop sequence from the end of the generated text
+ for stop_seq in invocation_params["stop"]:
+ if response_text[-len(stop_seq) :] == stop_seq:
+ response_text = response_text[: -len(stop_seq)]
+ return response_text
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ invocation_params = self._invocation_params(stop, **kwargs)
+
+ for response in self.client.text_generation(
+ prompt, **invocation_params, stream=True
+ ):
+ # identify stop sequence in generated text, if any
+ stop_seq_found: str | None = None
+ for stop_seq in invocation_params["stop"]:
+ if stop_seq in response:
+ stop_seq_found = stop_seq
+
+ # identify text to yield
+ text: str | None = None
+ if stop_seq_found:
+ text = response[: response.index(stop_seq_found)]
+ else:
+ text = response
+
+ # yield text, if any
+ if text:
+ chunk = GenerationChunk(text=text)
+
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text)
+ yield chunk
+
+ # break if stop sequence found
+ if stop_seq_found:
+ break
+
+ async def _astream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[GenerationChunk]:
+ invocation_params = self._invocation_params(stop, **kwargs)
+ async for response in await self.async_client.text_generation(
+ prompt, **invocation_params, stream=True
+ ):
+ # identify stop sequence in generated text, if any
+ stop_seq_found: str | None = None
+ for stop_seq in invocation_params["stop"]:
+ if stop_seq in response:
+ stop_seq_found = stop_seq
+
+ # identify text to yield
+ text: str | None = None
+ if stop_seq_found:
+ text = response[: response.index(stop_seq_found)]
+ else:
+ text = response
+
+ # yield text, if any
+ if text:
+ chunk = GenerationChunk(text=text)
+
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text)
+ yield chunk
+
+ # break if stop sequence found
+ if stop_seq_found:
+ break
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_pipeline.py b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba646f1309f181b60f023f8500cd6a4e3d561dff
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/llms/huggingface_pipeline.py
@@ -0,0 +1,422 @@
+from __future__ import annotations # type: ignore[import-not-found]
+
+import importlib.util
+import logging
+from collections.abc import Iterator, Mapping
+from typing import Any
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.llms import BaseLLM
+from langchain_core.outputs import Generation, GenerationChunk, LLMResult
+from pydantic import ConfigDict, model_validator
+
+from langchain_huggingface.utils.import_utils import (
+ IMPORT_ERROR,
+ is_ipex_available,
+ is_openvino_available,
+ is_optimum_intel_available,
+ is_optimum_intel_version,
+)
+
+DEFAULT_MODEL_ID = "gpt2"
+DEFAULT_TASK = "text-generation"
+VALID_TASKS = (
+ "text2text-generation",
+ "text-generation",
+ "image-text-to-text",
+ "summarization",
+ "translation",
+)
+DEFAULT_BATCH_SIZE = 4
+_MIN_OPTIMUM_VERSION = "1.21"
+
+
+logger = logging.getLogger(__name__)
+
+
+class HuggingFacePipeline(BaseLLM):
+ """HuggingFace Pipeline API.
+
+ To use, you should have the `transformers` python package installed.
+
+ Only supports `text-generation`, `text2text-generation`, `image-text-to-text`,
+ `summarization` and `translation` for now.
+
+ Example using from_model_id:
+ ```python
+ from langchain_huggingface import HuggingFacePipeline
+
+ hf = HuggingFacePipeline.from_model_id(
+ model_id="gpt2",
+ task="text-generation",
+ pipeline_kwargs={"max_new_tokens": 10},
+ )
+ ```
+
+ Example passing pipeline in directly:
+ ```python
+ from langchain_huggingface import HuggingFacePipeline
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
+
+ model_id = "gpt2"
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
+ model = AutoModelForCausalLM.from_pretrained(model_id)
+ pipe = pipeline(
+ "text-generation",
+ model=model,
+ tokenizer=tokenizer,
+ max_new_tokens=10,
+ )
+ hf = HuggingFacePipeline(pipeline=pipe)
+ ```
+ """
+
+ pipeline: Any = None
+
+ model_id: str | None = None
+ """The model name. If not set explicitly by the user,
+ it will be inferred from the provided pipeline (if available).
+ If neither is provided, the DEFAULT_MODEL_ID will be used."""
+
+ model_kwargs: dict | None = None
+ """Keyword arguments passed to the model."""
+
+ pipeline_kwargs: dict | None = None
+ """Keyword arguments passed to the pipeline."""
+
+ batch_size: int = DEFAULT_BATCH_SIZE
+ """Batch size to use when passing multiple documents to generate."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def pre_init_validator(cls, values: dict[str, Any]) -> dict[str, Any]:
+ """Ensure model_id is set either by pipeline or user input."""
+ if "model_id" not in values:
+ if values.get("pipeline"):
+ values["model_id"] = values["pipeline"].model.name_or_path
+ else:
+ values["model_id"] = DEFAULT_MODEL_ID
+ return values
+
+ @classmethod
+ def from_model_id(
+ cls,
+ model_id: str,
+ task: str,
+ backend: str = "default",
+ device: int | None = None,
+ device_map: str | None = None,
+ model_kwargs: dict | None = None,
+ pipeline_kwargs: dict | None = None,
+ batch_size: int = DEFAULT_BATCH_SIZE,
+ **kwargs: Any,
+ ) -> HuggingFacePipeline:
+ """Construct the pipeline object from model_id and task."""
+ try:
+ from transformers import ( # type: ignore[import]
+ AutoModelForCausalLM,
+ AutoModelForSeq2SeqLM,
+ AutoTokenizer,
+ )
+ from transformers import pipeline as hf_pipeline # type: ignore[import]
+
+ except ImportError as e:
+ msg = (
+ "Could not import transformers python package. "
+ "Please install it with `pip install transformers`."
+ )
+ raise ValueError(msg) from e
+
+ _model_kwargs = model_kwargs.copy() if model_kwargs else {}
+ if device_map is not None:
+ if device is not None:
+ msg = (
+ "Both `device` and `device_map` are specified. "
+ "`device` will override `device_map`. "
+ "You will most likely encounter unexpected behavior."
+ "Please remove `device` and keep "
+ "`device_map`."
+ )
+ raise ValueError(msg)
+
+ if "device_map" in _model_kwargs:
+ msg = "`device_map` is already specified in `model_kwargs`."
+ raise ValueError(msg)
+
+ _model_kwargs["device_map"] = device_map
+ tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)
+
+ if backend in {"openvino", "ipex"}:
+ if task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+
+ err_msg = f"Backend: {backend} {IMPORT_ERROR.format(f'optimum[{backend}]')}"
+ if not is_optimum_intel_available():
+ raise ImportError(err_msg)
+
+ # TODO: upgrade _MIN_OPTIMUM_VERSION to 1.22 after release
+ min_optimum_version = (
+ "1.22"
+ if backend == "ipex" and task != "text-generation"
+ else _MIN_OPTIMUM_VERSION
+ )
+ if is_optimum_intel_version("<", min_optimum_version):
+ msg = (
+ f"Backend: {backend} requires optimum-intel>="
+ f"{min_optimum_version}. You can install it with pip: "
+ "`pip install --upgrade --upgrade-strategy eager "
+ f"`optimum[{backend}]`."
+ )
+ raise ImportError(msg)
+
+ if backend == "openvino":
+ if not is_openvino_available():
+ raise ImportError(err_msg)
+
+ from optimum.intel import ( # type: ignore[import]
+ OVModelForCausalLM,
+ OVModelForSeq2SeqLM,
+ )
+
+ model_cls = (
+ OVModelForCausalLM
+ if task == "text-generation"
+ else OVModelForSeq2SeqLM
+ )
+ else:
+ if not is_ipex_available():
+ raise ImportError(err_msg)
+
+ if task == "text-generation":
+ from optimum.intel import (
+ IPEXModelForCausalLM, # type: ignore[import]
+ )
+
+ model_cls = IPEXModelForCausalLM
+ else:
+ from optimum.intel import (
+ IPEXModelForSeq2SeqLM, # type: ignore[import]
+ )
+
+ model_cls = IPEXModelForSeq2SeqLM
+
+ else:
+ model_cls = (
+ AutoModelForCausalLM
+ if task == "text-generation"
+ else AutoModelForSeq2SeqLM
+ )
+
+ model = model_cls.from_pretrained(model_id, **_model_kwargs)
+
+ if tokenizer.pad_token is None:
+ if model.config.pad_token_id is not None:
+ tokenizer.pad_token_id = model.config.pad_token_id
+ elif model.config.eos_token_id is not None and isinstance(
+ model.config.eos_token_id, int
+ ):
+ tokenizer.pad_token_id = model.config.eos_token_id
+ elif tokenizer.eos_token_id is not None:
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ else:
+ tokenizer.add_special_tokens({"pad_token": "[PAD]"})
+
+ if (
+ (
+ getattr(model, "is_loaded_in_4bit", False)
+ or getattr(model, "is_loaded_in_8bit", False)
+ )
+ and device is not None
+ and backend == "default"
+ ):
+ logger.warning(
+ f"Setting the `device` argument to None from {device} to avoid "
+ "the error caused by attempting to move the model that was already "
+ "loaded on the GPU using the Accelerate module to the same or "
+ "another device."
+ )
+ device = None
+
+ if (
+ device is not None
+ and importlib.util.find_spec("torch") is not None
+ and backend == "default"
+ ):
+ import torch
+
+ cuda_device_count = torch.cuda.device_count()
+ if device < -1 or (device >= cuda_device_count):
+ msg = (
+ f"Got device=={device}, "
+ f"device is required to be within [-1, {cuda_device_count})"
+ )
+ raise ValueError(msg)
+ if device_map is not None and device < 0:
+ device = None
+ if device is not None and device < 0 and cuda_device_count > 0:
+ logger.warning(
+ "Device has %d GPUs available. "
+ "Provide device={deviceId} to `from_model_id` to use available"
+ "GPUs for execution. deviceId is -1 (default) for CPU and "
+ "can be a positive integer associated with CUDA device id.",
+ cuda_device_count,
+ )
+ if device is not None and device_map is not None and backend == "openvino":
+ logger.warning("Please set device for OpenVINO through: `model_kwargs`")
+ if "trust_remote_code" in _model_kwargs:
+ _model_kwargs = {
+ k: v for k, v in _model_kwargs.items() if k != "trust_remote_code"
+ }
+ _pipeline_kwargs = pipeline_kwargs or {}
+ pipeline = hf_pipeline( # type: ignore[call-overload]
+ task=task,
+ model=model,
+ tokenizer=tokenizer,
+ device=device,
+ batch_size=batch_size,
+ model_kwargs=_model_kwargs,
+ **_pipeline_kwargs,
+ )
+ if pipeline.task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {pipeline.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ return cls(
+ pipeline=pipeline,
+ model_id=model_id,
+ model_kwargs=_model_kwargs,
+ pipeline_kwargs=_pipeline_kwargs,
+ batch_size=batch_size,
+ **kwargs,
+ )
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ "model_id": self.model_id,
+ "model_kwargs": self.model_kwargs,
+ "pipeline_kwargs": self.pipeline_kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "huggingface_pipeline"
+
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ # List to hold all results
+ text_generations: list[str] = []
+ pipeline_kwargs = kwargs.get("pipeline_kwargs", {})
+ skip_prompt = kwargs.get("skip_prompt", False)
+
+ for i in range(0, len(prompts), self.batch_size):
+ batch_prompts = prompts[i : i + self.batch_size]
+
+ # Process batch of prompts
+ responses = self.pipeline(
+ batch_prompts,
+ **pipeline_kwargs,
+ )
+
+ # Process each response in the batch
+ for j, response in enumerate(responses):
+ if isinstance(response, list):
+ # if model returns multiple generations, pick the top one
+ response = response[0]
+
+ if (
+ self.pipeline.task == "text-generation"
+ or self.pipeline.task == "text2text-generation"
+ or self.pipeline.task == "image-text-to-text"
+ ):
+ text = response["generated_text"]
+ elif self.pipeline.task == "summarization":
+ text = response["summary_text"]
+ elif self.pipeline.task in "translation":
+ text = response["translation_text"]
+ else:
+ msg = (
+ f"Got invalid task {self.pipeline.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ if skip_prompt:
+ text = text[len(batch_prompts[j]) :]
+ # Append the processed text to results
+ text_generations.append(text)
+
+ return LLMResult(
+ generations=[[Generation(text=text)] for text in text_generations]
+ )
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ from threading import Thread
+
+ import torch
+ from transformers import (
+ StoppingCriteria,
+ StoppingCriteriaList,
+ TextIteratorStreamer,
+ )
+
+ pipeline_kwargs = kwargs.get("pipeline_kwargs", {})
+ skip_prompt = kwargs.get("skip_prompt", True)
+
+ if stop is not None:
+ stop = self.pipeline.tokenizer.convert_tokens_to_ids(stop)
+ stopping_ids_list = stop or []
+
+ class StopOnTokens(StoppingCriteria):
+ def __call__(
+ self,
+ input_ids: torch.LongTensor,
+ scores: torch.FloatTensor,
+ **kwargs: Any,
+ ) -> bool:
+ return any(input_ids[0][-1] == stop_id for stop_id in stopping_ids_list)
+
+ stopping_criteria = StoppingCriteriaList([StopOnTokens()])
+
+ streamer = TextIteratorStreamer(
+ self.pipeline.tokenizer,
+ timeout=60.0,
+ skip_prompt=skip_prompt,
+ skip_special_tokens=True,
+ )
+ generation_kwargs = dict(
+ text_inputs=prompt,
+ streamer=streamer,
+ stopping_criteria=stopping_criteria,
+ **pipeline_kwargs,
+ )
+ t1 = Thread(target=self.pipeline, kwargs=generation_kwargs)
+ t1.start()
+
+ for char in streamer:
+ chunk = GenerationChunk(text=char)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+
+ yield chunk
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/tests/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4a24a1e18b0020f295775a0f09b2d993c674d7f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/tests/integration_tests/__init__.py b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/integration_tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12d815900e4555376cf8601d5904cfeb4508b12c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b48dc2b99a9d0889d4a06835aca877e8226cf940
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_huggingface/utils/import_utils.py b/python/user_packages/Python313/site-packages/langchain_huggingface/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f217517a9804918467093d45edba19e0b110908a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_huggingface/utils/import_utils.py
@@ -0,0 +1,114 @@
+from __future__ import annotations
+
+import importlib.metadata
+import importlib.util
+import operator as op
+
+from packaging import version
+
+STR_OPERATION_TO_FUNC = {
+ ">": op.gt,
+ ">=": op.ge,
+ "==": op.eq,
+ "!=": op.ne,
+ "<=": op.le,
+ "<": op.lt,
+}
+
+
+_optimum_available = importlib.util.find_spec("optimum") is not None
+_optimum_version = "N/A"
+if _optimum_available:
+ try:
+ _optimum_version = importlib.metadata.version("optimum")
+ except importlib.metadata.PackageNotFoundError:
+ _optimum_available = False
+
+
+_optimum_intel_available = (
+ _optimum_available and importlib.util.find_spec("optimum.intel") is not None
+)
+_optimum_intel_version = "N/A"
+if _optimum_intel_available:
+ try:
+ _optimum_intel_version = importlib.metadata.version("optimum-intel")
+ except importlib.metadata.PackageNotFoundError:
+ _optimum_intel_available = False
+
+
+_ipex_available = importlib.util.find_spec("intel_extension_for_pytorch") is not None
+
+_openvino_available = importlib.util.find_spec("openvino") is not None
+
+
+# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L319
+def compare_versions(
+ library_or_version: str | version.Version,
+ operation: str,
+ requirement_version: str,
+) -> bool:
+ """Compare a library version to some requirement using a given operation.
+
+ Args:
+ library_or_version:
+ A library name or a version to check.
+ operation:
+ A string representation of an operator, such as `">"` or `"<="`.
+ requirement_version:
+ The version to compare the library version against
+
+ """
+ if operation not in STR_OPERATION_TO_FUNC:
+ msg = (
+ f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}"
+ f", received {operation}"
+ )
+ raise ValueError(msg)
+ if isinstance(library_or_version, str):
+ library_or_version = version.parse(
+ importlib.metadata.version(library_or_version)
+ )
+ return STR_OPERATION_TO_FUNC[operation](
+ library_or_version, version.parse(requirement_version)
+ )
+
+
+def is_optimum_available() -> bool:
+ return _optimum_available
+
+
+def is_optimum_intel_available() -> bool:
+ return _optimum_intel_available
+
+
+def is_ipex_available() -> bool:
+ return _ipex_available
+
+
+def is_openvino_available() -> bool:
+ return _openvino_available
+
+
+def is_optimum_version(operation: str, reference_version: str) -> bool:
+ """Compare the current Optimum version to a given reference with an operation."""
+ if not _optimum_version:
+ return False
+ return compare_versions(
+ version.parse(_optimum_version), operation, reference_version
+ )
+
+
+def is_optimum_intel_version(operation: str, reference_version: str) -> bool:
+ """Compare current Optimum Intel version to a given reference with an operation."""
+ if not _optimum_intel_version:
+ return False
+ return compare_versions(
+ version.parse(_optimum_intel_version), operation, reference_version
+ )
+
+
+IMPORT_ERROR = """
+requires the {0} library but it was not found in your environment.
+You can install it with pip: `pip install {0}`.
+Please note that you may need to restart your runtime after installation.
+"""
diff --git a/python/user_packages/Python313/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5600729a39188be2387b22ba3016de16c112bc25
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24490a97cbb48c05b271e757129a62138ddec998
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/protocol.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/protocol.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cfb28c0c9be82849b07262d1fb94a7f3b36d842e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_protocol/__pycache__/protocol.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39ede3148bf9fa3ff8248703d885aea52c6a5606
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b97b70ca1081ff0d0f678b47de044a090a8506ae
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/character.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/character.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d204ef2f8251ac65b2ba4fa6b4ece9c8dc8ff13e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/character.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/html.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/html.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..370481c1846b2c7e311683e5b507911817f9ed48
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/html.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/json.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/json.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a71dfed7f8153d6d1270b9eeeb107bb4e5514e14
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/json.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9026e663af2f302abb19ba054495848c3a9c62cd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eac59eb30f1cc263151768dd570d2bcc5860ea6e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/latex.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/latex.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7c4e250b62f6e8711513897c446cb96dc61e2cb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/latex.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2e3f2a7f05609ed2b09549aa4388bc252486225
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95cf4907b3f628c2150d16749e9d0ad661d21c55
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/python.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/python.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24649847981d43bf7411788d7ab84cb3958142f4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/python.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f085d0cfd598b4389b00ed8f986a2dd0b1200328
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-313.pyc b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c80936e1baa1495dfff4778c4c37db13fc21fde
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt b/python/user_packages/Python313/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt
new file mode 100644
index 0000000000000000000000000000000000000000..620e13f54b1bd4904472bb9fee2e919d30f4dab2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/python/user_packages/Python313/site-packages/langgraph-1.2.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/langgraph-1.2.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..fc0602feecdd6748623c852ab534e1ca612673c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph-1.2.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/callbacks.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/callbacks.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50b41fae03b6d13d4c226a1e14570c3702d27d83
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/callbacks.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/config.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..723339c70f7ae82ec5415224496f3d2bd967d60a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/config.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/constants.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/constants.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e1b465ef3c1a12648920e1acab5af26e1882bcb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/constants.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/errors.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5f1a149201df8b15e2a96f2dcf813fbebaf9385
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/errors.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/runtime.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/runtime.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29f5d27d07b551ae49ce97826c764c5ce5d856bf
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/runtime.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a59203bcab052d7ada63c657c8241b58d5e0a0f7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/typing.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/typing.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93cabfb11e398bcd66cece6916e1be2b4a5ede25
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/typing.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/version.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e12e555c4528b7e9c658f127c8e10f46f8862b65
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/version.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/__pycache__/warnings.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/__pycache__/warnings.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f495261acfed5d4cbfcabbe840ffb80196f3b020
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/__pycache__/warnings.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__init__.py b/python/user_packages/Python313/site-packages/langgraph/_internal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e71cdc23604618ae999e82ee1a796b78543ddc4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/__init__.py
@@ -0,0 +1,4 @@
+"""Internal modules for LangGraph.
+
+This module is not part of the public API, and thus stability is not guaranteed.
+"""
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b4fb554adf915bfe025752723e7047377596e3e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_cache.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_cache.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..156b73fe3ede4792cfb15d48dcc9fafa695ed560
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_cache.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_config.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_config.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df3a18f8518a5f4ce2779ba935ece788399d047c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_config.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_constants.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_constants.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3e5d21c5208b48065728600b2201bb5c809bdd9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_constants.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_fields.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_fields.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..824d197bd764365462daab833dbd8249404a0ca2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_fields.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_future.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_future.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65c29947cb5a07381a263a439302efd4e3da53d2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_future.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38d8fb30613de2711bb4a18a107953cb9b28eac8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_queue.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_queue.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e80ae442804f130d9dd5bdc201df6fc119e895e5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_queue.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_replay.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_replay.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..511b5ba52fe23aa991d89384b08d8cedd5e42ec3
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_replay.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_retry.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f9b75322e4bf5569cb3b02754a17ce5f6924bdd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_retry.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c232eb988d4e9951ba042919dd55f6583a61d53
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a3529d086462fcc2cc06fab9a66a56ce201f9f3
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_serde.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_serde.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3bf926bf6224a1150d3bb2beb4a2561970e7ffd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_serde.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43a76f33c0307bb433b658ce28237c81fc7b0ccf
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_typing.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_typing.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..787bf3ddc1c2f1115a371dcedca382ea193c93ca
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/_internal/__pycache__/_typing.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_cache.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9c451474b96509db622e1197a4a95d9a21ca4a2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_cache.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from collections.abc import Hashable, Mapping, Sequence
+from typing import Any
+
+
+def _freeze(obj: Any, depth: int = 10) -> Hashable:
+ if isinstance(obj, Hashable) or depth <= 0:
+ # already hashable, no need to freeze
+ return obj
+ elif isinstance(obj, Mapping):
+ # sort keys so {"a":1,"b":2} == {"b":2,"a":1}
+ return tuple(sorted((k, _freeze(v, depth - 1)) for k, v in obj.items()))
+ elif isinstance(obj, Sequence):
+ return tuple(_freeze(x, depth - 1) for x in obj)
+ # numpy / pandas etc. can provide their own .tobytes()
+ elif hasattr(obj, "tobytes"):
+ return (
+ type(obj).__name__,
+ obj.tobytes(),
+ obj.shape if hasattr(obj, "shape") else None,
+ )
+ return obj # strings, ints, dataclasses with frozen=True, etc.
+
+
+def default_cache_key(*args: Any, **kwargs: Any) -> str | bytes:
+ """Default cache key function that uses the arguments and keyword arguments to generate a hashable key."""
+ import pickle
+
+ # protocol 5 strikes a good balance between speed and size
+ return pickle.dumps((_freeze(args), _freeze(kwargs)), protocol=5, fix_imports=False)
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_config.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bb9128da7afb66046fc575c7a06c809019e5df0
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_config.py
@@ -0,0 +1,368 @@
+from __future__ import annotations
+
+from collections import ChainMap
+from collections.abc import Sequence
+from os import getenv
+from typing import Any, cast
+
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ BaseCallbackManager,
+ CallbackManager,
+ Callbacks,
+)
+from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables.config import (
+ CONFIG_KEYS,
+ COPIABLE_KEYS,
+ var_child_runnable_config,
+)
+from langgraph.checkpoint.base import CheckpointMetadata
+
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ NS_END,
+ NS_SEP,
+)
+
+DEFAULT_RECURSION_LIMIT = int(getenv("LANGGRAPH_DEFAULT_RECURSION_LIMIT", "10007"))
+DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT = int(
+ getenv("LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT", "5000")
+)
+
+
+def recast_checkpoint_ns(ns: str) -> str:
+ """Remove task IDs from checkpoint namespace.
+
+ Args:
+ ns: The checkpoint namespace with task IDs.
+
+ Returns:
+ str: The checkpoint namespace without task IDs.
+ """
+ return NS_SEP.join(
+ part.split(NS_END)[0] for part in ns.split(NS_SEP) if not part.isdigit()
+ )
+
+
+def patch_configurable(
+ config: RunnableConfig | None, patch: dict[str, Any]
+) -> RunnableConfig:
+ if config is None:
+ return {CONF: patch}
+ elif CONF not in config:
+ return {**config, CONF: patch}
+ else:
+ return {**config, CONF: {**config[CONF], **patch}}
+
+
+def patch_checkpoint_map(
+ config: RunnableConfig | None, metadata: CheckpointMetadata | None
+) -> RunnableConfig:
+ if config is None:
+ return config
+ elif parents := (metadata.get("parents") if metadata else None):
+ conf = config[CONF]
+ return patch_configurable(
+ config,
+ {
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **parents,
+ conf[CONFIG_KEY_CHECKPOINT_NS]: conf[CONFIG_KEY_CHECKPOINT_ID],
+ },
+ },
+ )
+ else:
+ return config
+
+
+def merge_configs(*configs: RunnableConfig | None) -> RunnableConfig:
+ """Merge multiple configs into one.
+
+ Args:
+ *configs: The configs to merge.
+
+ Returns:
+ RunnableConfig: The merged config.
+ """
+ base: RunnableConfig = {}
+ # Even though the keys aren't literals, this is correct
+ # because both dicts are the same type
+ for config in configs:
+ if config is None:
+ continue
+ for key, value in config.items():
+ if not value:
+ continue
+ if key == "metadata":
+ if base_value := base.get(key):
+ base[key] = {**base_value, **value} # type: ignore
+ else:
+ base[key] = value # type: ignore[literal-required]
+ elif key == "tags":
+ if base_value := base.get(key):
+ base[key] = [*base_value, *value] # type: ignore
+ else:
+ base[key] = value # type: ignore[literal-required]
+ elif key == CONF:
+ if base_value := base.get(key):
+ base[key] = {**base_value, **value} # type: ignore[dict-item]
+ else:
+ base[key] = value
+ elif key == "callbacks":
+ base_callbacks = base.get("callbacks")
+ # callbacks can be either None, list[handler] or manager
+ # so merging two callbacks values has 6 cases
+ if isinstance(value, list):
+ if base_callbacks is None:
+ base["callbacks"] = value.copy()
+ elif isinstance(base_callbacks, list):
+ base["callbacks"] = base_callbacks + value
+ else:
+ # base_callbacks is a manager
+ mngr = base_callbacks.copy()
+ for callback in value:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ elif isinstance(value, BaseCallbackManager):
+ # value is a manager
+ if base_callbacks is None:
+ base["callbacks"] = value.copy()
+ elif isinstance(base_callbacks, list):
+ mngr = value.copy()
+ for callback in base_callbacks:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ else:
+ # base_callbacks is also a manager
+ base["callbacks"] = base_callbacks.merge(value)
+ else:
+ raise NotImplementedError
+ elif key == "recursion_limit":
+ if config["recursion_limit"] != DEFAULT_RECURSION_LIMIT:
+ base["recursion_limit"] = config["recursion_limit"]
+ else:
+ base[key] = config[key] # type: ignore[literal-required]
+ if CONF not in base:
+ base[CONF] = {}
+ return base
+
+
+def patch_config(
+ config: RunnableConfig | None,
+ *,
+ callbacks: Callbacks = None,
+ recursion_limit: int | None = None,
+ max_concurrency: int | None = None,
+ run_name: str | None = None,
+ configurable: dict[str, Any] | None = None,
+) -> RunnableConfig:
+ """Patch a config with new values.
+
+ Args:
+ config: The config to patch.
+ callbacks: The callbacks to set.
+ recursion_limit: The recursion limit to set.
+ max_concurrency: The max number of concurrent steps to run, which also applies to parallelized steps.
+ run_name: The run name to set.
+ configurable: The configurable to set.
+
+ Returns:
+ RunnableConfig: The patched config.
+ """
+ config = config.copy() if config is not None else {}
+ if callbacks is not None:
+ # If we're replacing callbacks, we need to unset run_name
+ # As that should apply only to the same run as the original callbacks
+ config["callbacks"] = callbacks
+ if "run_name" in config:
+ del config["run_name"]
+ if "run_id" in config:
+ del config["run_id"]
+ if recursion_limit is not None:
+ config["recursion_limit"] = recursion_limit
+ if max_concurrency is not None:
+ config["max_concurrency"] = max_concurrency
+ if run_name is not None:
+ config["run_name"] = run_name
+ if configurable is not None:
+ config[CONF] = {**config.get(CONF, {}), **configurable}
+ return config
+
+
+def get_callback_manager_for_config(
+ config: RunnableConfig, tags: Sequence[str] | None = None
+) -> CallbackManager:
+ """Get a callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ CallbackManager: The callback manager.
+ """
+ from langchain_core.callbacks.manager import CallbackManager
+
+ # merge tags
+ all_tags = config.get("tags")
+ if all_tags is not None and tags is not None:
+ all_tags = [*all_tags, *tags]
+ elif tags is not None:
+ all_tags = list(tags)
+ # use existing callbacks if they exist
+ if (callbacks := config.get("callbacks")) and isinstance(
+ callbacks, CallbackManager
+ ):
+ if all_tags:
+ callbacks.add_tags(all_tags)
+ if metadata := config.get("metadata"):
+ callbacks.add_metadata(metadata)
+ manager = callbacks
+ else:
+ # otherwise create a new manager
+ manager = CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=all_tags,
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_tracing_metadata_defaults(config),
+ )
+ return manager
+
+
+def get_async_callback_manager_for_config(
+ config: RunnableConfig,
+ tags: Sequence[str] | None = None,
+) -> AsyncCallbackManager:
+ """Get an async callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ AsyncCallbackManager: The async callback manager.
+ """
+ from langchain_core.callbacks.manager import AsyncCallbackManager
+
+ # merge tags
+ all_tags = config.get("tags")
+ if all_tags is not None and tags is not None:
+ all_tags = [*all_tags, *tags]
+ elif tags is not None:
+ all_tags = list(tags)
+ # use existing callbacks if they exist
+ if (callbacks := config.get("callbacks")) and isinstance(
+ callbacks, AsyncCallbackManager
+ ):
+ if all_tags:
+ callbacks.add_tags(all_tags)
+ if metadata := config.get("metadata"):
+ callbacks.add_metadata(metadata)
+ manager = callbacks
+ else:
+ # otherwise create a new manager
+ manager = AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=all_tags,
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_tracing_metadata_defaults(config),
+ )
+ return manager
+
+
+def _is_not_empty(value: Any) -> bool:
+ if isinstance(value, (list, tuple, dict)):
+ return len(value) > 0
+ else:
+ return value is not None
+
+
+def ensure_config(*configs: RunnableConfig | None) -> RunnableConfig:
+ """Return a config with all keys, merging any provided configs.
+
+ Args:
+ *configs: Configs to merge before ensuring defaults.
+
+ Returns:
+ RunnableConfig: The merged and ensured config.
+ """
+ empty = RunnableConfig(
+ tags=[],
+ metadata=ChainMap(),
+ callbacks=None,
+ recursion_limit=DEFAULT_RECURSION_LIMIT,
+ configurable={},
+ )
+ if var_config := var_child_runnable_config.get():
+ empty.update(
+ {
+ k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
+ for k, v in var_config.items()
+ if _is_not_empty(v)
+ },
+ )
+ for config in configs:
+ if config is None:
+ continue
+ for k, v in config.items():
+ if _is_not_empty(v) and k in CONFIG_KEYS:
+ if k == CONF:
+ empty[k] = cast(dict, v).copy()
+ else:
+ empty[k] = v # type: ignore[literal-required]
+ for k, v in config.items():
+ if _is_not_empty(v) and k not in CONFIG_KEYS:
+ empty[CONF][k] = v
+
+ configurable = empty.get("configurable")
+ metadata = empty.get("metadata")
+ if configurable and metadata is not None:
+ for key in _PROPAGATE_TO_METADATA:
+ if key in metadata:
+ continue
+ value = configurable.get(key)
+ if value:
+ metadata[key] = value
+ return empty
+
+
+_OMIT = ("key", "token", "secret", "password", "auth")
+
+
+def _exclude_as_metadata(key: str, value: Any) -> bool:
+ key_lower = key.casefold()
+ return (
+ key.startswith("__")
+ or not isinstance(value, (str, int, float, bool))
+ or any(substr in key_lower for substr in _OMIT)
+ )
+
+
+def _get_tracing_metadata_defaults(
+ config: RunnableConfig,
+) -> dict[str, Any] | None:
+ """Get tracer-only metadata defaults from configurable values."""
+ configurable = config.get("configurable")
+ if not configurable:
+ return None
+ metadata: dict[str, Any] = {}
+ for key, value in configurable.items():
+ if _exclude_as_metadata(key, value):
+ continue
+ metadata[key] = value
+ return metadata or None
+
+
+_PROPAGATE_TO_METADATA = frozenset(
+ (
+ "thread_id",
+ "checkpoint_id",
+ "checkpoint_ns",
+ "task_id",
+ "run_id",
+ "assistant_id",
+ "graph_id",
+ )
+)
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_constants.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..360f7f275bb412e7557ebe29182c245d8399f31e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_constants.py
@@ -0,0 +1,131 @@
+"""Constants used for Pregel operations."""
+
+import sys
+from typing import Literal, cast
+
+# --- Reserved write keys ---
+INPUT = sys.intern("__input__")
+# for values passed as input to the graph
+INTERRUPT = sys.intern("__interrupt__")
+# for dynamic interrupts raised by nodes
+RESUME = sys.intern("__resume__")
+# for values passed to resume a node after an interrupt
+ERROR = sys.intern("__error__")
+# for errors raised by nodes
+ERROR_SOURCE_NODE = sys.intern("__error_source_node__")
+# failed source node name for node-level error handlers
+# value format in pending writes: `(task_id, ERROR_SOURCE_NODE, node_name: str)`
+NO_WRITES = sys.intern("__no_writes__")
+# marker to signal node didn't write anything
+TASKS = sys.intern("__pregel_tasks")
+# for Send objects returned by nodes/edges, corresponds to PUSH below
+RETURN = sys.intern("__return__")
+# for writes of a task where we simply record the return value
+PREVIOUS = sys.intern("__previous__")
+# the implicit branch that handles each node's Control values
+
+
+# --- Reserved cache namespaces ---
+CACHE_NS_WRITES = sys.intern("__pregel_ns_writes")
+# cache namespace for node writes
+
+# --- Reserved config.configurable keys ---
+CONFIG_KEY_SEND = sys.intern("__pregel_send")
+# holds the `write` function that accepts writes to state/edges/reserved keys
+CONFIG_KEY_READ = sys.intern("__pregel_read")
+# holds the `read` function that returns a copy of the current state
+CONFIG_KEY_CALL = sys.intern("__pregel_call")
+# holds the `call` function that accepts a node/func, args and returns a future
+CONFIG_KEY_CHECKPOINTER = sys.intern("__pregel_checkpointer")
+# holds a `BaseCheckpointSaver` passed from parent graph to child graphs
+CONFIG_KEY_STREAM = sys.intern("__pregel_stream")
+# holds a `StreamProtocol` passed from parent graph to child graphs
+CONFIG_KEY_CACHE = sys.intern("__pregel_cache")
+# holds a `BaseCache` made available to subgraphs
+CONFIG_KEY_RESUMING = sys.intern("__pregel_resuming")
+# holds a boolean indicating if subgraphs should resume from a previous checkpoint
+CONFIG_KEY_REPLAY_STATE = sys.intern("__pregel_replay_state")
+# holds a ReplayState tracking the parent checkpoint_id upper bound and which
+# subgraph namespaces have already loaded their pre-replay checkpoint
+CONFIG_KEY_TASK_ID = sys.intern("__pregel_task_id")
+# holds the task ID for the current task
+CONFIG_KEY_THREAD_ID = sys.intern("thread_id")
+# holds the thread ID for the current invocation
+CONFIG_KEY_CHECKPOINT_MAP = sys.intern("checkpoint_map")
+# holds a mapping of checkpoint_ns -> checkpoint_id for parent graphs
+CONFIG_KEY_CHECKPOINT_ID = sys.intern("checkpoint_id")
+# holds the current checkpoint_id, if any
+CONFIG_KEY_CHECKPOINT_NS = sys.intern("checkpoint_ns")
+# holds the current checkpoint_ns, "" for root graph
+CONFIG_KEY_NODE_FINISHED = sys.intern("__pregel_node_finished")
+# holds a callback to be called when a node is finished
+CONFIG_KEY_TIMED_ATTEMPT_OBSERVER = sys.intern("__pregel_timed_attempt_observer")
+# holds a callback to be called when an idle-timed node attempt starts or finishes
+CONFIG_KEY_SCRATCHPAD = sys.intern("__pregel_scratchpad")
+# holds a mutable dict for temporary storage scoped to the current task
+CONFIG_KEY_RUNNER_SUBMIT = sys.intern("__pregel_runner_submit")
+# holds a function that receives tasks from runner, executes them and returns results
+CONFIG_KEY_DURABILITY = sys.intern("__pregel_durability")
+# holds the durability mode, one of "sync", "async", or "exit"
+CONFIG_KEY_RUNTIME = sys.intern("__pregel_runtime")
+# holds a `Runtime` instance with context, store, stream writer, etc.
+CONFIG_KEY_RESUME_MAP = sys.intern("__pregel_resume_map")
+# holds a mapping of task ns -> resume value for resuming tasks
+CONFIG_KEY_STREAM_MESSAGES_V2 = sys.intern("__pregel_stream_messages_v2")
+# when True, attach StreamMessagesHandlerV2 so content-block (v2) events
+# flow through stream_mode="messages"; set by StreamingHandler only.
+CONFIG_KEY_NODE_ERROR = sys.intern("__pregel_node_error")
+# holds a `NodeError` (failed source node + exception) for the current
+# node-level error handler invocation, injected when handler signature
+# requests `error: NodeError`
+
+# --- Other constants ---
+PUSH = sys.intern("__pregel_push")
+# denotes push-style tasks, ie. those created by Send objects
+PULL = sys.intern("__pregel_pull")
+# denotes pull-style tasks, ie. those triggered by edges
+NS_SEP = sys.intern("|")
+# for checkpoint_ns, separates each level (ie. graph|subgraph|subsubgraph)
+NS_END = sys.intern(":")
+# for checkpoint_ns, for each level, separates the namespace from the task_id
+CONF = cast(Literal["configurable"], sys.intern("configurable"))
+# key for the configurable dict in RunnableConfig
+NULL_TASK_ID = sys.intern("00000000-0000-0000-0000-000000000000")
+# the task_id to use for writes that are not associated with a task
+OVERWRITE = sys.intern("__overwrite__")
+# dict key for the overwrite value, used as `{'__overwrite__': value}`
+
+# redefined to avoid circular import with langgraph.constants
+_TAG_HIDDEN = sys.intern("langsmith:hidden")
+
+RESERVED = {
+ _TAG_HIDDEN,
+ # reserved write keys
+ INPUT,
+ INTERRUPT,
+ RESUME,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ NO_WRITES,
+ # reserved config.configurable keys
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_READ,
+ CONFIG_KEY_CHECKPOINTER,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_RESUMING,
+ CONFIG_KEY_REPLAY_STATE,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_TIMED_ATTEMPT_OBSERVER,
+ CONFIG_KEY_RESUME_MAP,
+ CONFIG_KEY_STREAM_MESSAGES_V2,
+ # other constants
+ PUSH,
+ PULL,
+ NS_SEP,
+ NS_END,
+ CONF,
+}
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_fields.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ada8dfa0cb053a98b5c1ce9d9dca3dcedda2775
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_fields.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+import dataclasses
+import types
+import weakref
+from collections.abc import Generator, Sequence
+from typing import Annotated, Any, Optional, Union, get_origin, get_type_hints
+
+from pydantic import BaseModel
+from typing_extensions import NotRequired, ReadOnly, Required
+
+from langgraph._internal._typing import MISSING
+
+
+def _is_optional_type(type_: Any) -> bool:
+ """Check if a type is Optional."""
+
+ # Handle new union syntax (PEP 604): str | None
+ if isinstance(type_, types.UnionType):
+ return any(
+ arg is type(None) or _is_optional_type(arg) for arg in type_.__args__
+ )
+
+ if hasattr(type_, "__origin__") and hasattr(type_, "__args__"):
+ origin = get_origin(type_)
+ if origin is Optional:
+ return True
+ if origin is Union:
+ return any(
+ arg is type(None) or _is_optional_type(arg) for arg in type_.__args__
+ )
+ if origin is Annotated:
+ return _is_optional_type(type_.__args__[0])
+ return origin is None
+ if hasattr(type_, "__bound__") and type_.__bound__ is not None:
+ return _is_optional_type(type_.__bound__)
+ return type_ is None
+
+
+def _is_required_type(type_: Any) -> bool | None:
+ """Check if an annotation is marked as Required/NotRequired.
+
+ Returns:
+ - True if required
+ - False if not required
+ - None if not annotated with either
+ """
+ origin = get_origin(type_)
+ if origin is Required:
+ return True
+ if origin is NotRequired:
+ return False
+ if origin is Annotated or getattr(origin, "__args__", None):
+ # See https://typing.readthedocs.io/en/latest/spec/typeddict.html#interaction-with-annotated
+ return _is_required_type(type_.__args__[0])
+ return None
+
+
+def _is_readonly_type(type_: Any) -> bool:
+ """Check if an annotation is marked as ReadOnly.
+
+ Returns:
+ - True if is read only
+ - False if not read only
+ """
+
+ # See: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typing-readonly-type-qualifier
+ origin = get_origin(type_)
+ if origin is Annotated:
+ return _is_readonly_type(type_.__args__[0])
+ if origin is ReadOnly:
+ return True
+ return False
+
+
+_DEFAULT_KEYS: frozenset[str] = frozenset()
+
+
+def get_field_default(name: str, type_: Any, schema: type[Any]) -> Any:
+ """Determine the default value for a field in a state schema.
+
+ This is based on:
+ If TypedDict:
+ - Required/NotRequired
+ - total=False -> everything optional
+ - Type annotation (Optional/Union[None])
+ """
+ optional_keys = getattr(schema, "__optional_keys__", _DEFAULT_KEYS)
+ irq = _is_required_type(type_)
+ if name in optional_keys:
+ # Either total=False or explicit NotRequired.
+ # No type annotation trumps this.
+ if irq:
+ # Unless it's earlier versions of python & explicit Required
+ return ...
+ return None
+ if irq is not None:
+ if irq:
+ # Handle Required[]
+ # (we already handled NotRequired and total=False)
+ return ...
+ # Handle NotRequired[] for earlier versions of python
+ return None
+ if dataclasses.is_dataclass(schema):
+ field_info = next(
+ (f for f in dataclasses.fields(schema) if f.name == name), None
+ )
+ if field_info:
+ if (
+ field_info.default is not dataclasses.MISSING
+ and field_info.default is not ...
+ ):
+ return field_info.default
+ elif field_info.default_factory is not dataclasses.MISSING:
+ return field_info.default_factory()
+ # Note, we ignore ReadOnly attributes,
+ # as they don't make much sense. (we don't care if you mutate the state in your node)
+ # and mutating state in your node has no effect on our graph state.
+ # Base case is the annotation
+ if _is_optional_type(type_):
+ return None
+ return ...
+
+
+def get_enhanced_type_hints(
+ type: type[Any],
+) -> Generator[tuple[str, Any, Any, str | None], None, None]:
+ """Attempt to extract default values and descriptions from provided type, used for config schema."""
+ for name, typ in get_type_hints(type).items():
+ default = None
+ description = None
+
+ # Pydantic models
+ try:
+ if hasattr(type, "model_fields") and name in type.model_fields:
+ field = type.model_fields[name]
+
+ if hasattr(field, "description") and field.description is not None:
+ description = field.description
+
+ if hasattr(field, "default") and field.default is not None:
+ default = field.default
+ if (
+ hasattr(default, "__class__")
+ and getattr(default.__class__, "__name__", "")
+ == "PydanticUndefinedType"
+ ):
+ default = None
+
+ except (AttributeError, KeyError, TypeError):
+ pass
+
+ # TypedDict, dataclass
+ try:
+ if hasattr(type, "__dict__"):
+ type_dict = getattr(type, "__dict__")
+
+ if name in type_dict:
+ default = type_dict[name]
+ except (AttributeError, KeyError, TypeError):
+ pass
+
+ yield name, typ, default, description
+
+
+def get_update_as_tuples(input: Any, keys: Sequence[str]) -> list[tuple[str, Any]]:
+ """Get Pydantic state update as a list of (key, value) tuples."""
+ if isinstance(input, BaseModel):
+ keep = input.model_fields_set
+ defaults = {k: v.default for k, v in type(input).model_fields.items()}
+ else:
+ keep = None
+ defaults = {}
+
+ # NOTE: This behavior for Pydantic is somewhat inelegant,
+ # but we keep around for backwards compatibility
+ # if input is a Pydantic model, only update values
+ # that are different from the default values or in the keep set
+ return [
+ (k, value)
+ for k in keys
+ if (value := getattr(input, k, MISSING)) is not MISSING
+ and (
+ value is not None
+ or defaults.get(k, MISSING) is not None
+ or (keep is not None and k in keep)
+ )
+ ]
+
+
+ANNOTATED_KEYS_CACHE: weakref.WeakKeyDictionary[type[Any], tuple[str, ...]] = (
+ weakref.WeakKeyDictionary()
+)
+
+
+def get_cached_annotated_keys(obj: type[Any]) -> tuple[str, ...]:
+ """Return cached annotated keys for a Python class."""
+ if obj in ANNOTATED_KEYS_CACHE:
+ return ANNOTATED_KEYS_CACHE[obj]
+ if isinstance(obj, type):
+ keys: list[str] = []
+ for base in reversed(obj.__mro__):
+ ann = base.__dict__.get("__annotations__")
+ # In Python 3.14+, Pydantic models use descriptors for __annotations__
+ # so we need to fall back to getattr if __dict__.get returns None
+ if ann is None:
+ ann = getattr(base, "__annotations__", None)
+ if ann is None or isinstance(ann, types.GetSetDescriptorType):
+ continue
+ keys.extend(ann.keys())
+ return ANNOTATED_KEYS_CACHE.setdefault(obj, tuple(keys))
+ else:
+ raise TypeError(f"Expected a type, got {type(obj)}. ")
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_future.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_future.py
new file mode 100644
index 0000000000000000000000000000000000000000..31c56bf4bfab0c5edec7e42e6c816acd2ad4637d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_future.py
@@ -0,0 +1,220 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import contextvars
+import inspect
+import sys
+import types
+from collections.abc import Awaitable, Coroutine, Generator
+from typing import TypeVar, cast
+
+T = TypeVar("T")
+AnyFuture = asyncio.Future | concurrent.futures.Future
+
+CONTEXT_NOT_SUPPORTED = sys.version_info < (3, 11)
+EAGER_NOT_SUPPORTED = sys.version_info < (3, 12)
+
+
+def _get_loop(fut: asyncio.Future) -> asyncio.AbstractEventLoop:
+ # Tries to call Future.get_loop() if it's available.
+ # Otherwise fallbacks to using the old '_loop' property.
+ try:
+ get_loop = fut.get_loop
+ except AttributeError:
+ pass
+ else:
+ return get_loop()
+ return fut._loop
+
+
+def _convert_future_exc(exc: BaseException) -> BaseException:
+ exc_class = type(exc)
+ if exc_class is concurrent.futures.CancelledError:
+ return asyncio.CancelledError(*exc.args)
+ elif exc_class is concurrent.futures.TimeoutError:
+ return asyncio.TimeoutError(*exc.args)
+ elif exc_class is concurrent.futures.InvalidStateError:
+ return asyncio.InvalidStateError(*exc.args)
+ else:
+ return exc
+
+
+def _set_concurrent_future_state(
+ concurrent: concurrent.futures.Future,
+ source: AnyFuture,
+) -> None:
+ """Copy state from a future to a concurrent.futures.Future."""
+ assert source.done()
+ if source.cancelled():
+ concurrent.cancel()
+ if not concurrent.set_running_or_notify_cancel():
+ return
+ exception = source.exception()
+ if exception is not None:
+ concurrent.set_exception(_convert_future_exc(exception))
+ else:
+ result = source.result()
+ concurrent.set_result(result)
+
+
+def _copy_future_state(source: AnyFuture, dest: asyncio.Future) -> None:
+ """Internal helper to copy state from another Future.
+
+ The other Future may be a concurrent.futures.Future.
+ """
+ if dest.done():
+ return
+ assert source.done()
+ if dest.cancelled():
+ return
+ if source.cancelled():
+ dest.cancel()
+ else:
+ exception = source.exception()
+ if exception is not None:
+ dest.set_exception(_convert_future_exc(exception))
+ else:
+ result = source.result()
+ dest.set_result(result)
+
+
+def _chain_future(source: AnyFuture, destination: AnyFuture) -> None:
+ """Chain two futures so that when one completes, so does the other.
+
+ The result (or exception) of source will be copied to destination.
+ If destination is cancelled, source gets cancelled too.
+ Compatible with both asyncio.Future and concurrent.futures.Future.
+ """
+ if not asyncio.isfuture(source) and not isinstance(
+ source, concurrent.futures.Future
+ ):
+ raise TypeError("A future is required for source argument")
+ if not asyncio.isfuture(destination) and not isinstance(
+ destination, concurrent.futures.Future
+ ):
+ raise TypeError("A future is required for destination argument")
+ source_loop = _get_loop(source) if asyncio.isfuture(source) else None
+ dest_loop = _get_loop(destination) if asyncio.isfuture(destination) else None
+
+ def _set_state(future: AnyFuture, other: AnyFuture) -> None:
+ if asyncio.isfuture(future):
+ _copy_future_state(other, future)
+ else:
+ _set_concurrent_future_state(future, other)
+
+ def _call_check_cancel(destination: AnyFuture) -> None:
+ if destination.cancelled():
+ if source_loop is None or source_loop is dest_loop:
+ source.cancel()
+ else:
+ source_loop.call_soon_threadsafe(source.cancel)
+
+ def _call_set_state(source: AnyFuture) -> None:
+ if destination.cancelled() and dest_loop is not None and dest_loop.is_closed():
+ return
+ if dest_loop is None or dest_loop is source_loop:
+ _set_state(destination, source)
+ else:
+ if dest_loop.is_closed():
+ return
+ dest_loop.call_soon_threadsafe(_set_state, destination, source)
+
+ destination.add_done_callback(_call_check_cancel)
+ source.add_done_callback(_call_set_state)
+
+
+def chain_future(source: AnyFuture, destination: AnyFuture) -> AnyFuture:
+ # adapted from asyncio.run_coroutine_threadsafe
+ try:
+ _chain_future(source, destination)
+ return destination
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except BaseException as exc:
+ if isinstance(destination, concurrent.futures.Future):
+ if destination.set_running_or_notify_cancel():
+ destination.set_exception(exc)
+ else:
+ destination.set_exception(exc)
+ raise
+
+
+def _ensure_future(
+ coro_or_future: Coroutine[None, None, T] | Awaitable[T],
+ *,
+ loop: asyncio.AbstractEventLoop,
+ name: str | None = None,
+ context: contextvars.Context | None = None,
+ lazy: bool = True,
+) -> asyncio.Task[T]:
+ called_wrap_awaitable = False
+ if not asyncio.iscoroutine(coro_or_future):
+ if inspect.isawaitable(coro_or_future):
+ coro_or_future = cast(
+ Coroutine[None, None, T], _wrap_awaitable(coro_or_future)
+ )
+ called_wrap_awaitable = True
+ else:
+ raise TypeError(
+ "An asyncio.Future, a coroutine or an awaitable is required."
+ f" Got {type(coro_or_future).__name__} instead."
+ )
+
+ try:
+ if CONTEXT_NOT_SUPPORTED:
+ return loop.create_task(coro_or_future, name=name)
+ elif EAGER_NOT_SUPPORTED or lazy:
+ return loop.create_task(coro_or_future, name=name, context=context)
+ else:
+ return asyncio.eager_task_factory(
+ loop, coro_or_future, name=name, context=context
+ )
+ except RuntimeError:
+ if not called_wrap_awaitable:
+ coro_or_future.close()
+ raise
+
+
+@types.coroutine
+def _wrap_awaitable(awaitable: Awaitable[T]) -> Generator[None, None, T]:
+ """Helper for asyncio.ensure_future().
+
+ Wraps awaitable (an object with __await__) into a coroutine
+ that will later be wrapped in a Task by ensure_future().
+ """
+ return (yield from awaitable.__await__())
+
+
+def run_coroutine_threadsafe(
+ coro: Coroutine[None, None, T],
+ loop: asyncio.AbstractEventLoop,
+ *,
+ lazy: bool,
+ name: str | None = None,
+ context: contextvars.Context | None = None,
+) -> asyncio.Future[T]:
+ """Submit a coroutine object to a given event loop.
+
+ Return an asyncio.Future to access the result.
+ """
+
+ if asyncio._get_running_loop() is loop:
+ return _ensure_future(coro, loop=loop, name=name, context=context, lazy=lazy)
+ else:
+ future: asyncio.Future[T] = asyncio.Future(loop=loop)
+
+ def callback() -> None:
+ try:
+ chain_future(
+ _ensure_future(coro, loop=loop, name=name, context=context),
+ future,
+ )
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except BaseException as exc:
+ future.set_exception(exc)
+ raise
+
+ loop.call_soon_threadsafe(callback, context=context)
+ return future
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_pydantic.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_pydantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d93f085e1aac6eb7610c6dd060c057f3fb1dd1f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_pydantic.py
@@ -0,0 +1,275 @@
+from __future__ import annotations
+
+import sys
+import typing
+import warnings
+from contextlib import nullcontext
+from dataclasses import is_dataclass
+from functools import lru_cache
+from typing import (
+ Any,
+ cast,
+ overload,
+)
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ RootModel,
+)
+from pydantic import (
+ create_model as _create_model_base,
+)
+from pydantic.fields import FieldInfo
+from pydantic.json_schema import (
+ DEFAULT_REF_TEMPLATE,
+ GenerateJsonSchema,
+ JsonSchemaMode,
+)
+from typing_extensions import TypedDict
+
+
+@overload
+def get_fields(model: type[BaseModel]) -> dict[str, FieldInfo]: ...
+
+
+@overload
+def get_fields(model: BaseModel) -> dict[str, FieldInfo]: ...
+
+
+def get_fields(
+ model: type[BaseModel] | BaseModel,
+) -> dict[str, FieldInfo]:
+ """Get the field names of a Pydantic model."""
+ if hasattr(model, "model_fields"):
+ return model.model_fields
+
+ if hasattr(model, "__fields__"):
+ return model.__fields__
+ msg = f"Expected a Pydantic model. Got {type(model)}"
+ raise TypeError(msg)
+
+
+_SchemaConfig = ConfigDict(
+ arbitrary_types_allowed=True, frozen=True, protected_namespaces=()
+)
+
+NO_DEFAULT = object()
+
+
+def _create_root_model(
+ name: str,
+ type_: Any,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ """Create a base class."""
+
+ def schema(
+ cls: type[BaseModel],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ ) -> dict[str, Any]:
+ # Complains about schema not being defined in superclass
+ schema_ = super(cls, cls).schema( # type: ignore[misc]
+ by_alias=by_alias, ref_template=ref_template
+ )
+ schema_["title"] = name
+ return schema_
+
+ def model_json_schema(
+ cls: type[BaseModel],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+ mode: JsonSchemaMode = "validation",
+ ) -> dict[str, Any]:
+ # Complains about model_json_schema not being defined in superclass
+ schema_ = super(cls, cls).model_json_schema( # type: ignore[misc]
+ by_alias=by_alias,
+ ref_template=ref_template,
+ schema_generator=schema_generator,
+ mode=mode,
+ )
+ schema_["title"] = name
+ return schema_
+
+ base_class_attributes = {
+ "__annotations__": {"root": type_},
+ "model_config": ConfigDict(arbitrary_types_allowed=True),
+ "schema": classmethod(schema),
+ "model_json_schema": classmethod(model_json_schema),
+ "__module__": module_name or "langchain_core.runnables.utils",
+ }
+
+ if default_ is not NO_DEFAULT:
+ base_class_attributes["root"] = default_
+ with warnings.catch_warnings():
+ custom_root_type = type(name, (RootModel,), base_class_attributes)
+ return cast("type[BaseModel]", custom_root_type)
+
+
+@lru_cache(maxsize=256)
+def _create_root_model_cached(
+ model_name: str,
+ type_: Any,
+ *,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ return _create_root_model(
+ model_name, type_, default_=default_, module_name=module_name
+ )
+
+
+@lru_cache(maxsize=256)
+def _create_model_cached(
+ model_name: str,
+ /,
+ **field_definitions: Any,
+) -> type[BaseModel]:
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
+
+
+# Reserved names should capture all the `public` names / methods that are
+# used by BaseModel internally. This will keep the reserved names up-to-date.
+# For reference, the reserved names are:
+# "construct", "copy", "dict", "from_orm", "json", "parse_file", "parse_obj",
+# "parse_raw", "schema", "schema_json", "update_forward_refs", "validate",
+# "model_computed_fields", "model_config", "model_construct", "model_copy",
+# "model_dump", "model_dump_json", "model_extra", "model_fields",
+# "model_fields_set", "model_json_schema", "model_parametrized_name",
+# "model_post_init", "model_rebuild", "model_validate", "model_validate_json",
+# "model_validate_strings"
+_RESERVED_NAMES = {key for key in dir(BaseModel) if not key.startswith("_")}
+
+
+def _remap_field_definitions(field_definitions: dict[str, Any]) -> dict[str, Any]:
+ """This remaps fields to avoid colliding with internal pydantic fields."""
+
+ remapped = {}
+ for key, value in field_definitions.items():
+ if key.startswith("_") or key in _RESERVED_NAMES:
+ # Let's add a prefix to avoid colliding with internal pydantic fields
+ if isinstance(value, FieldInfo):
+ msg = (
+ f"Remapping for fields starting with '_' or fields with a name "
+ f"matching a reserved name {_RESERVED_NAMES} is not supported if "
+ f" the field is a pydantic Field instance. Got {key}."
+ )
+ raise NotImplementedError(msg)
+ type_, default_ = value
+ remapped[f"private_{key}"] = (
+ type_,
+ Field(
+ default=default_,
+ alias=key,
+ serialization_alias=key,
+ title=key.lstrip("_").replace("_", " ").title(),
+ ),
+ )
+ else:
+ remapped[key] = value
+ return remapped
+
+
+def create_model(
+ model_name: str,
+ *,
+ field_definitions: dict[str, Any] | None = None,
+ root: Any | None = None,
+) -> type[BaseModel]:
+ """Create a pydantic model with the given field definitions.
+
+ Attention:
+ Please do not use outside of langchain packages. This API
+ is subject to change at any time.
+
+ Args:
+ model_name: The name of the model.
+ module_name: The name of the module where the model is defined.
+ This is used by Pydantic to resolve any forward references.
+ field_definitions: The field definitions for the model.
+ root: Type for a root model (RootModel)
+
+ Returns:
+ Type[BaseModel]: The created model.
+ """
+ field_definitions = field_definitions or {}
+
+ if root:
+ if field_definitions:
+ msg = (
+ "When specifying __root__ no other "
+ f"fields should be provided. Got {field_definitions}"
+ )
+ raise NotImplementedError(msg)
+
+ if isinstance(root, tuple):
+ kwargs = {"type_": root[0], "default_": root[1]}
+ else:
+ kwargs = {"type_": root}
+
+ try:
+ named_root_model = _create_root_model_cached(model_name, **kwargs)
+ except TypeError:
+ # something in the arguments into _create_root_model_cached is not hashable
+ named_root_model = _create_root_model(
+ model_name,
+ **kwargs,
+ )
+ return named_root_model
+
+ # No root, just field definitions
+ names = set(field_definitions.keys())
+
+ capture_warnings = False
+
+ for name in names:
+ # Also if any non-reserved name is used (e.g., model_id or model_name)
+ if name.startswith("model"):
+ capture_warnings = True
+
+ with warnings.catch_warnings() if capture_warnings else nullcontext():
+ if capture_warnings:
+ warnings.filterwarnings(action="ignore")
+ try:
+ return _create_model_cached(model_name, **field_definitions)
+ except TypeError:
+ # something in field definitions is not hashable
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
+
+
+def is_supported_by_pydantic(type_: Any) -> bool:
+ """Check if a given "complex" type is supported by pydantic.
+
+ This will return False for primitive types like int, str, etc.
+
+ The check is meant for container types like dataclasses, TypedDicts, etc.
+ """
+ if is_dataclass(type_):
+ return True
+
+ if isinstance(type_, type) and issubclass(type_, BaseModel):
+ return True
+
+ if hasattr(type_, "__orig_bases__"):
+ for base in type_.__orig_bases__:
+ if base is TypedDict:
+ return True
+ elif base is typing.TypedDict: # noqa: TID251
+ # ignoring TID251 since it's OK to use typing.TypedDict in this case.
+ # Pydantic supports typing.TypedDict from Python 3.12
+ # For older versions, only typing_extensions.TypedDict is supported.
+ if sys.version_info >= (3, 12):
+ return True
+ return False
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_queue.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_queue.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2cc02a772ad64ca10b67da30c05d88fc37bb9eb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_queue.py
@@ -0,0 +1,124 @@
+# type: ignore
+from __future__ import annotations
+
+import asyncio
+import queue
+import threading
+import types
+from collections import deque
+from time import monotonic
+
+
+class AsyncQueue(asyncio.Queue):
+ """Async unbounded FIFO queue with a wait() method.
+
+ Subclassed from asyncio.Queue, adding a wait() method."""
+
+ async def wait(self) -> None:
+ """If queue is empty, wait until an item is available.
+
+ Copied from Queue.get(), removing the call to .get_nowait(),
+ ie. this doesn't consume the item, just waits for it.
+ """
+ while self.empty():
+ getter = self._get_loop().create_future()
+ self._getters.append(getter)
+ try:
+ await getter
+ except BaseException:
+ getter.cancel() # Just in case getter is not done yet.
+ try:
+ # Clean self._getters from canceled getters.
+ self._getters.remove(getter)
+ except ValueError:
+ # The getter could be removed from self._getters by a
+ # previous put_nowait call.
+ pass
+ if not self.empty() and not getter.cancelled():
+ # We were woken up by put_nowait(), but can't take
+ # the call. Wake up the next in line.
+ self._wakeup_next(self._getters)
+ raise
+
+
+class Semaphore(threading.Semaphore):
+ """Semaphore subclass with a wait() method."""
+
+ def wait(self, blocking: bool = True, timeout: float | None = None):
+ """Block until the semaphore can be acquired, but don't acquire it."""
+ if not blocking and timeout is not None:
+ raise ValueError("can't specify timeout for non-blocking acquire")
+ rc = False
+ endtime = None
+ with self._cond:
+ while self._value == 0:
+ if not blocking:
+ break
+ if timeout is not None:
+ if endtime is None:
+ endtime = monotonic() + timeout
+ else:
+ timeout = endtime - monotonic()
+ if timeout <= 0:
+ break
+ self._cond.wait(timeout)
+ else:
+ rc = True
+ return rc
+
+
+class SyncQueue:
+ """Unbounded FIFO queue with a wait() method.
+ Adapted from pure Python implementation of queue.SimpleQueue.
+ """
+
+ def __init__(self):
+ self._queue = deque()
+ self._count = Semaphore(0)
+
+ def put(self, item, block=True, timeout=None):
+ """Put the item on the queue.
+
+ The optional 'block' and 'timeout' arguments are ignored, as this method
+ never blocks. They are provided for compatibility with the Queue class.
+ """
+ self._queue.append(item)
+ self._count.release()
+
+ def get(self, block=False, timeout=None):
+ """Remove and return an item from the queue.
+
+ If optional args 'block' is true and 'timeout' is None (the default),
+ block if necessary until an item is available. If 'timeout' is
+ a non-negative number, it blocks at most 'timeout' seconds and raises
+ the Empty exception if no item was available within that time.
+ Otherwise ('block' is false), return an item if one is immediately
+ available, else raise the Empty exception ('timeout' is ignored
+ in that case).
+ """
+ if timeout is not None and timeout < 0:
+ raise ValueError("'timeout' must be a non-negative number")
+ if not self._count.acquire(block, timeout):
+ raise queue.Empty
+ try:
+ return self._queue.popleft()
+ except IndexError:
+ raise queue.Empty
+
+ def wait(self, block=True, timeout=None):
+ """If queue is empty, wait until an item maybe is available,
+ but don't consume it.
+ """
+ if timeout is not None and timeout < 0:
+ raise ValueError("'timeout' must be a non-negative number")
+ self._count.wait(block, timeout)
+
+ def empty(self):
+ """Return True if the queue is empty, False otherwise (not reliable!)."""
+ return len(self._queue) == 0
+
+ def qsize(self):
+ """Return the approximate size of the queue (not reliable!)."""
+ return len(self._queue)
+
+ __class_getitem__ = classmethod(types.GenericAlias)
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_replay.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_replay.py
new file mode 100644
index 0000000000000000000000000000000000000000..a86c13319eb4584163c2fe18d86e70ca189c27dd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_replay.py
@@ -0,0 +1,90 @@
+"""Replay state for subgraph checkpoint loading during time-travel."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from langgraph._internal._constants import NS_END
+
+if TYPE_CHECKING:
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.checkpoint.base import BaseCheckpointSaver, CheckpointTuple
+
+
+class ReplayState:
+ """Tracks which subgraphs have already loaded their pre-replay checkpoint.
+
+ During a parent replay, each subgraph's first invocation should restore the
+ checkpoint from before the replay point. Subsequent invocations of the same
+ subgraph (e.g. in a loop) should use normal checkpoint loading so they pick
+ up freshly created checkpoints.
+
+ The single `ReplayState` instance is shared by reference across all derived
+ configs within one parent execution.
+ """
+
+ __slots__ = ("checkpoint_id", "_visited_ns")
+
+ def __init__(self, checkpoint_id: str) -> None:
+ self.checkpoint_id = checkpoint_id
+ # DO NOT CHANGE THIS VARIABLE – it may need to be rehydrated
+ # in other runtimes
+ self._visited_ns: set[str] = set()
+
+ def _is_first_visit(self, checkpoint_ns: str) -> bool:
+ """Return True the first time a subgraph namespace is seen.
+
+ The task-id suffix is stripped so that the same logical subgraph
+ (e.g. ``"sub_node"``) is recognized across loop iterations even
+ though each iteration has a different task id.
+ """
+ # "sub_node:task_id" -> "sub_node"
+ stable_ns = (
+ checkpoint_ns.rsplit(NS_END, 1)[0]
+ if NS_END in checkpoint_ns
+ else checkpoint_ns
+ )
+ if stable_ns in self._visited_ns:
+ return False
+ self._visited_ns.add(stable_ns)
+ return True
+
+ def get_checkpoint(
+ self,
+ checkpoint_ns: str,
+ checkpointer: BaseCheckpointSaver,
+ checkpoint_config: RunnableConfig,
+ ) -> CheckpointTuple | None:
+ """Load the right checkpoint for a subgraph during replay.
+
+ On the first call for a given subgraph namespace, returns the latest
+ checkpoint created *before* the replay point. On subsequent calls
+ (e.g. the same subgraph in a later loop iteration), falls back to
+ normal latest-checkpoint loading.
+ """
+ if self._is_first_visit(checkpoint_ns):
+ for saved in checkpointer.list(
+ checkpoint_config,
+ before={"configurable": {"checkpoint_id": self.checkpoint_id}},
+ limit=1,
+ ):
+ return saved
+ return None
+ return checkpointer.get_tuple(checkpoint_config)
+
+ async def aget_checkpoint(
+ self,
+ checkpoint_ns: str,
+ checkpointer: BaseCheckpointSaver,
+ checkpoint_config: RunnableConfig,
+ ) -> CheckpointTuple | None:
+ """Async version of `get_checkpoint`."""
+ if self._is_first_visit(checkpoint_ns):
+ async for saved in checkpointer.alist(
+ checkpoint_config,
+ before={"configurable": {"checkpoint_id": self.checkpoint_id}},
+ limit=1,
+ ):
+ return saved
+ return None
+ return await checkpointer.aget_tuple(checkpoint_config)
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_retry.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d4e41fd78fc046530246c05555864bcc50ea44a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_retry.py
@@ -0,0 +1,29 @@
+def default_retry_on(exc: Exception) -> bool:
+ import httpx
+ import requests
+
+ if isinstance(exc, ConnectionError):
+ return True
+ if isinstance(exc, httpx.HTTPStatusError):
+ return 500 <= exc.response.status_code < 600
+ if isinstance(exc, requests.HTTPError):
+ return 500 <= exc.response.status_code < 600 if exc.response else True
+ if isinstance(
+ exc,
+ (
+ ValueError,
+ TypeError,
+ ArithmeticError,
+ ImportError,
+ LookupError,
+ NameError,
+ SyntaxError,
+ RuntimeError,
+ ReferenceError,
+ StopIteration,
+ StopAsyncIteration,
+ OSError,
+ ),
+ ):
+ return False
+ return True
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_runnable.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_runnable.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c110b96f40d3847046d404c5315d1311da78d02
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_runnable.py
@@ -0,0 +1,942 @@
+from __future__ import annotations
+
+import asyncio
+import enum
+import inspect
+import sys
+import warnings
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Coroutine,
+ Generator,
+ Iterator,
+ Sequence,
+)
+from contextlib import AsyncExitStack, contextmanager
+from contextvars import Context, Token, copy_context
+from functools import partial, wraps
+from typing import (
+ Any,
+ Optional,
+ Protocol,
+ TypeGuard,
+ cast,
+)
+
+from langchain_core.runnables.base import (
+ Runnable,
+ RunnableConfig,
+ RunnableLambda,
+ RunnableParallel,
+ RunnableSequence,
+)
+from langchain_core.runnables.base import (
+ RunnableLike as LCRunnableLike,
+)
+from langchain_core.runnables.config import (
+ run_in_executor,
+ var_child_runnable_config,
+)
+from langchain_core.runnables.utils import Input, Output
+from langchain_core.tracers.langchain import LangChainTracer
+from langgraph.store.base import BaseStore
+
+from langgraph._internal._config import (
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ patch_config,
+)
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_NODE_ERROR,
+ CONFIG_KEY_RUNTIME,
+)
+from langgraph._internal._typing import MISSING
+from langgraph.errors import NodeError
+from langgraph.types import StreamWriter
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = None # type: ignore
+
+
+def _set_config_context(
+ config: RunnableConfig, run: Any = None
+) -> Token[RunnableConfig | None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+ """
+ config_token = var_child_runnable_config.set(config)
+ if run is not None:
+ from langsmith.run_helpers import _set_tracing_context
+
+ _set_tracing_context({"parent": run})
+ return config_token
+
+
+def _unset_config_context(token: Token[RunnableConfig | None], run: Any = None) -> None:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ token: The config token to reset.
+ """
+ var_child_runnable_config.reset(token)
+ if run is not None:
+ from langsmith.run_helpers import _set_tracing_context
+
+ _set_tracing_context(
+ {
+ "parent": None,
+ "project_name": None,
+ "tags": None,
+ "metadata": None,
+ "enabled": None,
+ "client": None,
+ }
+ )
+
+
+@contextmanager
+def set_config_context(
+ config: RunnableConfig, run: Any = None
+) -> Generator[Context, None, None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+ """
+ ctx = copy_context()
+ config_token = ctx.run(_set_config_context, config, run)
+ try:
+ yield ctx
+ finally:
+ ctx.run(_unset_config_context, config_token, run)
+
+
+def create_task_in_config_context(
+ coro_factory: Callable[[], Coroutine[Any, Any, Any]], config: RunnableConfig
+) -> asyncio.Task[Any]:
+ """Create an asyncio.Task that inherits `config` as the child runnable context.
+
+ `asyncio.create_task` snapshots the current contextvars onto the new task,
+ so calling `create_task` while the config context is set ensures the task
+ sees `config` via `var_child_runnable_config` and any tracing parent.
+ """
+ with set_config_context(config) as context:
+ return context.run(lambda: asyncio.create_task(coro_factory()))
+
+
+# Before Python 3.11 native StrEnum is not available
+class StrEnum(str, enum.Enum):
+ """A string enum."""
+
+
+# Special type to denote any type is accepted
+ANY_TYPE = object()
+
+ASYNCIO_ACCEPTS_CONTEXT = sys.version_info >= (3, 11)
+
+# List of keyword arguments that can be injected into nodes / tasks / tools at runtime.
+# A named argument may appear multiple times if it appears with distinct types.
+KWARGS_CONFIG_KEYS: tuple[tuple[str, tuple[Any, ...], str, Any], ...] = (
+ (
+ "config",
+ (
+ RunnableConfig,
+ "RunnableConfig",
+ Optional[RunnableConfig], # noqa: UP045
+ "Optional[RunnableConfig]",
+ inspect.Parameter.empty,
+ ),
+ # for now, use config directly, eventually, will pop off of Runtime
+ "N/A",
+ inspect.Parameter.empty,
+ ),
+ (
+ "writer",
+ (StreamWriter, "StreamWriter", inspect.Parameter.empty),
+ "stream_writer",
+ lambda _: None,
+ ),
+ (
+ "store",
+ (
+ BaseStore,
+ "BaseStore",
+ inspect.Parameter.empty,
+ ),
+ "store",
+ inspect.Parameter.empty,
+ ),
+ (
+ "store",
+ (
+ Optional[BaseStore], # noqa: UP045
+ "Optional[BaseStore]",
+ ),
+ "store",
+ None,
+ ),
+ (
+ "previous",
+ (ANY_TYPE,),
+ "previous",
+ inspect.Parameter.empty,
+ ),
+ (
+ "runtime",
+ (ANY_TYPE,),
+ # we never hit this block, we just inject runtime directly
+ "N/A",
+ inspect.Parameter.empty,
+ ),
+ (
+ "error",
+ (NodeError, "NodeError"),
+ # we never hit this block, we read directly from configurable
+ "N/A",
+ # default to None so non-handler nodes that happen to type a parameter
+ # `error: NodeError` don't blow up; handlers always receive a NodeError.
+ None,
+ ),
+)
+"""List of kwargs that can be passed to functions, and their corresponding
+config keys, default values and type annotations.
+
+Used to configure keyword arguments that can be injected at runtime
+from the `Runtime` object as kwargs to `invoke`, `ainvoke`, `stream` and `astream`.
+
+For a keyword to be injected from the config object, the function signature
+must contain a kwarg with the same name and a matching type annotation.
+
+Each tuple contains:
+- the name of the kwarg in the function signature
+- the type annotation(s) for the kwarg
+- the `Runtime` attribute for fetching the value (N/A if not applicable)
+
+This is fully internal and should be further refactored to use `get_type_hints`
+to resolve forward references and optional types formatted like BaseStore | None.
+"""
+
+VALID_KINDS = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
+
+
+class _RunnableWithWriter(Protocol[Input, Output]):
+ def __call__(self, state: Input, *, writer: StreamWriter) -> Output: ...
+
+
+class _RunnableWithStore(Protocol[Input, Output]):
+ def __call__(self, state: Input, *, store: BaseStore) -> Output: ...
+
+
+class _RunnableWithWriterStore(Protocol[Input, Output]):
+ def __call__(
+ self, state: Input, *, writer: StreamWriter, store: BaseStore
+ ) -> Output: ...
+
+
+class _RunnableWithConfigWriter(Protocol[Input, Output]):
+ def __call__(
+ self, state: Input, *, config: RunnableConfig, writer: StreamWriter
+ ) -> Output: ...
+
+
+class _RunnableWithConfigStore(Protocol[Input, Output]):
+ def __call__(
+ self, state: Input, *, config: RunnableConfig, store: BaseStore
+ ) -> Output: ...
+
+
+class _RunnableWithConfigWriterStore(Protocol[Input, Output]):
+ def __call__(
+ self,
+ state: Input,
+ *,
+ config: RunnableConfig,
+ writer: StreamWriter,
+ store: BaseStore,
+ ) -> Output: ...
+
+
+RunnableLike = (
+ LCRunnableLike
+ | _RunnableWithWriter[Input, Output]
+ | _RunnableWithStore[Input, Output]
+ | _RunnableWithWriterStore[Input, Output]
+ | _RunnableWithConfigWriter[Input, Output]
+ | _RunnableWithConfigStore[Input, Output]
+ | _RunnableWithConfigWriterStore[Input, Output]
+)
+
+
+class RunnableCallable(Runnable):
+ """A much simpler version of RunnableLambda that requires sync and async functions."""
+
+ def __init__(
+ self,
+ func: Callable[..., Any | Runnable] | None,
+ afunc: Callable[..., Awaitable[Any | Runnable]] | None = None,
+ *,
+ name: str | None = None,
+ tags: Sequence[str] | None = None,
+ trace: bool = True,
+ recurse: bool = True,
+ explode_args: bool = False,
+ **kwargs: Any,
+ ) -> None:
+ self.name = name
+ if self.name is None:
+ if func:
+ try:
+ if func.__name__ != "":
+ self.name = func.__name__
+ except AttributeError:
+ pass
+ elif afunc:
+ try:
+ self.name = afunc.__name__
+ except AttributeError:
+ pass
+ self.func = func
+ self.afunc = afunc
+ self.tags = tags
+ self.kwargs = kwargs
+ self.trace = trace
+ self.recurse = recurse
+ self.explode_args = explode_args
+ # check signature
+ if func is None and afunc is None:
+ raise ValueError("At least one of func or afunc must be provided.")
+
+ self.func_accepts: dict[str, tuple[str, Any]] = {}
+ params = inspect.signature(cast(Callable, func or afunc)).parameters
+
+ for kw, typ, runtime_key, default in KWARGS_CONFIG_KEYS:
+ p = params.get(kw)
+
+ if p is None or p.kind not in VALID_KINDS:
+ # If parameter is not found or is not a valid kind, skip
+ continue
+
+ if typ != (ANY_TYPE,) and p.annotation not in typ:
+ # A specific type is required, but the function annotation does
+ # not match the expected type.
+
+ # If this is a config parameter with incorrect typing, emit a warning
+ # because we used to support any type but are moving towards more correct typing
+ if kw == "config" and p.annotation != inspect.Parameter.empty:
+ warnings.warn(
+ f"The 'config' parameter should be typed as 'RunnableConfig' or "
+ f"'RunnableConfig | None', not '{p.annotation}'. ",
+ UserWarning,
+ stacklevel=4,
+ )
+ continue
+
+ # If the kwarg is accepted by the function, store the key / runtime attribute to inject
+ self.func_accepts[kw] = (runtime_key, default)
+
+ def __repr__(self) -> str:
+ repr_args = {
+ k: v
+ for k, v in self.__dict__.items()
+ if k not in {"name", "func", "afunc", "config", "kwargs", "trace"}
+ }
+ return f"{self.get_name()}({', '.join(f'{k}={v!r}' for k, v in repr_args.items())})"
+
+ def invoke(
+ self, input: Any, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Any:
+ if self.func is None:
+ raise TypeError(
+ f'No synchronous function provided to "{self.name}".'
+ "\nEither initialize with a synchronous function or invoke"
+ " via the async API (ainvoke, astream, etc.)"
+ )
+ if config is None:
+ config = ensure_config()
+ if self.explode_args:
+ args, _kwargs = input
+ kwargs = {**self.kwargs, **_kwargs, **kwargs}
+ else:
+ args = (input,)
+ kwargs = {**self.kwargs, **kwargs}
+
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+
+ for kw, (runtime_key, default) in self.func_accepts.items():
+ # If the kwarg is already set, use the set value
+ if kw in kwargs:
+ continue
+
+ kw_value: Any = MISSING
+ if kw == "config":
+ kw_value = config
+ elif kw == "error":
+ kw_value = config.get(CONF, {}).get(CONFIG_KEY_NODE_ERROR, MISSING)
+ elif runtime:
+ if kw == "runtime":
+ kw_value = runtime
+ else:
+ try:
+ kw_value = getattr(runtime, runtime_key)
+ except AttributeError:
+ pass
+
+ if kw_value is MISSING:
+ if default is inspect.Parameter.empty:
+ raise ValueError(
+ f"Missing required config key '{runtime_key}' for '{self.name}'."
+ )
+ kw_value = default
+ kwargs[kw] = kw_value
+
+ if self.trace:
+ callback_manager = get_callback_manager_for_config(config, self.tags)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ # get the run
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ # run in context
+ with set_config_context(child_config, run) as context:
+ ret = context.run(self.func, *args, **kwargs)
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(ret)
+ else:
+ ret = self.func(*args, **kwargs)
+ if self.recurse and isinstance(ret, Runnable):
+ return ret.invoke(input, config)
+ return ret
+
+ async def ainvoke(
+ self, input: Any, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Any:
+ if not self.afunc:
+ return self.invoke(input, config)
+ if config is None:
+ config = ensure_config()
+ if self.explode_args:
+ args, _kwargs = input
+ kwargs = {**self.kwargs, **_kwargs, **kwargs}
+ else:
+ args = (input,)
+ kwargs = {**self.kwargs, **kwargs}
+
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+
+ for kw, (runtime_key, default) in self.func_accepts.items():
+ # If the kwarg has already been set, use the set value
+ if kw in kwargs:
+ continue
+
+ kw_value: Any = MISSING
+ if kw == "config":
+ kw_value = config
+ elif kw == "error":
+ kw_value = config.get(CONF, {}).get(CONFIG_KEY_NODE_ERROR, MISSING)
+ elif runtime:
+ if kw == "runtime":
+ kw_value = runtime
+ else:
+ try:
+ kw_value = getattr(runtime, runtime_key)
+ except AttributeError:
+ pass
+ if kw_value is MISSING:
+ if default is inspect.Parameter.empty:
+ raise ValueError(
+ f"Missing required config key '{runtime_key}' for '{self.name}'."
+ )
+ kw_value = default
+ kwargs[kw] = kw_value
+
+ if self.trace:
+ callback_manager = get_async_callback_manager_for_config(config, self.tags)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.name,
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ coro = cast(Coroutine[None, None, Any], self.afunc(*args, **kwargs))
+ if ASYNCIO_ACCEPTS_CONTEXT:
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ with set_config_context(child_config, run) as context:
+ ret = await asyncio.create_task(coro, context=context)
+ else:
+ ret = await coro
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(ret)
+ else:
+ ret = await self.afunc(*args, **kwargs)
+ if self.recurse and isinstance(ret, Runnable):
+ return await ret.ainvoke(input, config)
+ return ret
+
+
+def is_async_callable(
+ func: Any,
+) -> TypeGuard[Callable[..., Awaitable]]:
+ """Check if a function is async."""
+ return (
+ inspect.iscoroutinefunction(func)
+ or hasattr(func, "__call__")
+ and inspect.iscoroutinefunction(func.__call__)
+ )
+
+
+def is_async_generator(
+ func: Any,
+) -> TypeGuard[Callable[..., AsyncIterator]]:
+ """Check if a function is an async generator."""
+ return (
+ inspect.isasyncgenfunction(func)
+ or hasattr(func, "__call__")
+ and inspect.isasyncgenfunction(func.__call__)
+ )
+
+
+def coerce_to_runnable(
+ thing: RunnableLike, *, name: str | None, trace: bool
+) -> Runnable:
+ """Coerce a runnable-like object into a Runnable.
+
+ Args:
+ thing: A runnable-like object.
+
+ Returns:
+ A Runnable.
+ """
+ if isinstance(thing, Runnable):
+ return thing
+ elif is_async_generator(thing) or inspect.isgeneratorfunction(thing):
+ return RunnableLambda(thing, name=name)
+ elif callable(thing):
+ if is_async_callable(thing):
+ return RunnableCallable(None, thing, name=name, trace=trace)
+ else:
+ return RunnableCallable(
+ thing,
+ wraps(thing)(partial(run_in_executor, None, thing)), # type: ignore[arg-type]
+ name=name,
+ trace=trace,
+ )
+ elif isinstance(thing, dict):
+ return RunnableParallel(thing)
+ else:
+ raise TypeError(
+ f"Expected a Runnable, callable or dict."
+ f"Instead got an unsupported type: {type(thing)}"
+ )
+
+
+class RunnableSeq(Runnable):
+ """Sequence of `Runnable`, where the output of each is the input of the next.
+
+ `RunnableSeq` is a simpler version of `RunnableSequence` that is internal to
+ LangGraph.
+ """
+
+ def __init__(
+ self,
+ *steps: RunnableLike,
+ name: str | None = None,
+ trace_inputs: Callable[[Any], Any] | None = None,
+ ) -> None:
+ """Create a new RunnableSeq.
+
+ Args:
+ steps: The steps to include in the sequence.
+ name: The name of the `Runnable`.
+
+ Raises:
+ ValueError: If the sequence has less than 2 steps.
+ """
+ steps_flat: list[Runnable] = []
+ for step in steps:
+ if isinstance(step, RunnableSequence):
+ steps_flat.extend(step.steps)
+ elif isinstance(step, RunnableSeq):
+ steps_flat.extend(step.steps)
+ else:
+ steps_flat.append(coerce_to_runnable(step, name=None, trace=True))
+ if len(steps_flat) < 2:
+ raise ValueError(
+ f"RunnableSeq must have at least 2 steps, got {len(steps_flat)}"
+ )
+ self.steps = steps_flat
+ self.name = name
+ self.trace_inputs = trace_inputs
+
+ def __or__(
+ self,
+ other: Any,
+ ) -> Runnable:
+ if isinstance(other, RunnableSequence):
+ return RunnableSeq(
+ *self.steps,
+ other.first,
+ *other.middle,
+ other.last,
+ name=self.name or other.name,
+ )
+ elif isinstance(other, RunnableSeq):
+ return RunnableSeq(
+ *self.steps,
+ *other.steps,
+ name=self.name or other.name,
+ )
+ else:
+ return RunnableSeq(
+ *self.steps,
+ coerce_to_runnable(other, name=None, trace=True),
+ name=self.name,
+ )
+
+ def __ror__(
+ self,
+ other: Any,
+ ) -> Runnable:
+ if isinstance(other, RunnableSequence):
+ return RunnableSequence(
+ other.first,
+ *other.middle,
+ other.last,
+ *self.steps,
+ name=other.name or self.name,
+ )
+ elif isinstance(other, RunnableSeq):
+ return RunnableSeq(
+ *other.steps,
+ *self.steps,
+ name=other.name or self.name,
+ )
+ else:
+ return RunnableSequence(
+ coerce_to_runnable(other, name=None, trace=True),
+ *self.steps,
+ name=self.name,
+ )
+
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Any:
+ if config is None:
+ config = ensure_config()
+ # setup callbacks and context
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ self.trace_inputs(input) if self.trace_inputs is not None else input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ # 1st step is the actual node,
+ # others are writers which don't need to be run in context
+ if i == 0:
+ # get the run object
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ # run in context
+ with set_config_context(config, run) as context:
+ input = context.run(step.invoke, input, config, **kwargs)
+ else:
+ input = step.invoke(input, config)
+ # finish the root run
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(input)
+ return input
+
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Any:
+ if config is None:
+ config = ensure_config()
+ # setup callbacks
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ self.trace_inputs(input) if self.trace_inputs is not None else input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ # 1st step is the actual node,
+ # others are writers which don't need to be run in context
+ if i == 0:
+ if ASYNCIO_ACCEPTS_CONTEXT:
+ # get the run object
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ # run in context
+ with set_config_context(config, run) as context:
+ input = await asyncio.create_task(
+ step.ainvoke(input, config, **kwargs), context=context
+ )
+ else:
+ input = await step.ainvoke(input, config, **kwargs)
+ else:
+ input = await step.ainvoke(input, config)
+ # finish the root run
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(input)
+ return input
+
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Any]:
+ if config is None:
+ config = ensure_config()
+ # setup callbacks
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ self.trace_inputs(input) if self.trace_inputs is not None else input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ # get the run object
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ # create first step config
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{1}"),
+ )
+ # run all in context
+ with set_config_context(config, run) as context:
+ try:
+ # stream the last steps
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ for idx, step in enumerate(self.steps):
+ if idx == 0:
+ iterator = step.stream(input, config, **kwargs)
+ else:
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{idx + 1}"),
+ )
+ iterator = step.transform(iterator, config)
+ # populates streamed_output in astream_log() output if needed
+ if _StreamingCallbackHandler is not None:
+ for h in run_manager.handlers:
+ if isinstance(h, _StreamingCallbackHandler):
+ iterator = h.tap_output_iter(run_manager.run_id, iterator)
+ # consume into final output
+ output = context.run(_consume_iter, iterator)
+ # sequence doesn't emit output, yield to mark as generator
+ yield
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Any]:
+ if config is None:
+ config = ensure_config()
+ # setup callbacks
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ self.trace_inputs(input) if self.trace_inputs is not None else input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ # stream the last steps
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ if ASYNCIO_ACCEPTS_CONTEXT:
+ # get the run object
+ for h in run_manager.handlers:
+ if isinstance(h, LangChainTracer):
+ run = h.run_map.get(str(run_manager.run_id))
+ break
+ else:
+ run = None
+ # create first step config
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{1}"),
+ )
+ # run all in context
+ with set_config_context(config, run) as context:
+ try:
+ async with AsyncExitStack() as stack:
+ for idx, step in enumerate(self.steps):
+ if idx == 0:
+ aiterator = step.astream(input, config, **kwargs)
+ else:
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(
+ f"seq:step:{idx + 1}"
+ ),
+ )
+ aiterator = step.atransform(aiterator, config)
+ if hasattr(aiterator, "aclose"):
+ stack.push_async_callback(aiterator.aclose)
+ # populates streamed_output in astream_log() output if needed
+ if _StreamingCallbackHandler is not None:
+ for h in run_manager.handlers:
+ if isinstance(h, _StreamingCallbackHandler):
+ aiterator = h.tap_output_aiter(
+ run_manager.run_id, aiterator
+ )
+ # consume into final output
+ output = await asyncio.create_task(
+ _consume_aiter(aiterator), context=context
+ )
+ # sequence doesn't emit output, yield to mark as generator
+ yield
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ else:
+ try:
+ async with AsyncExitStack() as stack:
+ for idx, step in enumerate(self.steps):
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{idx + 1}"),
+ )
+ if idx == 0:
+ aiterator = step.astream(input, config, **kwargs)
+ else:
+ aiterator = step.atransform(aiterator, config)
+ if hasattr(aiterator, "aclose"):
+ stack.push_async_callback(aiterator.aclose)
+ # populates streamed_output in astream_log() output if needed
+ if _StreamingCallbackHandler is not None:
+ for h in run_manager.handlers:
+ if isinstance(h, _StreamingCallbackHandler):
+ aiterator = h.tap_output_aiter(
+ run_manager.run_id, aiterator
+ )
+ # consume into final output
+ output = await _consume_aiter(aiterator)
+ # sequence doesn't emit output, yield to mark as generator
+ yield
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+
+
+def _consume_iter(it: Iterator[Any]) -> Any:
+ """Consume an iterator."""
+ output: Any = None
+ add_supported = False
+ for chunk in it:
+ # collect final output
+ if output is None:
+ output = chunk
+ elif add_supported:
+ try:
+ output = output + chunk
+ except TypeError:
+ output = chunk
+ add_supported = False
+ else:
+ output = chunk
+ return output
+
+
+async def _consume_aiter(it: AsyncIterator[Any]) -> Any:
+ """Consume an async iterator."""
+ output: Any = None
+ add_supported = False
+ async for chunk in it:
+ # collect final output
+ if add_supported:
+ try:
+ output = output + chunk
+ except TypeError:
+ output = chunk
+ add_supported = False
+ else:
+ output = chunk
+ return output
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_scratchpad.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_scratchpad.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd96b726c66276761acc88d88324d9bc3d7ea7d1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_scratchpad.py
@@ -0,0 +1,19 @@
+import dataclasses
+from collections.abc import Callable
+from typing import Any
+
+from langgraph.types import _DC_KWARGS
+
+
+@dataclasses.dataclass(**_DC_KWARGS)
+class PregelScratchpad:
+ step: int
+ stop: int
+ # call
+ call_counter: Callable[[], int]
+ # interrupt
+ interrupt_counter: Callable[[], int]
+ get_null_resume: Callable[[bool], Any]
+ resume: list[Any]
+ # subgraph
+ subgraph_counter: Callable[[], int]
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_serde.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_serde.py
new file mode 100644
index 0000000000000000000000000000000000000000..775242a874109c0c044e45f203d9b515fbaf3d3c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_serde.py
@@ -0,0 +1,253 @@
+from __future__ import annotations
+
+import dataclasses
+import logging
+import sys
+import types
+from collections import deque
+from enum import Enum
+from typing import (
+ Annotated,
+ Any,
+ Literal,
+ Union,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+from langchain_core import messages as lc_messages
+from langgraph.checkpoint.base import BaseCheckpointSaver
+from pydantic import BaseModel
+from typing_extensions import NotRequired, Required, is_typeddict
+
+try:
+ from langgraph.checkpoint.serde._msgpack import ( # noqa: F401
+ STRICT_MSGPACK_ENABLED,
+ )
+except ImportError:
+ STRICT_MSGPACK_ENABLED = False
+
+_warned_allowlist_unsupported = False
+
+logger = logging.getLogger(__name__)
+
+
+def _supports_checkpointer_allowlist() -> bool:
+ return hasattr(BaseCheckpointSaver, "with_allowlist")
+
+
+_SUPPORTS_ALLOWLIST = _supports_checkpointer_allowlist()
+
+
+def apply_checkpointer_allowlist(
+ checkpointer: Any, allowlist: set[tuple[str, ...]] | None
+) -> Any:
+ if not checkpointer or allowlist is None or checkpointer in (True, False):
+ return checkpointer
+ if not _SUPPORTS_ALLOWLIST:
+ global _warned_allowlist_unsupported
+ if not _warned_allowlist_unsupported:
+ logger.warning(
+ "Checkpointer does not support with_allowlist; strict msgpack "
+ "allowlist will be skipped."
+ )
+ _warned_allowlist_unsupported = True
+ return checkpointer
+ return checkpointer.with_allowlist(allowlist)
+
+
+def curated_core_allowlist() -> set[tuple[str, ...]]:
+ allowlist: set[tuple[str, ...]] = set()
+ for name in (
+ "BaseMessage",
+ "BaseMessageChunk",
+ "HumanMessage",
+ "HumanMessageChunk",
+ "AIMessage",
+ "AIMessageChunk",
+ "SystemMessage",
+ "SystemMessageChunk",
+ "ChatMessage",
+ "ChatMessageChunk",
+ "ToolMessage",
+ "ToolMessageChunk",
+ "FunctionMessage",
+ "FunctionMessageChunk",
+ "RemoveMessage",
+ ):
+ cls = getattr(lc_messages, name, None)
+ if cls is None:
+ continue
+ allowlist.add((cls.__module__, cls.__name__))
+
+ return allowlist
+
+
+def build_serde_allowlist(
+ *,
+ schemas: list[type[Any]] | None = None,
+ channels: dict[str, Any] | None = None,
+) -> set[tuple[str, ...]]:
+ allowlist = curated_core_allowlist()
+ if schemas:
+ schemas = [schema for schema in schemas if schema is not None]
+ return allowlist | collect_allowlist_from_schemas(
+ schemas=schemas,
+ channels=channels,
+ )
+
+
+def collect_allowlist_from_schemas(
+ *,
+ schemas: list[type[Any]] | None = None,
+ channels: dict[str, Any] | None = None,
+) -> set[tuple[str, ...]]:
+ allowlist: set[tuple[str, ...]] = set()
+ seen: set[Any] = set()
+ seen_ids: set[int] = set()
+
+ if schemas:
+ for schema in schemas:
+ _collect_from_type(schema, allowlist, seen, seen_ids)
+
+ if channels:
+ for channel in channels.values():
+ value_type = getattr(channel, "ValueType", None)
+ if value_type is not None:
+ _collect_from_type(value_type, allowlist, seen, seen_ids)
+ update_type = getattr(channel, "UpdateType", None)
+ if update_type is not None:
+ _collect_from_type(update_type, allowlist, seen, seen_ids)
+
+ return allowlist
+
+
+def _collect_from_type(
+ typ: Any,
+ allowlist: set[tuple[str, ...]],
+ seen: set[Any],
+ seen_ids: set[int],
+) -> None:
+ if _already_seen(typ, seen, seen_ids):
+ return
+
+ if typ is Any or typ is None:
+ return
+
+ if typ is Literal:
+ return
+
+ if isinstance(typ, types.UnionType):
+ for arg in typ.__args__:
+ _collect_from_type(arg, allowlist, seen, seen_ids)
+ return
+
+ origin = get_origin(typ)
+ if origin is Union:
+ for arg in get_args(typ):
+ _collect_from_type(arg, allowlist, seen, seen_ids)
+ return
+ if origin is Annotated or origin in (Required, NotRequired):
+ args = get_args(typ)
+ if args:
+ _collect_from_type(args[0], allowlist, seen, seen_ids)
+ return
+
+ if origin is Literal:
+ return
+
+ if origin in (list, set, tuple, dict, deque, frozenset):
+ for arg in get_args(typ):
+ _collect_from_type(arg, allowlist, seen, seen_ids)
+ return
+
+ if hasattr(typ, "__supertype__"):
+ _collect_from_type(typ.__supertype__, allowlist, seen, seen_ids)
+ return
+
+ if is_typeddict(typ):
+ for field_type in _safe_get_type_hints(typ).values():
+ _collect_from_type(field_type, allowlist, seen, seen_ids)
+ return
+
+ if _is_pydantic_model(typ):
+ allowlist.add((typ.__module__, typ.__name__))
+ field_types = _safe_get_type_hints(typ)
+ if field_types:
+ for field_type in field_types.values():
+ _collect_from_type(field_type, allowlist, seen, seen_ids)
+ else:
+ for field_type in _pydantic_field_types(typ):
+ _collect_from_type(field_type, allowlist, seen, seen_ids)
+ return
+
+ if dataclasses.is_dataclass(typ):
+ if typ_name := getattr(typ, "__name__", None):
+ allowlist.add((typ.__module__, typ_name))
+ field_types = _safe_get_type_hints(typ)
+ if field_types:
+ for field_type in field_types.values():
+ _collect_from_type(field_type, allowlist, seen, seen_ids)
+ else:
+ for field in dataclasses.fields(typ):
+ _collect_from_type(field.type, allowlist, seen, seen_ids)
+ return
+
+ if isinstance(typ, type) and issubclass(typ, Enum):
+ allowlist.add((typ.__module__, typ.__name__))
+ return
+
+
+def _already_seen(typ: Any, seen: set[Any], seen_ids: set[int]) -> bool:
+ try:
+ if typ in seen:
+ return True
+ seen.add(typ)
+ return False
+ except TypeError:
+ typ_id = id(typ)
+ if typ_id in seen_ids:
+ return True
+ seen_ids.add(typ_id)
+ return False
+
+
+def _safe_get_type_hints(typ: Any) -> dict[str, Any]:
+ try:
+ module = sys.modules.get(getattr(typ, "__module__", ""))
+ globalns = module.__dict__ if module else None
+ localns = dict(vars(typ)) if hasattr(typ, "__dict__") else None
+ return get_type_hints(
+ typ, globalns=globalns, localns=localns, include_extras=True
+ )
+ except Exception:
+ return {}
+
+
+def _is_pydantic_model(typ: Any) -> bool:
+ if not isinstance(typ, type):
+ return False
+ if issubclass(typ, BaseModel):
+ return True
+ try:
+ from pydantic.v1 import BaseModel as BaseModelV1
+ except Exception:
+ return False
+ return issubclass(typ, BaseModelV1)
+
+
+def _pydantic_field_types(typ: type[Any]) -> list[Any]:
+ if hasattr(typ, "model_fields"):
+ return [
+ field.annotation
+ for field in typ.model_fields.values()
+ if getattr(field, "annotation", None) is not None
+ ]
+ if hasattr(typ, "__fields__"):
+ return [
+ field.outer_type_
+ for field in typ.__fields__.values()
+ if getattr(field, "outer_type_", None) is not None
+ ]
+ return []
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_timeout.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_timeout.py
new file mode 100644
index 0000000000000000000000000000000000000000..11ff43527d9b6e849776c6ad2acad50d029a9cfd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_timeout.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from datetime import timedelta
+from typing import Literal
+
+from langgraph.types import TimeoutPolicy
+
+_SYNC_TIMEOUT_PREFIX = (
+ "Node timeouts are only supported for async nodes because sync Python "
+ "execution cannot be safely cancelled in-process."
+)
+
+
+def coerce_timeout_policy(
+ value: float | timedelta | TimeoutPolicy | None,
+) -> TimeoutPolicy | None:
+ """Normalize a timeout value to positive-second policy fields."""
+ return TimeoutPolicy.coerce(value)
+
+
+def sync_timeout_unsupported(
+ name: str, *, kind: Literal["Node", "Task"] = "Node"
+) -> ValueError:
+ """Build the canonical error for using `timeout` with a sync target."""
+ return ValueError(f"{_SYNC_TIMEOUT_PREFIX} {kind} {name!r} is sync.")
diff --git a/python/user_packages/Python313/site-packages/langgraph/_internal/_typing.py b/python/user_packages/Python313/site-packages/langgraph/_internal/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..19854d1c814ba83a9236aef6816645ccc17e2e85
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/_internal/_typing.py
@@ -0,0 +1,54 @@
+"""Private typing utilities for LangGraph."""
+
+from __future__ import annotations
+
+from dataclasses import Field
+from typing import Any, ClassVar, Protocol, TypeAlias
+
+from pydantic import BaseModel
+from typing_extensions import TypedDict
+
+
+class TypedDictLikeV1(Protocol):
+ """Protocol to represent types that behave like TypedDicts
+
+ Version 1: using `ClassVar` for keys."""
+
+ __required_keys__: ClassVar[frozenset[str]]
+ __optional_keys__: ClassVar[frozenset[str]]
+
+
+class TypedDictLikeV2(Protocol):
+ """Protocol to represent types that behave like TypedDicts
+
+ Version 2: not using `ClassVar` for keys."""
+
+ __required_keys__: frozenset[str]
+ __optional_keys__: frozenset[str]
+
+
+class DataclassLike(Protocol):
+ """Protocol to represent types that behave like dataclasses.
+
+ Inspired by the private _DataclassT from dataclasses that uses a similar protocol as a bound."""
+
+ __dataclass_fields__: ClassVar[dict[str, Field[Any]]]
+
+
+StateLike: TypeAlias = TypedDictLikeV1 | TypedDictLikeV2 | DataclassLike | BaseModel
+"""Type alias for state-like types.
+
+It can either be a `TypedDict`, `dataclass`, or Pydantic `BaseModel`.
+Note: we cannot use either `TypedDict` or `dataclass` directly due to limitations in type checking.
+"""
+
+MISSING = object()
+"""Unset sentinel value."""
+
+
+class DeprecatedKwargs(TypedDict):
+ """TypedDict to use for extra keyword arguments, enabling type checking warnings for deprecated arguments."""
+
+
+EMPTY_SEQ: tuple[str, ...] = tuple()
+"""An empty sequence of strings."""
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/base/__init__.py b/python/user_packages/Python313/site-packages/langgraph/cache/base/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..092324e721d4717bdc35bc843ee0c317aabaf19c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/cache/base/__init__.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Mapping, Sequence
+from typing import Generic, TypeVar
+
+from langgraph.checkpoint.serde.base import SerializerProtocol
+from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
+
+ValueT = TypeVar("ValueT")
+Namespace = tuple[str, ...]
+FullKey = tuple[Namespace, str]
+
+
+class BaseCache(ABC, Generic[ValueT]):
+ """Base class for a cache."""
+
+ serde: SerializerProtocol = JsonPlusSerializer(pickle_fallback=False)
+
+ def __init__(self, *, serde: SerializerProtocol | None = None) -> None:
+ """Initialize the cache with a serializer."""
+ self.serde = serde or self.serde
+
+ @abstractmethod
+ def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Get the cached values for the given keys."""
+
+ @abstractmethod
+ async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Asynchronously get the cached values for the given keys."""
+
+ @abstractmethod
+ def set(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Set the cached values for the given keys and TTLs."""
+
+ @abstractmethod
+ async def aset(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Asynchronously set the cached values for the given keys and TTLs."""
+
+ @abstractmethod
+ def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
+
+ @abstractmethod
+ async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Asynchronously delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0621abe1688d8585010e81fb6061c7b50be5f757
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/base/py.typed b/python/user_packages/Python313/site-packages/langgraph/cache/base/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/memory/__init__.py b/python/user_packages/Python313/site-packages/langgraph/cache/memory/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b10db0511c62f2e4c98a19a8bc796599db71124
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/cache/memory/__init__.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+import datetime
+import threading
+from collections.abc import Mapping, Sequence
+
+from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT
+from langgraph.checkpoint.serde.base import SerializerProtocol
+
+
+class InMemoryCache(BaseCache[ValueT]):
+ def __init__(self, *, serde: SerializerProtocol | None = None):
+ super().__init__(serde=serde)
+ self._cache: dict[Namespace, dict[str, tuple[str, bytes, float | None]]] = {}
+ self._lock = threading.RLock()
+
+ def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Get the cached values for the given keys."""
+ with self._lock:
+ if not keys:
+ return {}
+ now = datetime.datetime.now(datetime.timezone.utc).timestamp()
+ values: dict[FullKey, ValueT] = {}
+ for ns_tuple, key in keys:
+ ns = Namespace(ns_tuple)
+ if ns in self._cache and key in self._cache[ns]:
+ enc, val, expiry = self._cache[ns][key]
+ if expiry is None or now < expiry:
+ values[(ns, key)] = self.serde.loads_typed((enc, val))
+ else:
+ del self._cache[ns][key]
+ return values
+
+ async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Asynchronously get the cached values for the given keys."""
+ return self.get(keys)
+
+ def set(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Set the cached values for the given keys."""
+ with self._lock:
+ now = datetime.datetime.now(datetime.timezone.utc)
+ for (ns, key), (value, ttl) in keys.items():
+ if ttl is not None:
+ delta = datetime.timedelta(seconds=ttl)
+ expiry: float | None = (now + delta).timestamp()
+ else:
+ expiry = None
+ if ns not in self._cache:
+ self._cache[ns] = {}
+ self._cache[ns][key] = (
+ *self.serde.dumps_typed(value),
+ expiry,
+ )
+
+ async def aset(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Asynchronously set the cached values for the given keys."""
+ self.set(keys)
+
+ def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
+ with self._lock:
+ if namespaces is None:
+ self._cache.clear()
+ else:
+ for ns in namespaces:
+ if ns in self._cache:
+ del self._cache[ns]
+
+ async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Asynchronously delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
+ self.clear(namespaces)
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac2e224497c430fa5ffce1b91eb568fb2be9f63f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/redis/__init__.py b/python/user_packages/Python313/site-packages/langgraph/cache/redis/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea4f71480d02a01ec242335d32ac532f61ccfb7d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/cache/redis/__init__.py
@@ -0,0 +1,144 @@
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT
+from langgraph.checkpoint.serde.base import SerializerProtocol
+
+
+class RedisCache(BaseCache[ValueT]):
+ """Redis-based cache implementation with TTL support."""
+
+ def __init__(
+ self,
+ redis: Any,
+ *,
+ serde: SerializerProtocol | None = None,
+ prefix: str = "langgraph:cache:",
+ ) -> None:
+ """Initialize the cache with a Redis client.
+
+ Args:
+ redis: Redis client instance (sync or async)
+ serde: Serializer to use for values
+ prefix: Key prefix for all cached values
+ """
+ super().__init__(serde=serde)
+ self.redis = redis
+ self.prefix = prefix
+
+ def _make_key(self, ns: Namespace, key: str) -> str:
+ """Create a Redis key from namespace and key."""
+ ns_str = ":".join(ns) if ns else ""
+ return f"{self.prefix}{ns_str}:{key}" if ns_str else f"{self.prefix}{key}"
+
+ def _parse_key(self, redis_key: str) -> tuple[Namespace, str]:
+ """Parse a Redis key back to namespace and key."""
+ if not redis_key.startswith(self.prefix):
+ raise ValueError(
+ f"Key {redis_key} does not start with prefix {self.prefix}"
+ )
+
+ remaining = redis_key[len(self.prefix) :]
+ if ":" in remaining:
+ parts = remaining.split(":")
+ key = parts[-1]
+ ns_parts = parts[:-1]
+ return (tuple(ns_parts), key)
+ else:
+ return (tuple(), remaining)
+
+ def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Get the cached values for the given keys."""
+ if not keys:
+ return {}
+
+ # Build Redis keys
+ redis_keys = [self._make_key(ns, key) for ns, key in keys]
+
+ # Get values from Redis using MGET
+ try:
+ raw_values = self.redis.mget(redis_keys)
+ except Exception:
+ # If Redis is unavailable, return empty dict
+ return {}
+
+ values: dict[FullKey, ValueT] = {}
+ for i, raw_value in enumerate(raw_values):
+ if raw_value is not None:
+ try:
+ # Deserialize the value
+ encoding, data = raw_value.split(b":", 1)
+ values[keys[i]] = self.serde.loads_typed((encoding.decode(), data))
+ except Exception:
+ # Skip corrupted entries
+ continue
+
+ return values
+
+ async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
+ """Asynchronously get the cached values for the given keys."""
+ return self.get(keys)
+
+ def set(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Set the cached values for the given keys and TTLs."""
+ if not mapping:
+ return
+
+ # Use pipeline for efficient batch operations
+ pipe = self.redis.pipeline()
+
+ for (ns, key), (value, ttl) in mapping.items():
+ redis_key = self._make_key(ns, key)
+ encoding, data = self.serde.dumps_typed(value)
+
+ # Store as "encoding:data" format
+ serialized_value = f"{encoding}:".encode() + data
+
+ if ttl is not None:
+ pipe.setex(redis_key, ttl, serialized_value)
+ else:
+ pipe.set(redis_key, serialized_value)
+
+ try:
+ pipe.execute()
+ except Exception:
+ # Silently fail if Redis is unavailable
+ pass
+
+ async def aset(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
+ """Asynchronously set the cached values for the given keys and TTLs."""
+ self.set(mapping)
+
+ def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
+ try:
+ if namespaces is None:
+ # Clear all keys with our prefix
+ pattern = f"{self.prefix}*"
+ keys = self.redis.keys(pattern)
+ if keys:
+ self.redis.delete(*keys)
+ else:
+ # Clear specific namespaces
+ keys_to_delete = []
+ for ns in namespaces:
+ ns_str = ":".join(ns) if ns else ""
+ pattern = (
+ f"{self.prefix}{ns_str}:*" if ns_str else f"{self.prefix}*"
+ )
+ keys = self.redis.keys(pattern)
+ keys_to_delete.extend(keys)
+
+ if keys_to_delete:
+ self.redis.delete(*keys_to_delete)
+ except Exception:
+ # Silently fail if Redis is unavailable
+ pass
+
+ async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
+ """Asynchronously delete the cached values for the given namespaces.
+ If no namespaces are provided, clear all cached values."""
+ self.clear(namespaces)
diff --git a/python/user_packages/Python313/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d96001eede367f1f8df0cc49d22ecba3db4f5b5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__init__.py b/python/user_packages/Python313/site-packages/langgraph/channels/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc7fcc471f55c0b4911a0c5d11b4c1875799d281
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/__init__.py
@@ -0,0 +1,29 @@
+from langgraph.channels.any_value import AnyValue
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.binop import BinaryOperatorAggregate
+from langgraph.channels.delta import DeltaChannel
+from langgraph.channels.ephemeral_value import EphemeralValue
+from langgraph.channels.last_value import LastValue, LastValueAfterFinish
+from langgraph.channels.named_barrier_value import (
+ NamedBarrierValue,
+ NamedBarrierValueAfterFinish,
+)
+from langgraph.channels.topic import Topic
+from langgraph.channels.untracked_value import UntrackedValue
+
+__all__ = (
+ # base
+ "BaseChannel",
+ # value types
+ "AnyValue",
+ "LastValue",
+ "LastValueAfterFinish",
+ "UntrackedValue",
+ "EphemeralValue",
+ "BinaryOperatorAggregate",
+ "DeltaChannel",
+ "NamedBarrierValue",
+ "NamedBarrierValueAfterFinish",
+ # topics
+ "Topic",
+)
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c1b9c2d60519ca7f3197fc088704cff1c81a55
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/any_value.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/any_value.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bec77aadcf4322f7e7ac82a98f552e240dbb7764
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/any_value.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c117b41b51144d7297202a1c8883e47c31c2fb7f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/binop.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/binop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a973b57796e286fd96d0802ca78fb0b518b18b5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/binop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/delta.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/delta.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d08128f15bf42ae53fd5e6a2d8fc5a10b3024e9b
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/delta.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f4ee9b71065e5ae2774515f310fe92c8b03194c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/last_value.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/last_value.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09b309e7b869789c1e73cf6c70330ba4934b43bd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/last_value.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb31871d655a4215399e13e979b239e3676321c6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/topic.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/topic.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0166a93c2f78e6dd7f6f310eeff4ce55e388d0dd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/topic.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2723044f2af4f3785358e465a4bf9ad7686a590
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/any_value.py b/python/user_packages/Python313/site-packages/langgraph/channels/any_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ba25557469dce738422287050393c98714be0fc
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/any_value.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any, Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import EmptyChannelError
+
+__all__ = ("AnyValue",)
+
+
+class AnyValue(Generic[Value], BaseChannel[Value, Value, Value]):
+ """Stores the last value received, assumes that if multiple values are
+ received, they are all equal."""
+
+ __slots__ = ("typ", "value")
+
+ value: Value | Any
+
+ def __init__(self, typ: Any, key: str = "") -> None:
+ super().__init__(typ, key)
+ self.value = MISSING
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, AnyValue)
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.key)
+ empty.value = self.value
+ return empty
+
+ def from_checkpoint(self, checkpoint: Value) -> Self:
+ empty = self.__class__(self.typ, self.key)
+ if checkpoint is not MISSING:
+ empty.value = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ if len(values) == 0:
+ if self.value is MISSING:
+ return False
+ else:
+ self.value = MISSING
+ return True
+
+ self.value = values[-1]
+ return True
+
+ def get(self) -> Value:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
+
+ def checkpoint(self) -> Value:
+ return self.value
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/base.py b/python/user_packages/Python313/site-packages/langgraph/channels/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..9207aa2bbf2c1dd3c4a3a32624f882ce845433d5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/base.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Sequence
+from typing import Any, Generic, TypeVar
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.errors import EmptyChannelError
+
+Value = TypeVar("Value")
+Update = TypeVar("Update")
+Checkpoint = TypeVar("Checkpoint")
+
+__all__ = ("BaseChannel",)
+
+
+class BaseChannel(Generic[Value, Update, Checkpoint], ABC):
+ """Base class for all channels."""
+
+ __slots__ = ("key", "typ")
+
+ def __init__(self, typ: Any, key: str = "") -> None:
+ self.typ = typ
+ self.key = key
+
+ @property
+ @abstractmethod
+ def ValueType(self) -> Any:
+ """The type of the value stored in the channel."""
+
+ @property
+ @abstractmethod
+ def UpdateType(self) -> Any:
+ """The type of the update received by the channel."""
+
+ # serialize/deserialize methods
+
+ def copy(self) -> Self:
+ """Return a copy of the channel.
+
+ By default, delegates to `checkpoint()` and `from_checkpoint()`.
+
+ Subclasses can override this method with a more efficient implementation.
+ """
+ return self.from_checkpoint(self.checkpoint())
+
+ def checkpoint(self) -> Checkpoint | Any:
+ """Return a serializable representation of the channel's current state.
+
+ Raises `EmptyChannelError` if the channel is empty (never updated yet),
+ or doesn't support checkpoints.
+ """
+ try:
+ return self.get()
+ except EmptyChannelError:
+ return MISSING
+
+ @abstractmethod
+ def from_checkpoint(self, checkpoint: Checkpoint | Any) -> Self:
+ """Return a new identical channel, optionally initialized from a checkpoint.
+
+ If the checkpoint contains complex data structures, they should be copied.
+ """
+
+ # read methods
+
+ @abstractmethod
+ def get(self) -> Value:
+ """Return the current value of the channel.
+
+ Raises `EmptyChannelError` if the channel is empty (never updated yet)."""
+
+ def is_available(self) -> bool:
+ """Return `True` if the channel is available (not empty), `False` otherwise.
+
+ Subclasses should override this method to provide a more efficient
+ implementation than calling `get()` and catching `EmptyChannelError`.
+ """
+ try:
+ self.get()
+ return True
+ except EmptyChannelError:
+ return False
+
+ # write methods
+
+ @abstractmethod
+ def update(self, values: Sequence[Update]) -> bool:
+ """Update the channel's value with the given sequence of updates.
+ The order of the updates in the sequence is arbitrary.
+ This method is called by Pregel for all channels at the end of each step.
+
+ If there are no updates, it is called with an empty sequence.
+
+ Raises `InvalidUpdateError` if the sequence of updates is invalid.
+
+ Returns `True` if the channel was updated, `False` otherwise."""
+
+ def consume(self) -> bool:
+ """Notify the channel that a subscribed task ran.
+
+ By default, no-op.
+
+ A channel can use this method to modify its state, preventing the value from being consumed again.
+
+ Returns `True` if the channel was updated, `False` otherwise.
+ """
+ return False
+
+ def finish(self) -> bool:
+ """Notify the channel that the Pregel run is finishing.
+
+ By default, no-op.
+
+ A channel can use this method to modify its state, preventing finish.
+
+ Returns `True` if the channel was updated, `False` otherwise.
+ """
+ return False
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/binop.py b/python/user_packages/Python313/site-packages/langgraph/channels/binop.py
new file mode 100644
index 0000000000000000000000000000000000000000..5735ac65da17e11e2e0d8c6e4875d333a6c733b6
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/binop.py
@@ -0,0 +1,141 @@
+import collections.abc
+from collections.abc import Callable, Sequence
+from typing import Any, Generic
+
+from typing_extensions import NotRequired, Required, Self
+
+from langgraph._internal._constants import OVERWRITE
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import (
+ EmptyChannelError,
+ ErrorCode,
+ InvalidUpdateError,
+ create_error_message,
+)
+from langgraph.types import Overwrite
+
+__all__ = ("BinaryOperatorAggregate",)
+
+
+# Adapted from typing_extensions
+def _strip_extras(t): # type: ignore[no-untyped-def]
+ """Strips Annotated, Required and NotRequired from a given type."""
+ if hasattr(t, "__origin__"):
+ if t.__origin__ in (Required, NotRequired):
+ return _strip_extras(t.__args__[0])
+ return _strip_extras(t.__origin__)
+ return t
+
+
+def _get_overwrite(value: Any) -> tuple[bool, Any]:
+ """Inspects the given value and returns (is_overwrite, overwrite_value)."""
+ if isinstance(value, Overwrite):
+ return True, value.value
+ if isinstance(value, dict) and len(value) == 1 and OVERWRITE in value:
+ return True, value[OVERWRITE]
+ return False, None
+
+
+def _operators_equal(a: Callable, b: Callable) -> bool:
+ """Return True if two reducer operators should be considered equal.
+
+ Lambdas all share the name '' so identity comparison is
+ unreliable; treat any pairing that includes a lambda as equal.
+ """
+ if a.__name__ == "" or b.__name__ == "":
+ return True
+ return a is b
+
+
+class BinaryOperatorAggregate(Generic[Value], BaseChannel[Value, Value, Value]):
+ """Stores the result of applying a binary operator to the current value and each new value.
+
+ ```python
+ import operator
+
+ total = Channels.BinaryOperatorAggregate(int, operator.add)
+ ```
+ """
+
+ __slots__ = ("value", "operator")
+
+ def __init__(self, typ: type[Value], operator: Callable[[Value, Value], Value]):
+ super().__init__(typ)
+ self.operator = operator
+ # special forms from typing or collections.abc are not instantiable
+ # so we need to replace them with their concrete counterparts
+ typ = _strip_extras(typ)
+ if typ in (collections.abc.Sequence, collections.abc.MutableSequence):
+ typ = list
+ if typ in (collections.abc.Set, collections.abc.MutableSet):
+ typ = set
+ if typ in (collections.abc.Mapping, collections.abc.MutableMapping):
+ typ = dict
+ try:
+ self.value = typ()
+ except Exception:
+ self.value = MISSING
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, BinaryOperatorAggregate) and _operators_equal(
+ self.operator, value.operator
+ )
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.operator)
+ empty.key = self.key
+ empty.value = self.value
+ return empty
+
+ def from_checkpoint(self, checkpoint: Value) -> Self:
+ empty = self.__class__(self.typ, self.operator)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ empty.value = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ if not values:
+ return False
+ if self.value is MISSING:
+ self.value = values[0]
+ values = values[1:]
+ seen_overwrite: bool = False
+ for value in values:
+ is_overwrite, overwrite_value = _get_overwrite(value)
+ if is_overwrite:
+ if seen_overwrite:
+ msg = create_error_message(
+ message="Can receive only one Overwrite value per super-step.",
+ error_code=ErrorCode.INVALID_CONCURRENT_GRAPH_UPDATE,
+ )
+ raise InvalidUpdateError(msg)
+ self.value = overwrite_value
+ seen_overwrite = True
+ continue
+ if not seen_overwrite:
+ self.value = self.operator(self.value, value)
+ return True
+
+ def get(self) -> Value:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
+
+ def checkpoint(self) -> Value:
+ return self.value
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/delta.py b/python/user_packages/Python313/site-packages/langgraph/channels/delta.py
new file mode 100644
index 0000000000000000000000000000000000000000..052ced50df5c5eaff3b7df7074d8379e2d88086f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/delta.py
@@ -0,0 +1,204 @@
+from __future__ import annotations
+
+import collections.abc
+import copy as _copy
+from collections.abc import Callable, Sequence
+from typing import Any, Generic
+
+from langgraph.checkpoint.base import PendingWrite
+from langgraph.checkpoint.serde.types import _DeltaSnapshot
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.channels.binop import _get_overwrite, _operators_equal, _strip_extras
+from langgraph.errors import (
+ EmptyChannelError,
+ ErrorCode,
+ InvalidUpdateError,
+ create_error_message,
+)
+
+__all__ = ("DeltaChannel",)
+
+
+class DeltaChannel(Generic[Value], BaseChannel[Any, Any, Any]):
+ """Reducer channel that stores only a sentinel in checkpoint blobs and
+ reconstructs state by replaying ancestor writes through the reducer.
+
+ !!! warning "Beta"
+
+ `DeltaChannel` is in beta. The API and on-disk representation may
+ change in future releases. Threads written with `DeltaChannel` today
+ are expected to remain readable, but the surrounding contract
+ (`BaseCheckpointSaver.get_delta_channel_history`, the
+ `_DeltaSnapshot` blob shape, the `counters_since_delta_snapshot`
+ metadata field) is not yet stable.
+
+ The reducer receives the current accumulated value and a batch of writes
+ in one call: `reducer(state, [write1, write2, ...]) -> new_state`.
+
+ Reducers must be deterministic and batching-invariant (associative across
+ folds): applying two consecutive write batches separately must produce the
+ same state as applying their concatenation once:
+
+ reducer(reducer(state, xs), ys) == reducer(state, xs + ys)
+
+ This lets LangGraph replay checkpointed writes in larger batches than they
+ were originally produced without changing reconstructed state.
+
+ Snapshot cadence is driven by two counters: per-channel update count and
+ total supersteps since last snapshot. `create_checkpoint` writes a full
+ `_DeltaSnapshot` blob when EITHER the update count reaches
+ `snapshot_frequency` OR the supersteps count reaches the system-wide
+ `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` bound (default 5000), bounding
+ replay depth even for channels that stop receiving writes.
+
+ Parameters:
+ reducer: `(state, list[writes]) -> new_state`. Must be deterministic
+ and batching-invariant as described above.
+ typ: The value type (e.g. `list`, `dict`). Inferred automatically
+ from the outer type when used inside `Annotated[T, DeltaChannel(...)]`.
+ snapshot_frequency: Every Nth update to this channel writes a snapshot
+ blob (default `1000`). Must be a positive int.
+ """
+
+ __slots__ = ("value", "reducer", "snapshot_frequency")
+ value: Value | Any
+
+ def __init__(
+ self,
+ reducer: Callable[[Any, Sequence[Any]], Any],
+ typ: type[Value] | None = None,
+ *,
+ snapshot_frequency: int = 1000,
+ ) -> None:
+ if snapshot_frequency <= 0:
+ raise ValueError(
+ f"snapshot_frequency must be a positive int, got {snapshot_frequency}"
+ )
+ if typ is None:
+ typ = list # type: ignore[assignment] # placeholder; overridden by _is_field_channel
+ super().__init__(typ)
+ self.reducer = reducer
+ self.snapshot_frequency = snapshot_frequency
+ typ = _strip_extras(typ)
+ if typ in (collections.abc.Sequence, collections.abc.MutableSequence):
+ typ = list
+ if typ in (collections.abc.Set, collections.abc.MutableSet):
+ typ = set
+ if typ in (collections.abc.Mapping, collections.abc.MutableMapping):
+ typ = dict
+ self.typ = typ
+ self.value: Any = MISSING
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, DeltaChannel):
+ return False
+ if self.snapshot_frequency != other.snapshot_frequency:
+ return False
+ return _operators_equal(self.reducer, other.reducer)
+
+ @property
+ def ValueType(self) -> Any:
+ return self.typ
+
+ @property
+ def UpdateType(self) -> Any:
+ return self.typ
+
+ def copy(self) -> Self:
+ new = self.__class__(
+ self.reducer, self.typ, snapshot_frequency=self.snapshot_frequency
+ )
+ new.key = self.key
+ new.value = self.value if self.value is MISSING else _copy.copy(self.value)
+ return new
+
+ def from_checkpoint(self, checkpoint: Any) -> Self:
+ """Initialize from a stored blob.
+
+ Blob types:
+ * `MISSING`: start empty; caller replays writes.
+ * `_DeltaSnapshot(value)`: restore value directly from snapshot.
+ * plain value (migration from old `BinaryOperatorAggregate` blobs):
+ use directly.
+ """
+ new = self.__class__(
+ self.reducer, self.typ, snapshot_frequency=self.snapshot_frequency
+ )
+ new.key = self.key
+ if checkpoint is MISSING:
+ new.value = self.typ()
+ elif isinstance(checkpoint, _DeltaSnapshot):
+ new.value = checkpoint.value
+ else:
+ new.value = checkpoint
+ return new
+
+ def replay_writes(self, writes: Sequence[PendingWrite]) -> None:
+ """Apply ancestor writes oldest-to-newest via a single reducer call.
+
+ If any write is an Overwrite, the last one in the sequence acts as
+ the reset point: its value becomes the new base and only writes
+ after it are passed to the reducer.
+ """
+ values = [v for _, _, v in writes]
+ if not values:
+ return
+ base = self.value
+ start = 0
+ for i, v in enumerate(values):
+ is_ow, ow_value = _get_overwrite(v)
+ if is_ow:
+ base = _copy.copy(ow_value) if ow_value is not None else self.typ()
+ start = i + 1
+ remaining = values[start:]
+ self.value = self.reducer(base, remaining) if remaining else base
+
+ def update(self, values: Sequence[Any]) -> bool:
+ if not values:
+ return False
+ overwrite_idx: int | None = None
+ for i, v in enumerate(values):
+ is_ow, _ = _get_overwrite(v)
+ if is_ow:
+ if overwrite_idx is not None:
+ msg = create_error_message(
+ message="Can receive only one Overwrite value per super-step.",
+ error_code=ErrorCode.INVALID_CONCURRENT_GRAPH_UPDATE,
+ )
+ raise InvalidUpdateError(msg)
+ overwrite_idx = i
+ if overwrite_idx is not None:
+ _, overwrite_value = _get_overwrite(values[overwrite_idx])
+ base = (
+ _copy.copy(overwrite_value)
+ if overwrite_value is not None
+ else self.typ()
+ )
+ remaining = [v for i, v in enumerate(values) if i != overwrite_idx]
+ self.value = self.reducer(base, remaining) if remaining else base
+ return True
+ base = self.typ() if self.value is MISSING else self.value
+ self.value = self.reducer(base, list(values))
+ return True
+
+ def get(self) -> Any:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
+
+ def checkpoint(self) -> Any:
+ """Return stored representation: always `MISSING`.
+
+ Snapshot decisions live in `create_checkpoint` (which has the channel
+ version) and write `_DeltaSnapshot(ch.get())` directly into
+ `channel_values`. For non-snapshot steps the channel does not appear
+ in `channel_values`; reconstruction walks ancestor writes via the
+ saver's `get_delta_channel_history`.
+ """
+ return MISSING
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/ephemeral_value.py b/python/user_packages/Python313/site-packages/langgraph/channels/ephemeral_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..108588d0b8276d0b818d53cd908d0563e7181035
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/ephemeral_value.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any, Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import EmptyChannelError, InvalidUpdateError
+
+__all__ = ("EphemeralValue",)
+
+
+class EphemeralValue(Generic[Value], BaseChannel[Value, Value, Value]):
+ """Stores the value received in the step immediately preceding, clears after."""
+
+ __slots__ = ("value", "guard")
+
+ value: Value | Any
+ guard: bool
+
+ def __init__(self, typ: Any, guard: bool = True) -> None:
+ super().__init__(typ)
+ self.guard = guard
+ self.value = MISSING
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, EphemeralValue) and value.guard == self.guard
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.guard)
+ empty.key = self.key
+ empty.value = self.value
+ return empty
+
+ def from_checkpoint(self, checkpoint: Value) -> Self:
+ empty = self.__class__(self.typ, self.guard)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ empty.value = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ if len(values) == 0:
+ if self.value is not MISSING:
+ self.value = MISSING
+ return True
+ else:
+ return False
+ if len(values) != 1 and self.guard:
+ raise InvalidUpdateError(
+ f"At key '{self.key}': EphemeralValue(guard=True) can receive only one value per step. Use guard=False if you want to store any one of multiple values."
+ )
+
+ self.value = values[-1]
+ return True
+
+ def get(self) -> Value:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
+
+ def checkpoint(self) -> Value:
+ return self.value
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/last_value.py b/python/user_packages/Python313/site-packages/langgraph/channels/last_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..54caac7581ea5e1929f89e2b8a21653621dfac37
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/last_value.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any, Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import (
+ EmptyChannelError,
+ ErrorCode,
+ InvalidUpdateError,
+ create_error_message,
+)
+
+__all__ = ("LastValue", "LastValueAfterFinish")
+
+
+class LastValue(Generic[Value], BaseChannel[Value, Value, Value]):
+ """Stores the last value received, can receive at most one value per step."""
+
+ __slots__ = ("value",)
+
+ value: Value | Any
+
+ def __init__(self, typ: Any, key: str = "") -> None:
+ super().__init__(typ, key)
+ self.value = MISSING
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, LastValue)
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.key)
+ empty.value = self.value
+ return empty
+
+ def from_checkpoint(self, checkpoint: Value) -> Self:
+ empty = self.__class__(self.typ, self.key)
+ if checkpoint is not MISSING:
+ empty.value = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ if len(values) == 0:
+ return False
+ if len(values) != 1:
+ msg = create_error_message(
+ message=f"At key '{self.key}': Can receive only one value per step. Use an Annotated key to handle multiple values.",
+ error_code=ErrorCode.INVALID_CONCURRENT_GRAPH_UPDATE,
+ )
+ raise InvalidUpdateError(msg)
+
+ self.value = values[-1]
+ return True
+
+ def get(self) -> Value:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
+
+ def checkpoint(self) -> Value:
+ return self.value
+
+
+class LastValueAfterFinish(
+ Generic[Value], BaseChannel[Value, Value, tuple[Value, bool]]
+):
+ """Stores the last value received, but only made available after finish().
+ Once made available, clears the value."""
+
+ __slots__ = ("value", "finished")
+
+ value: Value | Any
+ finished: bool
+
+ def __init__(self, typ: Any, key: str = "") -> None:
+ super().__init__(typ, key)
+ self.value = MISSING
+ self.finished = False
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, LastValueAfterFinish)
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def checkpoint(self) -> tuple[Value | Any, bool] | Any:
+ if self.value is MISSING:
+ return MISSING
+ return (self.value, self.finished)
+
+ def from_checkpoint(self, checkpoint: tuple[Value | Any, bool] | Any) -> Self:
+ empty = self.__class__(self.typ)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ empty.value, empty.finished = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value | Any]) -> bool:
+ if len(values) == 0:
+ return False
+
+ self.finished = False
+ self.value = values[-1]
+ return True
+
+ def consume(self) -> bool:
+ if self.finished:
+ self.finished = False
+ self.value = MISSING
+ return True
+
+ return False
+
+ def finish(self) -> bool:
+ if not self.finished and self.value is not MISSING:
+ self.finished = True
+ return True
+ else:
+ return False
+
+ def get(self) -> Value:
+ if self.value is MISSING or not self.finished:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING and self.finished
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/named_barrier_value.py b/python/user_packages/Python313/site-packages/langgraph/channels/named_barrier_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..d45644110f47956d7adb5ef9c2138eae597dcf3c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/named_barrier_value.py
@@ -0,0 +1,167 @@
+from collections.abc import Sequence
+from typing import Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import EmptyChannelError, InvalidUpdateError
+
+__all__ = ("NamedBarrierValue", "NamedBarrierValueAfterFinish")
+
+
+class NamedBarrierValue(Generic[Value], BaseChannel[Value, Value, set[Value]]):
+ """A channel that waits until all named values are received before making the value available."""
+
+ __slots__ = ("names", "seen")
+
+ names: set[Value]
+ seen: set[Value]
+
+ def __init__(self, typ: type[Value], names: set[Value]) -> None:
+ super().__init__(typ)
+ self.names = names
+ self.seen: set[str] = set()
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, NamedBarrierValue) and value.names == self.names
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.names)
+ empty.key = self.key
+ empty.seen = self.seen.copy()
+ return empty
+
+ def checkpoint(self) -> set[Value]:
+ return self.seen
+
+ def from_checkpoint(self, checkpoint: set[Value]) -> Self:
+ empty = self.__class__(self.typ, self.names)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ empty.seen = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ updated = False
+ for value in values:
+ if value in self.names:
+ if value not in self.seen:
+ self.seen.add(value)
+ updated = True
+ else:
+ raise InvalidUpdateError(
+ f"At key '{self.key}': Value {value} not in {self.names}"
+ )
+ return updated
+
+ def get(self) -> Value:
+ if self.seen != self.names:
+ raise EmptyChannelError()
+ return None
+
+ def is_available(self) -> bool:
+ return self.seen == self.names
+
+ def consume(self) -> bool:
+ if self.seen == self.names:
+ self.seen = set()
+ return True
+ return False
+
+
+class NamedBarrierValueAfterFinish(
+ Generic[Value], BaseChannel[Value, Value, set[Value]]
+):
+ """A channel that waits until all named values are received before making the value ready to be made available. It is only made available after finish() is called."""
+
+ __slots__ = ("names", "seen", "finished")
+
+ names: set[Value]
+ seen: set[Value]
+
+ def __init__(self, typ: type[Value], names: set[Value]) -> None:
+ super().__init__(typ)
+ self.names = names
+ self.seen: set[str] = set()
+ self.finished = False
+
+ def __eq__(self, value: object) -> bool:
+ return (
+ isinstance(value, NamedBarrierValueAfterFinish)
+ and value.names == self.names
+ )
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.names)
+ empty.key = self.key
+ empty.seen = self.seen.copy()
+ empty.finished = self.finished
+ return empty
+
+ def checkpoint(self) -> tuple[set[Value], bool]:
+ return (self.seen, self.finished)
+
+ def from_checkpoint(self, checkpoint: tuple[set[Value], bool]) -> Self:
+ empty = self.__class__(self.typ, self.names)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ empty.seen, empty.finished = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ updated = False
+ for value in values:
+ if value in self.names:
+ if value not in self.seen:
+ self.seen.add(value)
+ updated = True
+ else:
+ raise InvalidUpdateError(
+ f"At key '{self.key}': Value {value} not in {self.names}"
+ )
+ return updated
+
+ def get(self) -> Value:
+ if not self.finished or self.seen != self.names:
+ raise EmptyChannelError()
+ return None
+
+ def is_available(self) -> bool:
+ return self.finished and self.seen == self.names
+
+ def consume(self) -> bool:
+ if self.finished and self.seen == self.names:
+ self.finished = False
+ self.seen = set()
+ return True
+ return False
+
+ def finish(self) -> bool:
+ if not self.finished and self.seen == self.names:
+ self.finished = True
+ return True
+ else:
+ return False
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/topic.py b/python/user_packages/Python313/site-packages/langgraph/channels/topic.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f17d7c9e8152c9bbe7b779f404ad2f7701101dd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/topic.py
@@ -0,0 +1,94 @@
+from __future__ import annotations
+
+from collections.abc import Iterator, Sequence
+from typing import Any, Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import EmptyChannelError
+
+__all__ = ("Topic",)
+
+
+def _flatten(values: Sequence[Value | list[Value]]) -> Iterator[Value]:
+ for value in values:
+ if isinstance(value, list):
+ yield from value
+ else:
+ yield value
+
+
+class Topic(
+ Generic[Value],
+ BaseChannel[Sequence[Value], Value | list[Value], list[Value]],
+):
+ """A configurable PubSub Topic.
+
+ Args:
+ typ: The type of the value stored in the channel.
+ accumulate: Whether to accumulate values across steps. If `False`, the channel will be emptied after each step.
+ """
+
+ __slots__ = ("values", "accumulate")
+
+ def __init__(self, typ: type[Value], accumulate: bool = False) -> None:
+ super().__init__(typ)
+ # attrs
+ self.accumulate = accumulate
+ # state
+ self.values = list[Value]()
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, Topic) and value.accumulate == self.accumulate
+
+ @property
+ def ValueType(self) -> Any:
+ """The type of the value stored in the channel."""
+ return Sequence[self.typ] # type: ignore[name-defined]
+
+ @property
+ def UpdateType(self) -> Any:
+ """The type of the update received by the channel."""
+ return self.typ | list[self.typ] # type: ignore[name-defined]
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.accumulate)
+ empty.key = self.key
+ empty.values = self.values.copy()
+ return empty
+
+ def checkpoint(self) -> list[Value]:
+ return self.values
+
+ def from_checkpoint(self, checkpoint: list[Value]) -> Self:
+ empty = self.__class__(self.typ, self.accumulate)
+ empty.key = self.key
+ if checkpoint is not MISSING:
+ if isinstance(checkpoint, tuple):
+ # backwards compatibility
+ empty.values = checkpoint[1]
+ else:
+ empty.values = checkpoint
+ return empty
+
+ def update(self, values: Sequence[Value | list[Value]]) -> bool:
+ updated = False
+ if not self.accumulate:
+ updated = bool(self.values)
+ self.values = list[Value]()
+ if flat_values := tuple(_flatten(values)):
+ updated = True
+ self.values.extend(flat_values)
+ return updated
+
+ def get(self) -> Sequence[Value]:
+ if self.values:
+ return list(self.values)
+ else:
+ raise EmptyChannelError
+
+ def is_available(self) -> bool:
+ return bool(self.values)
diff --git a/python/user_packages/Python313/site-packages/langgraph/channels/untracked_value.py b/python/user_packages/Python313/site-packages/langgraph/channels/untracked_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcd55186b9ae7199205e8ad527adbb3bbf660e49
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/channels/untracked_value.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any, Generic
+
+from typing_extensions import Self
+
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel, Value
+from langgraph.errors import EmptyChannelError, InvalidUpdateError
+
+__all__ = ("UntrackedValue",)
+
+
+class UntrackedValue(Generic[Value], BaseChannel[Value, Value, Value]):
+ """Stores the last value received, never checkpointed."""
+
+ __slots__ = ("value", "guard")
+
+ guard: bool
+ value: Value | Any
+
+ def __init__(self, typ: type[Value], guard: bool = True) -> None:
+ super().__init__(typ)
+ self.guard = guard
+ self.value = MISSING
+
+ def __eq__(self, value: object) -> bool:
+ return isinstance(value, UntrackedValue) and value.guard == self.guard
+
+ @property
+ def ValueType(self) -> type[Value]:
+ """The type of the value stored in the channel."""
+ return self.typ
+
+ @property
+ def UpdateType(self) -> type[Value]:
+ """The type of the update received by the channel."""
+ return self.typ
+
+ def copy(self) -> Self:
+ """Return a copy of the channel."""
+ empty = self.__class__(self.typ, self.guard)
+ empty.key = self.key
+ empty.value = self.value
+ return empty
+
+ def checkpoint(self) -> Value | Any:
+ return MISSING
+
+ def from_checkpoint(self, checkpoint: Value) -> Self:
+ empty = self.__class__(self.typ, self.guard)
+ empty.key = self.key
+ return empty
+
+ def update(self, values: Sequence[Value]) -> bool:
+ if len(values) == 0:
+ return False
+ if len(values) != 1 and self.guard:
+ raise InvalidUpdateError(
+ f"At key '{self.key}': UntrackedValue(guard=True) can receive only one value per step. Use guard=False if you want to store any one of multiple values."
+ )
+
+ self.value = values[-1]
+ return True
+
+ def get(self) -> Value:
+ if self.value is MISSING:
+ raise EmptyChannelError()
+ return self.value
+
+ def is_available(self) -> bool:
+ return self.value is not MISSING
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__init__.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e42061190d539c20c4358771824837e8598da6c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__init__.py
@@ -0,0 +1,860 @@
+from __future__ import annotations
+
+import copy
+import logging
+from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ NamedTuple,
+ TypedDict,
+ TypeVar,
+)
+
+from langchain_core.runnables import RunnableConfig
+from typing_extensions import NotRequired
+
+from langgraph.checkpoint.base.id import uuid6
+from langgraph.checkpoint.serde.base import SerializerProtocol, maybe_add_typed_methods
+from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
+from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
+from langgraph.checkpoint.serde.types import (
+ ERROR,
+ INTERRUPT,
+ RESUME,
+ SCHEDULED,
+ ChannelProtocol,
+)
+
+V = TypeVar("V", int, float, str)
+PendingWrite = tuple[str, str, Any]
+
+
+logger = logging.getLogger(__name__)
+
+
+# Marked as total=False to allow for future expansion.
+class CheckpointMetadata(TypedDict, total=False):
+ """Metadata associated with a checkpoint."""
+
+ source: Literal["input", "loop", "update", "fork"]
+ """The source of the checkpoint.
+
+ - `"input"`: The checkpoint was created from an input to invoke/stream/batch.
+ - `"loop"`: The checkpoint was created from inside the pregel loop.
+ - `"update"`: The checkpoint was created from a manual state update.
+ - `"fork"`: The checkpoint was created as a copy of another checkpoint.
+ """
+ step: int
+ """The step number of the checkpoint.
+
+ `-1` for the first `"input"` checkpoint.
+ `0` for the first `"loop"` checkpoint.
+ `...` for the `nth` checkpoint afterwards.
+ """
+ parents: dict[str, str]
+ """The IDs of the parent checkpoints.
+
+ Mapping from checkpoint namespace to checkpoint ID.
+ """
+ run_id: str
+ """The ID of the run that created this checkpoint."""
+ counters_since_delta_snapshot: dict[str, tuple[int, int]]
+ """Per-channel counters since the last `_DeltaSnapshot` was written.
+
+ !!! warning "Beta"
+
+ This metadata field backs `DeltaChannel` (beta). The key name and
+ contents may change while the delta-channel design stabilizes.
+
+ Maps channel name -> `(updates, supersteps)`:
+
+ - index 0 (`updates`): number of supersteps that wrote to this channel
+ since its last snapshot blob.
+ - index 1 (`supersteps`): total supersteps elapsed since this channel's
+ last snapshot, regardless of whether the channel was written.
+
+ A snapshot fires when EITHER `updates >= ch.snapshot_frequency` OR
+ `supersteps >= DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` (system-wide bound,
+ default 5000, env `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`).
+ The supersteps bound prevents unbounded ancestor walks on threads where
+ a delta channel exists but is no longer being updated.
+
+ Absent on threads that don't use delta channels. Persisted as a
+ 2-element list in JSON (no native tuple).
+ """
+
+
+ChannelVersions = dict[str, str | int | float]
+
+
+class Checkpoint(TypedDict):
+ """State snapshot at a given point in time."""
+
+ v: int
+ """The version of the checkpoint format. Currently `1`."""
+ id: str
+ """The ID of the checkpoint.
+
+ This is both unique and monotonically increasing, so can be used for sorting
+ checkpoints from first to last."""
+ ts: str
+ """The timestamp of the checkpoint in ISO 8601 format."""
+ channel_values: dict[str, Any]
+ """The values of the channels at the time of the checkpoint.
+
+ Mapping from channel name to deserialized channel snapshot value.
+ """
+ channel_versions: ChannelVersions
+ """The versions of the channels at the time of the checkpoint.
+
+ The keys are channel names and the values are monotonically increasing
+ version strings for each channel.
+ """
+ versions_seen: dict[str, ChannelVersions]
+ """Map from node ID to map from channel name to version seen.
+
+ This keeps track of the versions of the channels that each node has seen.
+ Used to determine which nodes to execute next.
+ """
+ updated_channels: list[str] | None
+ """The channels that were updated in this checkpoint.
+ """
+
+
+def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
+ return Checkpoint(
+ v=checkpoint["v"],
+ ts=checkpoint["ts"],
+ id=checkpoint["id"],
+ channel_values=checkpoint["channel_values"].copy(),
+ channel_versions=checkpoint["channel_versions"].copy(),
+ versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()},
+ pending_sends=checkpoint.get("pending_sends", []).copy(),
+ updated_channels=checkpoint.get("updated_channels", None),
+ )
+
+
+class CheckpointTuple(NamedTuple):
+ """A tuple containing a checkpoint and its associated data."""
+
+ config: RunnableConfig
+ checkpoint: Checkpoint
+ metadata: CheckpointMetadata
+ parent_config: RunnableConfig | None = None
+ pending_writes: list[PendingWrite] | None = None
+
+
+class DeltaChannelHistory(TypedDict):
+ """Per-channel result entry from `BaseCheckpointSaver.get_delta_channel_history`.
+
+ !!! warning "Beta"
+
+ Part of the `DeltaChannel` support surface; in beta. Field names and
+ semantics may change.
+
+ Storage-level view of what one channel contributed across the ancestor
+ chain of a target checkpoint:
+
+ * `writes` — on-path deltas oldest→newest as `PendingWrite` tuples.
+ Always present; possibly empty. Already filtered to one channel.
+ Writes stored at the target checkpoint itself are pending for the
+ next super-step and are excluded.
+ * `seed` — the stored value at the nearest ancestor whose
+ `channel_values[ch]` is populated. Omitted if the walk reached the
+ root without finding any stored value (consumer treats absence as
+ "start empty"). Typically a `_DeltaSnapshot` for delta channels with
+ finite snapshot frequency, or a plain value for threads migrated
+ from a pre-delta channel type.
+ """
+
+ writes: list[PendingWrite]
+ seed: NotRequired[Any]
+
+
+class BaseCheckpointSaver(Generic[V]):
+ """Base class for creating a graph checkpointer.
+
+ Checkpointers allow LangGraph agents to persist their state
+ within and across multiple interactions.
+
+ When a checkpointer is configured, you should pass a `thread_id` in the config when
+ invoking the graph:
+
+ ```python
+ config = {"configurable": {"thread_id": "my-thread"}}
+ graph.invoke(inputs, config)
+ ```
+
+ The `thread_id` is the primary key used to store and retrieve checkpoints. Without
+ it, the checkpointer cannot save state, resume from interrupts, or enable
+ time-travel debugging.
+
+ How you choose ``thread_id`` depends on your use case:
+
+ - **Single-shot workflows**: Use a unique ID (e.g., uuid4) for each run when
+ executions are independent.
+ - **Conversational memory**: Reuse the same `thread_id` across invocations
+ to accumulate state (e.g., chat history) within a conversation.
+
+ Attributes:
+ serde (SerializerProtocol): Serializer for encoding/decoding checkpoints.
+
+ Note:
+ When creating a custom checkpoint saver, consider implementing async
+ versions to avoid blocking the main thread.
+ """
+
+ serde: SerializerProtocol = JsonPlusSerializer()
+
+ def __init__(
+ self,
+ *,
+ serde: SerializerProtocol | None = None,
+ ) -> None:
+ self.serde = maybe_add_typed_methods(serde or self.serde)
+
+ @property
+ def config_specs(self) -> list:
+ """Define the configuration options for the checkpoint saver.
+
+ Returns:
+ list: List of configuration field specs.
+ """
+ return []
+
+ def get(self, config: RunnableConfig) -> Checkpoint | None:
+ """Fetch a checkpoint using the given configuration.
+
+ Args:
+ config: Configuration specifying which checkpoint to retrieve.
+
+ Returns:
+ The requested checkpoint, or `None` if not found.
+ """
+ if value := self.get_tuple(config):
+ return value.checkpoint
+
+ def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
+ """Fetch a checkpoint tuple using the given configuration.
+
+ Args:
+ config: Configuration specifying which checkpoint to retrieve.
+
+ Returns:
+ The requested checkpoint tuple, or `None` if not found.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ def list(
+ self,
+ config: RunnableConfig | None,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> Iterator[CheckpointTuple]:
+ """List checkpoints that match the given criteria.
+
+ Args:
+ config: Base configuration for filtering checkpoints.
+ filter: Additional filtering criteria.
+ before: List checkpoints created before this configuration.
+ limit: Maximum number of checkpoints to return.
+
+ Returns:
+ Iterator of matching checkpoint tuples.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ def put(
+ self,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ """Store a checkpoint with its configuration and metadata.
+
+ Args:
+ config: Configuration for the checkpoint.
+ checkpoint: The checkpoint to store.
+ metadata: Additional metadata for the checkpoint.
+ new_versions: New channel versions as of this write.
+
+ Returns:
+ RunnableConfig: Updated configuration after storing the checkpoint.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ def put_writes(
+ self,
+ config: RunnableConfig,
+ writes: Sequence[tuple[str, Any]],
+ task_id: str,
+ task_path: str = "",
+ ) -> None:
+ """Store intermediate writes linked to a checkpoint.
+
+ Args:
+ config: Configuration of the related checkpoint.
+ writes: List of writes to store.
+ task_id: Identifier for the task creating the writes.
+ task_path: Path of the task creating the writes.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ def delete_thread(
+ self,
+ thread_id: str,
+ ) -> None:
+ """Delete all checkpoints and writes associated with a specific thread ID.
+
+ Args:
+ thread_id: The thread ID whose checkpoints should be deleted.
+ """
+ raise NotImplementedError
+
+ def delete_for_runs(
+ self,
+ run_ids: Sequence[str],
+ ) -> None:
+ """Delete all checkpoints and writes associated with the given run IDs.
+
+ Args:
+ run_ids: The run IDs whose checkpoints should be deleted.
+
+ !!! warning "DeltaChannel"
+
+ Deleting a run that produced ancestor `checkpoint_writes` — or
+ the only `_DeltaSnapshot` blob — for a still-live thread will
+ break reconstruction of any `DeltaChannel` whose history
+ depended on those rows. See the `DeltaChannel` note on `prune`
+ for safe-recovery strategies.
+ """
+ raise NotImplementedError
+
+ def copy_thread(
+ self,
+ source_thread_id: str,
+ target_thread_id: str,
+ ) -> None:
+ """Copy all checkpoints and writes from one thread to another.
+
+ Args:
+ source_thread_id: The thread ID to copy from.
+ target_thread_id: The thread ID to copy to.
+
+ !!! warning "DeltaChannel"
+
+ Implementations must copy the **complete** parent chain (all
+ ancestor checkpoints and their `checkpoint_writes`) — copying
+ only the head checkpoint will leave the target thread with
+ `DeltaChannel` state that cannot be reconstructed (no path back
+ to a `_DeltaSnapshot` ancestor). Equivalently, the copy must
+ include enough ancestors that every `DeltaChannel`-backed key
+ has either a `_DeltaSnapshot` in `channel_values` somewhere in
+ the chain, or a complete write history back to the chain root.
+ """
+ raise NotImplementedError
+
+ def prune(
+ self,
+ thread_ids: Sequence[str],
+ *,
+ strategy: str = "keep_latest",
+ ) -> None:
+ """Prune checkpoints for the given threads.
+
+ Args:
+ thread_ids: The thread IDs to prune.
+ strategy: The pruning strategy. `"keep_latest"` retains only the most
+ recent checkpoint per namespace. `"delete"` removes all checkpoints.
+
+ !!! warning "DeltaChannel"
+
+ Custom implementations must be `DeltaChannel`-aware. `DeltaChannel`
+ stores only a sentinel in `channel_values` for non-snapshot steps;
+ reconstruction walks the parent chain via
+ `get_delta_channel_history`, accumulating rows from
+ `checkpoint_writes` until it reaches an ancestor whose
+ `channel_values` contains a `_DeltaSnapshot` blob (written every
+ `snapshot_frequency` updates).
+
+ A naive `"keep_latest"` that drops intermediate checkpoints and
+ their writes can sever that chain: the surviving "latest"
+ checkpoint is rarely a snapshot point itself, so its delta
+ channels would silently reconstruct as empty (no error raised —
+ `get_delta_channel_history` simply returns no `seed`). Safe
+ options when the graph uses `DeltaChannel`:
+
+ * Walk back from each kept checkpoint and preserve every
+ ancestor (plus its `checkpoint_writes`) up to the nearest one
+ whose `channel_values` already contains a `_DeltaSnapshot` for
+ every `DeltaChannel`-backed key.
+ * Force a fresh snapshot on the kept checkpoint before deleting
+ ancestors — rewrite `channel_values[k] = _DeltaSnapshot(value)`
+ for each delta channel `k` (resolving `value` via the existing
+ ancestor walk first), then prune.
+ * Skip pruning threads whose graph uses `DeltaChannel` until one
+ of the above is implemented.
+ """
+ raise NotImplementedError
+
+ async def aget(self, config: RunnableConfig) -> Checkpoint | None:
+ """Asynchronously fetch a checkpoint using the given configuration.
+
+ Args:
+ config: Configuration specifying which checkpoint to retrieve.
+
+ Returns:
+ The requested checkpoint, or `None` if not found.
+ """
+ if value := await self.aget_tuple(config):
+ return value.checkpoint
+
+ async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
+ """Asynchronously fetch a checkpoint tuple using the given configuration.
+
+ Args:
+ config: Configuration specifying which checkpoint to retrieve.
+
+ Returns:
+ The requested checkpoint tuple, or `None` if not found.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ async def alist(
+ self,
+ config: RunnableConfig | None,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[CheckpointTuple]:
+ """Asynchronously list checkpoints that match the given criteria.
+
+ Args:
+ config: Base configuration for filtering checkpoints.
+ filter: Additional filtering criteria for metadata.
+ before: List checkpoints created before this configuration.
+ limit: Maximum number of checkpoints to return.
+
+ Returns:
+ Async iterator of matching checkpoint tuples.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+ yield
+
+ async def aput(
+ self,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ """Asynchronously store a checkpoint with its configuration and metadata.
+
+ Args:
+ config: Configuration for the checkpoint.
+ checkpoint: The checkpoint to store.
+ metadata: Additional metadata for the checkpoint.
+ new_versions: New channel versions as of this write.
+
+ Returns:
+ RunnableConfig: Updated configuration after storing the checkpoint.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ async def aput_writes(
+ self,
+ config: RunnableConfig,
+ writes: Sequence[tuple[str, Any]],
+ task_id: str,
+ task_path: str = "",
+ ) -> None:
+ """Asynchronously store intermediate writes linked to a checkpoint.
+
+ Args:
+ config: Configuration of the related checkpoint.
+ writes: List of writes to store.
+ task_id: Identifier for the task creating the writes.
+ task_path: Path of the task creating the writes.
+
+ Raises:
+ NotImplementedError: Implement this method in your custom checkpoint saver.
+ """
+ raise NotImplementedError
+
+ async def adelete_thread(
+ self,
+ thread_id: str,
+ ) -> None:
+ """Delete all checkpoints and writes associated with a specific thread ID.
+
+ Args:
+ thread_id: The thread ID whose checkpoints should be deleted.
+ """
+ raise NotImplementedError
+
+ async def adelete_for_runs(
+ self,
+ run_ids: Sequence[str],
+ ) -> None:
+ """Asynchronously delete all checkpoints and writes for the given run IDs.
+
+ Args:
+ run_ids: The run IDs whose checkpoints should be deleted.
+
+ !!! warning "DeltaChannel"
+
+ See `delete_for_runs` — deleting rows a still-live thread's
+ `DeltaChannel` reconstruction depends on (writes between the
+ head and its nearest `_DeltaSnapshot` ancestor) will silently
+ corrupt that channel's state.
+ """
+ raise NotImplementedError
+
+ async def acopy_thread(
+ self,
+ source_thread_id: str,
+ target_thread_id: str,
+ ) -> None:
+ """Asynchronously copy all checkpoints and writes from one thread to another.
+
+ Args:
+ source_thread_id: The thread ID to copy from.
+ target_thread_id: The thread ID to copy to.
+
+ !!! warning "DeltaChannel"
+
+ See `copy_thread` — the copy must carry the complete parent
+ chain (or at least back to a `_DeltaSnapshot` ancestor for every
+ `DeltaChannel`) so the target thread can reconstruct delta
+ state.
+ """
+ raise NotImplementedError
+
+ async def aprune(
+ self,
+ thread_ids: Sequence[str],
+ *,
+ strategy: str = "keep_latest",
+ ) -> None:
+ """Asynchronously prune checkpoints for the given threads.
+
+ Args:
+ thread_ids: The thread IDs to prune.
+ strategy: The pruning strategy. `"keep_latest"` retains only the most
+ recent checkpoint per namespace. `"delete"` removes all checkpoints.
+
+ !!! warning "DeltaChannel"
+
+ See `prune` for the full `DeltaChannel` caveat. In short:
+ `"keep_latest"` must not drop ancestor checkpoints / writes that
+ sit between the kept checkpoint and the nearest `_DeltaSnapshot`
+ ancestor, or delta channels will silently reconstruct as empty.
+ """
+ raise NotImplementedError
+
+ def get_delta_channel_history(
+ self, *, config: RunnableConfig, channels: Sequence[str]
+ ) -> Mapping[str, DeltaChannelHistory]:
+ """Walk the parent chain returning per-channel writes + seed.
+
+ !!! warning "Beta"
+
+ This method is part of the `DeltaChannel` support surface and is
+ in beta. The signature, return shape (`DeltaChannelHistory`), and
+ interaction with `_DeltaSnapshot` blobs may change. Override at
+ your own risk; the default implementation will continue to work
+ against the public `BaseCheckpointSaver` contract.
+
+ For each requested channel, walks ancestors of the checkpoint
+ identified by `config` (following `parent_config`) and accumulates
+ `pending_writes` for that channel. The walk terminates per-channel
+ at the nearest ancestor whose `channel_values[ch]` is populated;
+ that value is returned as `seed`. If the walk reaches the root
+ without finding a stored value, `seed` is omitted from that
+ channel's entry — the consumer treats the absence as "start
+ empty."
+
+ Walks the **parent chain** (not `list(before=...)`): for forked
+ threads, only on-path ancestors contribute.
+
+ The default implementation walks `get_tuple` + `parent_config`
+ once for all channels — each ancestor visited once, not once per
+ channel. Savers with direct storage access (`InMemorySaver`,
+ `PostgresSaver`) override for performance; the return contract is
+ fixed here.
+
+ Args:
+ config: Configuration identifying the target checkpoint.
+ channels: Channel names to walk for. Empty → empty mapping.
+
+ Returns:
+ Per-channel `DeltaChannelHistory` for every name in `channels`.
+ """
+ if not channels:
+ return {}
+ collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
+ seed_by_ch: dict[str, Any] = {}
+ remaining: set[str] = set(channels)
+ target_tuple = self.get_tuple(config)
+ cursor_config: RunnableConfig | None = (
+ target_tuple.parent_config if target_tuple else None
+ )
+ while cursor_config is not None and remaining:
+ tup = self.get_tuple(cursor_config)
+ if tup is None:
+ break
+ if tup.pending_writes:
+ for write in reversed(tup.pending_writes):
+ ch = write[1]
+ if ch in remaining:
+ collected_by_ch[ch].append(write)
+ for ch in list(remaining):
+ if ch in tup.checkpoint["channel_values"]:
+ seed_by_ch[ch] = tup.checkpoint["channel_values"][ch]
+ remaining.discard(ch)
+ cursor_config = tup.parent_config
+ result: dict[str, DeltaChannelHistory] = {}
+ for ch in channels:
+ entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))}
+ if ch in seed_by_ch:
+ entry["seed"] = seed_by_ch[ch]
+ result[ch] = entry
+ return result
+
+ async def aget_delta_channel_history(
+ self, *, config: RunnableConfig, channels: Sequence[str]
+ ) -> Mapping[str, DeltaChannelHistory]:
+ """Async version of `get_delta_channel_history`.
+
+ !!! warning "Beta"
+
+ This method is part of the `DeltaChannel` support surface and is
+ in beta. See `get_delta_channel_history` for caveats.
+ """
+ if not channels:
+ return {}
+ collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
+ seed_by_ch: dict[str, Any] = {}
+ remaining: set[str] = set(channels)
+ target_tuple = await self.aget_tuple(config)
+ cursor_config: RunnableConfig | None = (
+ target_tuple.parent_config if target_tuple else None
+ )
+ while cursor_config is not None and remaining:
+ tup = await self.aget_tuple(cursor_config)
+ if tup is None:
+ break
+ if tup.pending_writes:
+ for write in reversed(tup.pending_writes):
+ ch = write[1]
+ if ch in remaining:
+ collected_by_ch[ch].append(write)
+ for ch in list(remaining):
+ if ch in tup.checkpoint["channel_values"]:
+ seed_by_ch[ch] = tup.checkpoint["channel_values"][ch]
+ remaining.discard(ch)
+ cursor_config = tup.parent_config
+ result: dict[str, DeltaChannelHistory] = {}
+ for ch in channels:
+ entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))}
+ if ch in seed_by_ch:
+ entry["seed"] = seed_by_ch[ch]
+ result[ch] = entry
+ return result
+
+ def get_next_version(self, current: V | None, channel: None) -> V:
+ """Generate the next version ID for a channel.
+
+ Default is to use integer versions, incrementing by `1`.
+
+ If you override, you can use `str`/`int`/`float` versions, as long as they are monotonically increasing.
+
+ Args:
+ current: The current version identifier (`int`, `float`, or `str`).
+ channel: Deprecated argument, kept for backwards compatibility.
+
+ Returns:
+ V: The next version identifier, which must be increasing.
+ """
+ if isinstance(current, str):
+ raise NotImplementedError
+ elif current is None:
+ return 1
+ else:
+ return current + 1
+
+ def with_allowlist(
+ self, extra_allowlist: Collection[tuple[str, ...]]
+ ) -> BaseCheckpointSaver[V]:
+ """Return a shallow clone with a derived msgpack allowlist."""
+ serde = _with_msgpack_allowlist(self.serde, extra_allowlist)
+ if serde is self.serde:
+ return self
+ clone = copy.copy(self)
+ clone.serde = maybe_add_typed_methods(serde)
+ return clone
+
+
+def _with_msgpack_allowlist(
+ serde: SerializerProtocol, extra_allowlist: Collection[tuple[str, ...]]
+) -> SerializerProtocol:
+ if isinstance(serde, JsonPlusSerializer):
+ return serde.with_msgpack_allowlist(extra_allowlist)
+ if isinstance(serde, EncryptedSerializer):
+ inner = serde.serde
+ if isinstance(inner, JsonPlusSerializer):
+ updated_inner = inner.with_msgpack_allowlist(extra_allowlist)
+ if updated_inner is inner:
+ return serde
+ return EncryptedSerializer(serde.cipher, updated_inner)
+ logger.warning(
+ "Serializer %s does not support msgpack allowlist. "
+ "Strict msgpack deserialization will not be enforced.",
+ type(serde).__name__,
+ )
+ return serde
+
+
+class EmptyChannelError(Exception):
+ """Raised when attempting to get the value of a channel that hasn't been updated
+ for the first time yet."""
+
+ pass
+
+
+def get_checkpoint_id(config: RunnableConfig) -> str | None:
+ """Get checkpoint ID."""
+ return config["configurable"].get("checkpoint_id")
+
+
+def get_checkpoint_metadata(
+ config: RunnableConfig, metadata: CheckpointMetadata
+) -> CheckpointMetadata:
+ """Get checkpoint metadata in a backwards-compatible manner."""
+ metadata = {
+ k: v.replace("\u0000", "") if isinstance(v, str) else v
+ for k, v in metadata.items()
+ }
+ for obj in (config.get("metadata"), config.get("configurable")):
+ if not obj:
+ continue
+ for key, v in obj.items():
+ if key in metadata or key in EXCLUDED_METADATA_KEYS or key.startswith("__"):
+ continue
+ elif isinstance(v, str):
+ metadata[key] = v.replace("\u0000", "")
+ elif isinstance(v, (int, bool, float)):
+ metadata[key] = v
+ return metadata
+
+
+def get_serializable_checkpoint_metadata(
+ config: RunnableConfig, metadata: CheckpointMetadata
+) -> CheckpointMetadata:
+ """Get checkpoint metadata in a backwards-compatible manner."""
+ checkpoint_metadata = get_checkpoint_metadata(config, metadata)
+ if "writes" in checkpoint_metadata:
+ checkpoint_metadata.pop("writes")
+ return checkpoint_metadata
+
+
+"""
+Mapping from error type to error index.
+Regular writes just map to their index in the list of writes being saved.
+Special writes (e.g. errors) map to negative indices, to avoid those writes from
+conflicting with regular writes.
+Each Checkpointer implementation should use this mapping in put_writes.
+"""
+WRITES_IDX_MAP = {ERROR: -1, SCHEDULED: -2, INTERRUPT: -3, RESUME: -4}
+
+EXCLUDED_METADATA_KEYS = {
+ "thread_id",
+ "checkpoint_id",
+ "checkpoint_ns",
+ "checkpoint_map",
+ "langgraph_step",
+ "langgraph_node",
+ "langgraph_triggers",
+ "langgraph_path",
+ "langgraph_checkpoint_ns",
+}
+
+# --- below are deprecated utilities used by past versions of LangGraph ---
+
+LATEST_VERSION = 2
+
+
+def empty_checkpoint() -> Checkpoint:
+ from datetime import datetime, timezone
+
+ return Checkpoint(
+ v=LATEST_VERSION,
+ id=str(uuid6(clock_seq=-2)),
+ ts=datetime.now(timezone.utc).isoformat(),
+ channel_values={},
+ channel_versions={},
+ versions_seen={},
+ pending_sends=[],
+ updated_channels=None,
+ )
+
+
+def create_checkpoint(
+ checkpoint: Checkpoint,
+ channels: Mapping[str, ChannelProtocol] | None,
+ step: int,
+ *,
+ id: str | None = None,
+) -> Checkpoint:
+ """Create a checkpoint for the given channels."""
+ from datetime import datetime, timezone
+
+ ts = datetime.now(timezone.utc).isoformat()
+ if channels is None:
+ values = checkpoint["channel_values"]
+ else:
+ values = {}
+ for k, v in channels.items():
+ if k not in checkpoint["channel_versions"]:
+ continue
+ try:
+ values[k] = v.checkpoint()
+ except EmptyChannelError:
+ pass
+ return Checkpoint(
+ v=LATEST_VERSION,
+ ts=ts,
+ id=id or str(uuid6(clock_seq=step)),
+ channel_values=values,
+ channel_versions=checkpoint["channel_versions"],
+ versions_seen=checkpoint["versions_seen"],
+ pending_sends=checkpoint.get("pending_sends", []),
+ updated_channels=None,
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..691964761e988f89d3a197023949636d8800342a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e49ddb1c0e480ce8e9186d4683632486c7962a76
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/id.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/id.py
new file mode 100644
index 0000000000000000000000000000000000000000..30abc48a509601216fe7ddee3be55ceaa6cd93bd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/id.py
@@ -0,0 +1,109 @@
+"""Adapted from
+https://github.com/oittaa/uuid6-python/blob/main/src/uuid6/__init__.py#L95
+Bundled in to avoid install issues with uuid6 package
+"""
+
+from __future__ import annotations
+
+import random
+import time
+import uuid
+
+_last_v6_timestamp = None
+
+
+class UUID(uuid.UUID):
+ r"""UUID draft version objects"""
+
+ __slots__ = ()
+
+ def __init__(
+ self,
+ hex: str | None = None,
+ bytes: bytes | None = None,
+ bytes_le: bytes | None = None,
+ fields: tuple[int, int, int, int, int, int] | None = None,
+ int: int | None = None,
+ version: int | None = None,
+ *,
+ is_safe: uuid.SafeUUID = uuid.SafeUUID.unknown,
+ ) -> None:
+ r"""Create a UUID."""
+
+ if int is None or [hex, bytes, bytes_le, fields].count(None) != 4:
+ return super().__init__(
+ hex=hex,
+ bytes=bytes,
+ bytes_le=bytes_le,
+ fields=fields,
+ int=int,
+ version=version,
+ is_safe=is_safe,
+ )
+ if not 0 <= int < 1 << 128:
+ raise ValueError("int is out of range (need a 128-bit value)")
+ if version is not None:
+ if not 6 <= version <= 8:
+ raise ValueError("illegal version number")
+ # Set the variant to RFC 4122.
+ int &= ~(0xC000 << 48)
+ int |= 0x8000 << 48
+ # Set the version number.
+ int &= ~(0xF000 << 64)
+ int |= version << 76
+ super().__init__(int=int, is_safe=is_safe)
+
+ @property
+ def subsec(self) -> int:
+ return ((self.int >> 64) & 0x0FFF) << 8 | ((self.int >> 54) & 0xFF)
+
+ @property
+ def time(self) -> int:
+ if self.version == 6:
+ return (
+ (self.time_low << 28)
+ | (self.time_mid << 12)
+ | (self.time_hi_version & 0x0FFF)
+ )
+ if self.version == 7:
+ return self.int >> 80
+ if self.version == 8:
+ return (self.int >> 80) * 10**6 + _subsec_decode(self.subsec)
+ return super().time
+
+
+def _subsec_decode(value: int) -> int:
+ return -(-value * 10**6 // 2**20)
+
+
+def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID:
+ r"""UUID version 6 is a field-compatible version of UUIDv1, reordered for
+ improved DB locality. It is expected that UUIDv6 will primarily be
+ used in contexts where there are existing v1 UUIDs. Systems that do
+ not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead.
+
+ If 'node' is not given, a random 48-bit number is chosen.
+
+ If 'clock_seq' is given, it is used as the sequence number;
+ otherwise a random 14-bit sequence number is chosen."""
+
+ global _last_v6_timestamp
+
+ nanoseconds = time.time_ns()
+ # 0x01b21dd213814000 is the number of 100-ns intervals between the
+ # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
+ timestamp = nanoseconds // 100 + 0x01B21DD213814000
+ if _last_v6_timestamp is not None and timestamp <= _last_v6_timestamp:
+ timestamp = _last_v6_timestamp + 1
+ _last_v6_timestamp = timestamp
+ if clock_seq is None:
+ clock_seq = random.getrandbits(14) # instead of stable storage
+ if node is None:
+ node = random.getrandbits(48)
+ time_high_and_time_mid = (timestamp >> 12) & 0xFFFFFFFFFFFF
+ time_low_and_version = timestamp & 0x0FFF
+ uuid_int = time_high_and_time_mid << 80
+ uuid_int |= time_low_and_version << 64
+ uuid_int |= (clock_seq & 0x3FFF) << 48
+ uuid_int |= node & 0xFFFFFFFFFFFF
+ return UUID(int=uuid_int, version=6)
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/py.typed b/python/user_packages/Python313/site-packages/langgraph/checkpoint/base/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__init__.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80043c71060dea0cd56de974e6505049ce0cd2ad
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__init__.py
@@ -0,0 +1,704 @@
+from __future__ import annotations
+
+import logging
+import os
+import pickle
+import random
+import shutil
+from collections import defaultdict
+from collections.abc import AsyncIterator, Iterator, Mapping, Sequence
+from contextlib import AbstractAsyncContextManager, AbstractContextManager, ExitStack
+from types import TracebackType
+from typing import Any
+
+from langchain_core.runnables import RunnableConfig
+
+from langgraph.checkpoint.base import (
+ WRITES_IDX_MAP,
+ BaseCheckpointSaver,
+ ChannelVersions,
+ Checkpoint,
+ CheckpointMetadata,
+ CheckpointTuple,
+ DeltaChannelHistory,
+ PendingWrite,
+ SerializerProtocol,
+ get_checkpoint_id,
+ get_checkpoint_metadata,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class InMemorySaver(
+ BaseCheckpointSaver[str], AbstractContextManager, AbstractAsyncContextManager
+):
+ """An in-memory checkpoint saver.
+
+ This checkpoint saver stores checkpoints in memory using a `defaultdict`.
+
+ Note:
+ Only use `InMemorySaver` for debugging or testing purposes.
+ For production use cases we recommend installing [langgraph-checkpoint-postgres](https://pypi.org/project/langgraph-checkpoint-postgres/) and using `PostgresSaver` / `AsyncPostgresSaver`.
+
+ If you are using LangSmith Deployment, no checkpointer needs to be specified. The correct managed checkpointer will be used automatically.
+
+ Args:
+ serde: The serializer to use for serializing and deserializing checkpoints.
+
+ Example:
+ ```python
+ import asyncio
+
+ from langgraph.checkpoint.memory import InMemorySaver
+ from langgraph.graph import StateGraph
+
+ builder = StateGraph(int)
+ builder.add_node("add_one", lambda x: x + 1)
+ builder.set_entry_point("add_one")
+ builder.set_finish_point("add_one")
+
+ memory = InMemorySaver()
+ graph = builder.compile(checkpointer=memory)
+ coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}})
+ asyncio.run(coro) # Output: 2
+ ```
+ """
+
+ # thread ID -> checkpoint NS -> checkpoint ID -> checkpoint mapping
+ storage: defaultdict[
+ str,
+ dict[str, dict[str, tuple[tuple[str, bytes], tuple[str, bytes], str | None]]],
+ ]
+ # (thread ID, checkpoint NS, checkpoint ID) -> (task ID, write idx)
+ writes: defaultdict[
+ tuple[str, str, str],
+ dict[tuple[str, int], tuple[str, str, tuple[str, bytes], str]],
+ ]
+ blobs: dict[
+ tuple[
+ str, str, str, str | int | float
+ ], # thread id, checkpoint ns, channel, version
+ tuple[str, bytes],
+ ]
+
+ def __init__(
+ self,
+ *,
+ serde: SerializerProtocol | None = None,
+ factory: type[defaultdict] = defaultdict,
+ ) -> None:
+ super().__init__(serde=serde)
+ self.storage = factory(lambda: defaultdict(dict))
+ self.writes = factory(dict)
+ self.blobs = factory()
+ self.stack = ExitStack()
+ if factory is not defaultdict:
+ self.stack.enter_context(self.storage) # type: ignore[arg-type]
+ self.stack.enter_context(self.writes) # type: ignore[arg-type]
+ self.stack.enter_context(self.blobs) # type: ignore[arg-type]
+
+ def __enter__(self) -> InMemorySaver:
+ self.stack.__enter__()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ return self.stack.__exit__(exc_type, exc_value, traceback)
+
+ async def __aenter__(self) -> InMemorySaver:
+ self.stack.__enter__()
+ return self
+
+ async def __aexit__(
+ self,
+ __exc_type: type[BaseException] | None,
+ __exc_value: BaseException | None,
+ __traceback: TracebackType | None,
+ ) -> bool | None:
+ return self.stack.__exit__(__exc_type, __exc_value, __traceback)
+
+ def _load_blobs(
+ self,
+ thread_id: str,
+ checkpoint_ns: str,
+ versions: ChannelVersions,
+ ) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for k, ver in versions.items():
+ kk = (thread_id, checkpoint_ns, k, ver)
+ if kk not in self.blobs:
+ continue
+ vv = self.blobs[kk]
+ if vv[0] == "empty":
+ continue
+ result[k] = self.serde.loads_typed(vv)
+ return result
+
+ def get_delta_channel_history(
+ self, *, config: RunnableConfig, channels: Sequence[str]
+ ) -> Mapping[str, DeltaChannelHistory]:
+ """Override: walk the parent chain ONCE for all requested channels.
+
+ Each channel terminates independently at the nearest ancestor
+ whose stored blob is non-empty. Other channels keep walking until
+ they find their own terminator or hit the root.
+
+ Pre-delta plain-value blobs subsume their ancestor's pending
+ writes (the value already includes them); `_DeltaSnapshot` blobs
+ do not (snapshot is the value AT that ancestor, prior to its own
+ pending writes that produce the child).
+ """
+ if not channels:
+ return {}
+ # Imported lazily to avoid a hard checkpoint→serde-types coupling at
+ # module import; only this override needs the runtime check.
+ from langgraph.checkpoint.serde.types import _DeltaSnapshot
+
+ thread_id = config["configurable"]["thread_id"]
+ checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
+ checkpoint_id = config["configurable"].get("checkpoint_id", "")
+ ns_storage = self.storage.get(thread_id, {}).get(checkpoint_ns, {})
+
+ chain: list[str] = []
+ target_entry = ns_storage.get(checkpoint_id)
+ current: str | None = target_entry[2] if target_entry is not None else None
+ while current is not None:
+ entry = ns_storage.get(current)
+ if entry is None:
+ break
+ chain.append(current)
+ _, _, parent = entry
+ current = parent
+
+ collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
+ seed_by_ch: dict[str, Any] = {}
+ remaining: set[str] = set(channels)
+
+ for cp_id in chain:
+ if not remaining:
+ break
+ entry = ns_storage.get(cp_id)
+ ckpt = self.serde.loads_typed(entry[0]) if entry is not None else None
+
+ terminated_here: set[str] = set()
+ blob_value_by_ch: dict[str, Any] = {}
+ if ckpt is not None:
+ versions = ckpt.get("channel_versions", {})
+ for ch in remaining:
+ ver = versions.get(ch)
+ if ver is None:
+ continue
+ blob_entry = self.blobs.get((thread_id, checkpoint_ns, ch, ver))
+ if blob_entry is None or blob_entry[0] == "empty":
+ continue
+ blob_value_by_ch[ch] = self.serde.loads_typed(blob_entry)
+ terminated_here.add(ch)
+
+ step_writes = self.writes.get((thread_id, checkpoint_ns, cp_id), {})
+ for (_task_id, _idx), (tid, ch, serialized, _) in sorted(
+ step_writes.items(), reverse=True
+ ):
+ if ch not in remaining:
+ continue
+ blob_value = blob_value_by_ch.get(ch)
+ if blob_value is not None and not isinstance(
+ blob_value, _DeltaSnapshot
+ ):
+ continue
+ collected_by_ch[ch].append(
+ (tid, ch, self.serde.loads_typed(serialized))
+ )
+
+ for ch in terminated_here:
+ seed_by_ch[ch] = blob_value_by_ch[ch]
+ remaining.discard(ch)
+
+ result: dict[str, DeltaChannelHistory] = {}
+ for ch in channels:
+ entry_h: DeltaChannelHistory = {
+ "writes": list(reversed(collected_by_ch[ch]))
+ }
+ if ch in seed_by_ch:
+ entry_h["seed"] = seed_by_ch[ch]
+ result[ch] = entry_h
+ return result
+
+ async def aget_delta_channel_history(
+ self, *, config: RunnableConfig, channels: Sequence[str]
+ ) -> Mapping[str, DeltaChannelHistory]:
+ return self.get_delta_channel_history(config=config, channels=channels)
+
+ def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
+ """Get a checkpoint tuple from the in-memory storage.
+
+ This method retrieves a checkpoint tuple from the in-memory storage based on the
+ provided config. If the config contains a `checkpoint_id` key, the checkpoint with
+ the matching thread ID and timestamp is retrieved. Otherwise, the latest checkpoint
+ for the given thread ID is retrieved.
+
+ Args:
+ config: The config to use for retrieving the checkpoint.
+
+ Returns:
+ The retrieved checkpoint tuple, or None if no matching checkpoint was found.
+ """
+ thread_id: str = config["configurable"]["thread_id"]
+ checkpoint_ns: str = config["configurable"].get("checkpoint_ns", "")
+ if checkpoint_id := get_checkpoint_id(config):
+ if saved := self.storage[thread_id][checkpoint_ns].get(checkpoint_id):
+ checkpoint, metadata, parent_checkpoint_id = saved
+ writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values()
+ checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint)
+ return CheckpointTuple(
+ config=config,
+ checkpoint={
+ **checkpoint_,
+ "channel_values": self._load_blobs(
+ thread_id, checkpoint_ns, checkpoint_["channel_versions"]
+ ),
+ },
+ metadata=self.serde.loads_typed(metadata),
+ pending_writes=[
+ (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
+ ],
+ parent_config=(
+ {
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": parent_checkpoint_id,
+ }
+ }
+ if parent_checkpoint_id
+ else None
+ ),
+ )
+ else:
+ if checkpoints := self.storage[thread_id][checkpoint_ns]:
+ checkpoint_id = max(checkpoints.keys())
+ checkpoint, metadata, parent_checkpoint_id = checkpoints[checkpoint_id]
+ writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values()
+ checkpoint_ = self.serde.loads_typed(checkpoint)
+ return CheckpointTuple(
+ config={
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": checkpoint_id,
+ }
+ },
+ checkpoint={
+ **checkpoint_,
+ "channel_values": self._load_blobs(
+ thread_id, checkpoint_ns, checkpoint_["channel_versions"]
+ ),
+ },
+ metadata=self.serde.loads_typed(metadata),
+ pending_writes=[
+ (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
+ ],
+ parent_config=(
+ {
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": parent_checkpoint_id,
+ }
+ }
+ if parent_checkpoint_id
+ else None
+ ),
+ )
+
+ def list(
+ self,
+ config: RunnableConfig | None,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> Iterator[CheckpointTuple]:
+ """List checkpoints from the in-memory storage.
+
+ This method retrieves a list of checkpoint tuples from the in-memory storage based
+ on the provided criteria.
+
+ Args:
+ config: Base configuration for filtering checkpoints.
+ filter: Additional filtering criteria for metadata.
+ before: List checkpoints created before this configuration.
+ limit: Maximum number of checkpoints to return.
+
+ Yields:
+ An iterator of matching checkpoint tuples.
+ """
+ thread_ids = (config["configurable"]["thread_id"],) if config else self.storage
+ config_checkpoint_ns = (
+ config["configurable"].get("checkpoint_ns") if config else None
+ )
+ config_checkpoint_id = get_checkpoint_id(config) if config else None
+ for thread_id in thread_ids:
+ for checkpoint_ns in self.storage[thread_id].keys():
+ if (
+ config_checkpoint_ns is not None
+ and checkpoint_ns != config_checkpoint_ns
+ ):
+ continue
+
+ for checkpoint_id, (
+ checkpoint,
+ metadata_b,
+ parent_checkpoint_id,
+ ) in sorted(
+ self.storage[thread_id][checkpoint_ns].items(),
+ key=lambda x: x[0],
+ reverse=True,
+ ):
+ # filter by checkpoint ID from config
+ if config_checkpoint_id and checkpoint_id != config_checkpoint_id:
+ continue
+
+ # filter by checkpoint ID from `before` config
+ if (
+ before
+ and (before_checkpoint_id := get_checkpoint_id(before))
+ and checkpoint_id >= before_checkpoint_id
+ ):
+ continue
+
+ # filter by metadata
+ metadata = self.serde.loads_typed(metadata_b)
+ if filter and not all(
+ query_value == metadata.get(query_key)
+ for query_key, query_value in filter.items()
+ ):
+ continue
+
+ # limit search results
+ if limit is not None and limit <= 0:
+ break
+ elif limit is not None:
+ limit -= 1
+
+ writes = self.writes[
+ (thread_id, checkpoint_ns, checkpoint_id)
+ ].values()
+
+ checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint)
+
+ yield CheckpointTuple(
+ config={
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": checkpoint_id,
+ }
+ },
+ checkpoint={
+ **checkpoint_,
+ "channel_values": self._load_blobs(
+ thread_id,
+ checkpoint_ns,
+ checkpoint_["channel_versions"],
+ ),
+ },
+ metadata=metadata,
+ parent_config=(
+ {
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": parent_checkpoint_id,
+ }
+ }
+ if parent_checkpoint_id
+ else None
+ ),
+ pending_writes=[
+ (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
+ ],
+ )
+
+ def put(
+ self,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ """Save a checkpoint to the in-memory storage.
+
+ This method saves a checkpoint to the in-memory storage. The checkpoint is associated
+ with the provided config.
+
+ Args:
+ config: The config to associate with the checkpoint.
+ checkpoint: The checkpoint to save.
+ metadata: Additional metadata to save with the checkpoint.
+ new_versions: New versions as of this write
+
+ Returns:
+ RunnableConfig: The updated config containing the saved checkpoint's timestamp.
+ """
+ c = checkpoint.copy()
+ thread_id = config["configurable"]["thread_id"]
+ checkpoint_ns = config["configurable"]["checkpoint_ns"]
+ values: dict[str, Any] = c.pop("channel_values") # type: ignore[misc]
+ for k, v in new_versions.items():
+ self.blobs[(thread_id, checkpoint_ns, k, v)] = (
+ self.serde.dumps_typed(values[k]) if k in values else ("empty", b"")
+ )
+ self.storage[thread_id][checkpoint_ns].update(
+ {
+ checkpoint["id"]: (
+ self.serde.dumps_typed(c),
+ self.serde.dumps_typed(get_checkpoint_metadata(config, metadata)),
+ config["configurable"].get("checkpoint_id"), # parent
+ )
+ }
+ )
+ return {
+ "configurable": {
+ "thread_id": thread_id,
+ "checkpoint_ns": checkpoint_ns,
+ "checkpoint_id": checkpoint["id"],
+ }
+ }
+
+ def put_writes(
+ self,
+ config: RunnableConfig,
+ writes: Sequence[tuple[str, Any]],
+ task_id: str,
+ task_path: str = "",
+ ) -> None:
+ """Save a list of writes to the in-memory storage.
+
+ This method saves a list of writes to the in-memory storage. The writes are associated
+ with the provided config.
+
+ Args:
+ config: The config to associate with the writes.
+ writes: The writes to save.
+ task_id: Identifier for the task creating the writes.
+ task_path: Path of the task creating the writes.
+
+ Returns:
+ RunnableConfig: The updated config containing the saved writes' timestamp.
+ """
+ thread_id = config["configurable"]["thread_id"]
+ checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
+ checkpoint_id = config["configurable"]["checkpoint_id"]
+ outer_key = (thread_id, checkpoint_ns, checkpoint_id)
+ outer_writes_ = self.writes.get(outer_key)
+ for idx, (c, v) in enumerate(writes):
+ inner_key = (task_id, WRITES_IDX_MAP.get(c, idx))
+ if inner_key[1] >= 0 and outer_writes_ and inner_key in outer_writes_:
+ continue
+
+ self.writes[outer_key][inner_key] = (
+ task_id,
+ c,
+ self.serde.dumps_typed(v),
+ task_path,
+ )
+
+ def delete_thread(self, thread_id: str) -> None:
+ """Delete all checkpoints and writes associated with a thread ID.
+
+ Args:
+ thread_id: The thread ID to delete.
+
+ Returns:
+ None
+ """
+ if thread_id in self.storage:
+ del self.storage[thread_id]
+ for k in list(self.writes.keys()):
+ if k[0] == thread_id:
+ del self.writes[k]
+ for k in list(self.blobs.keys()):
+ if k[0] == thread_id:
+ del self.blobs[k]
+
+ async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
+ """Asynchronous version of `get_tuple`.
+
+ This method is an asynchronous wrapper around `get_tuple` that runs the synchronous
+ method in a separate thread using asyncio.
+
+ Args:
+ config: The config to use for retrieving the checkpoint.
+
+ Returns:
+ The retrieved checkpoint tuple, or None if no matching checkpoint was found.
+ """
+ return self.get_tuple(config)
+
+ async def alist(
+ self,
+ config: RunnableConfig | None,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[CheckpointTuple]:
+ """Asynchronous version of `list`.
+
+ This method is an asynchronous wrapper around `list` that runs the synchronous
+ method in a separate thread using asyncio.
+
+ Args:
+ config: The config to use for listing the checkpoints.
+
+ Yields:
+ An asynchronous iterator of checkpoint tuples.
+ """
+ for item in self.list(config, filter=filter, before=before, limit=limit):
+ yield item
+
+ async def aput(
+ self,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ """Asynchronous version of `put`.
+
+ Args:
+ config: The config to associate with the checkpoint.
+ checkpoint: The checkpoint to save.
+ metadata: Additional metadata to save with the checkpoint.
+ new_versions: New versions as of this write
+
+ Returns:
+ RunnableConfig: The updated config containing the saved checkpoint's timestamp.
+ """
+ return self.put(config, checkpoint, metadata, new_versions)
+
+ async def aput_writes(
+ self,
+ config: RunnableConfig,
+ writes: Sequence[tuple[str, Any]],
+ task_id: str,
+ task_path: str = "",
+ ) -> None:
+ """Asynchronous version of `put_writes`.
+
+ This method is an asynchronous wrapper around `put_writes` that runs the synchronous
+ method in a separate thread using asyncio.
+
+ Args:
+ config: The config to associate with the writes.
+ writes: The writes to save, each as a (channel, value) pair.
+ task_id: Identifier for the task creating the writes.
+ task_path: Path of the task creating the writes.
+
+ Returns:
+ None
+ """
+ return self.put_writes(config, writes, task_id, task_path)
+
+ async def adelete_thread(self, thread_id: str) -> None:
+ """Delete all checkpoints and writes associated with a thread ID.
+
+ Args:
+ thread_id: The thread ID to delete.
+
+ Returns:
+ None
+ """
+ return self.delete_thread(thread_id)
+
+ def get_next_version(self, current: str | None, channel: None) -> str:
+ if current is None:
+ current_v = 0
+ elif isinstance(current, int):
+ current_v = current
+ else:
+ current_v = int(current.split(".")[0])
+ next_v = current_v + 1
+ next_h = random.random()
+ return f"{next_v:032}.{next_h:016}"
+
+
+MemorySaver = InMemorySaver # Kept for backwards compatibility
+
+
+class PersistentDict(defaultdict):
+ """Persistent dictionary with an API compatible with shelve and anydbm.
+
+ The dict is kept in memory, so the dictionary operations run as fast as
+ a regular dictionary.
+
+ Write to disk is delayed until close or sync (similar to gdbm's fast mode).
+
+ Input file format is automatically discovered.
+ Output file format is selectable between pickle, json, and csv.
+ All three serialization formats are backed by fast C implementations.
+
+ Adapted from https://code.activestate.com/recipes/576642-persistent-dict-with-multiple-standard-file-format/
+
+ """
+
+ def __init__(self, *args: Any, filename: str, **kwds: Any) -> None:
+ self.flag = "c" # r=readonly, c=create, or n=new
+ self.mode = None # None or an octal triple like 0644
+ self.format = "pickle" # 'csv', 'json', or 'pickle'
+ self.filename = filename
+ super().__init__(*args, **kwds)
+
+ def sync(self) -> None:
+ "Write dict to disk"
+ if self.flag == "r":
+ return
+ tempname = self.filename + ".tmp"
+ fileobj = open(tempname, "wb" if self.format == "pickle" else "w")
+ try:
+ self.dump(fileobj)
+ except Exception:
+ os.remove(tempname)
+ raise
+ finally:
+ fileobj.close()
+ shutil.move(tempname, self.filename) # atomic commit
+ if self.mode is not None:
+ os.chmod(self.filename, self.mode)
+
+ def close(self) -> None:
+ self.sync()
+ self.clear()
+
+ def __enter__(self) -> PersistentDict:
+ return self
+
+ def __exit__(self, *exc_info: Any) -> None:
+ self.close()
+
+ def dump(self, fileobj: Any) -> None:
+ if self.format == "pickle":
+ pickle.dump(dict(self), fileobj, 2)
+ else:
+ raise NotImplementedError("Unknown format: " + repr(self.format))
+
+ def load(self) -> None:
+ # try formats from most restrictive to least restrictive
+ if self.flag == "n":
+ return
+ with open(self.filename, "rb" if self.format == "pickle" else "r") as fileobj:
+ for loader in (pickle.load,):
+ fileobj.seek(0)
+ try:
+ return self.update(loader(fileobj))
+ except EOFError:
+ return
+ except Exception:
+ logger.error(f"Failed to load file: {fileobj.name}")
+ raise
+ raise ValueError("File not in a supported format")
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f215c9f67896071a3d014206507a05131e9c7f19
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/py.typed b/python/user_packages/Python313/site-packages/langgraph/checkpoint/memory/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__init__.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..790030d8aba6958707c5919935b5e09f41391f17
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d69a3cb14a9d657113387c667b5ad06824b279ea
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1f66711ef8ab6c4324aa8afb158975d49f3c65f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b210e88140fb27149f29ab0e3c9636497bc7e4b
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8eb0b521e583c62dfb189ca40b64af6e72304ac
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..191978b148e6a939bf334ee6aa8af569a957983c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57ff37eaf44099069f4a38fc2cd44c86ddea0380
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/_msgpack.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/_msgpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a5188f1fd9da8e80b8d090454883885ca3aa466
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/_msgpack.py
@@ -0,0 +1,97 @@
+"""Msgpack deserialization safety controls.
+
+Set ``LANGGRAPH_STRICT_MSGPACK=true`` to restrict checkpoint deserialization
+to the types listed in ``SAFE_MSGPACK_TYPES``. Without this, any Python
+callable stored in checkpoint data will be imported and executed on load.
+"""
+
+import os
+from collections.abc import Iterable
+from typing import cast
+
+STRICT_MSGPACK_ENABLED = os.getenv("LANGGRAPH_STRICT_MSGPACK", "false").lower() in (
+ "1",
+ "true",
+ "yes",
+)
+
+
+_SENTINEL = cast(None, object())
+
+SAFE_MSGPACK_TYPES: frozenset[tuple[str, ...]] = frozenset(
+ {
+ # datetime types
+ ("datetime", "datetime"),
+ ("datetime", "date"),
+ ("datetime", "time"),
+ ("datetime", "timedelta"),
+ ("datetime", "timezone"),
+ # uuid
+ ("uuid", "UUID"),
+ # numeric
+ ("decimal", "Decimal"),
+ # collections
+ ("builtins", "set"),
+ ("builtins", "frozenset"),
+ ("collections", "deque"),
+ # ip addresses
+ ("ipaddress", "IPv4Address"),
+ ("ipaddress", "IPv4Interface"),
+ ("ipaddress", "IPv4Network"),
+ ("ipaddress", "IPv6Address"),
+ ("ipaddress", "IPv6Interface"),
+ ("ipaddress", "IPv6Network"),
+ # pathlib
+ ("pathlib", "Path"),
+ ("pathlib", "PosixPath"),
+ ("pathlib", "WindowsPath"),
+ # pathlib in Python 3.13+
+ ("pathlib._local", "Path"),
+ ("pathlib._local", "PosixPath"),
+ ("pathlib._local", "WindowsPath"),
+ # zoneinfo
+ ("zoneinfo", "ZoneInfo"),
+ # regex
+ ("re", "compile"),
+ # langchain-core messages (safe container types used by graph state)
+ ("langchain_core.messages.base", "BaseMessage"),
+ ("langchain_core.messages.base", "BaseMessageChunk"),
+ ("langchain_core.messages.human", "HumanMessage"),
+ ("langchain_core.messages.human", "HumanMessageChunk"),
+ ("langchain_core.messages.ai", "AIMessage"),
+ ("langchain_core.messages.ai", "AIMessageChunk"),
+ ("langchain_core.messages.system", "SystemMessage"),
+ ("langchain_core.messages.system", "SystemMessageChunk"),
+ ("langchain_core.messages.chat", "ChatMessage"),
+ ("langchain_core.messages.chat", "ChatMessageChunk"),
+ ("langchain_core.messages.tool", "ToolMessage"),
+ ("langchain_core.messages.tool", "ToolMessageChunk"),
+ ("langchain_core.messages.function", "FunctionMessage"),
+ ("langchain_core.messages.function", "FunctionMessageChunk"),
+ ("langchain_core.messages.modifier", "RemoveMessage"),
+ # langchain-core document model
+ ("langchain_core.documents.base", "Document"),
+ # langgraph
+ ("langgraph.types", "Send"),
+ ("langgraph.types", "TimeoutPolicy"),
+ ("langgraph.types", "Interrupt"),
+ ("langgraph.types", "Command"),
+ ("langgraph.types", "StateSnapshot"),
+ ("langgraph.types", "PregelTask"),
+ ("langgraph.types", "Overwrite"),
+ ("langgraph.store.base", "Item"),
+ ("langgraph.store.base", "GetOp"),
+ }
+)
+
+# Allowed (module, name, method) triples for EXT_METHOD_SINGLE_ARG.
+# Only these specific method invocations are permitted during deserialization.
+# This is separate from SAFE_MSGPACK_TYPES which only governs construction.
+SAFE_MSGPACK_METHODS: frozenset[tuple[str, str, str]] = frozenset(
+ {
+ ("datetime", "datetime", "fromisoformat"),
+ }
+)
+
+
+AllowedMsgpackModules = Iterable[tuple[str, ...] | type]
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/base.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..186e162fa76eb9cbabca88419673996a07453b28
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/base.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from typing import Any, Protocol, runtime_checkable
+
+
+class UntypedSerializerProtocol(Protocol):
+ """Protocol for serialization and deserialization of objects."""
+
+ def dumps(self, obj: Any) -> bytes: ...
+
+ def loads(self, data: bytes) -> Any: ...
+
+
+@runtime_checkable
+class SerializerProtocol(Protocol):
+ """Protocol for serialization and deserialization of objects.
+
+ - `dumps_typed`: Serialize an object to a tuple `(type, bytes)`.
+ - `loads_typed`: Deserialize an object from a tuple `(type, bytes)`.
+
+ Valid implementations include the `pickle`, `json` and `orjson` modules.
+ """
+
+ def dumps_typed(self, obj: Any) -> tuple[str, bytes]: ...
+
+ def loads_typed(self, data: tuple[str, bytes]) -> Any: ...
+
+
+class SerializerCompat(SerializerProtocol):
+ def __init__(self, serde: UntypedSerializerProtocol) -> None:
+ self.serde = serde
+
+ def dumps_typed(self, obj: Any) -> tuple[str, bytes]:
+ return type(obj).__name__, self.serde.dumps(obj)
+
+ def loads_typed(self, data: tuple[str, bytes]) -> Any:
+ return self.serde.loads(data[1])
+
+
+def maybe_add_typed_methods(
+ serde: SerializerProtocol | UntypedSerializerProtocol,
+) -> SerializerProtocol:
+ """Wrap serde old serde implementations in a class with loads_typed and dumps_typed for backwards compatibility."""
+
+ if not isinstance(serde, SerializerProtocol):
+ return SerializerCompat(serde)
+
+ return serde
+
+
+class CipherProtocol(Protocol):
+ """Protocol for encryption and decryption of data.
+
+ - `encrypt`: Encrypt plaintext.
+ - `decrypt`: Decrypt ciphertext.
+ """
+
+ def encrypt(self, plaintext: bytes) -> tuple[str, bytes]:
+ """Encrypt plaintext. Returns a tuple `(cipher name, ciphertext)`."""
+ ...
+
+ def decrypt(self, ciphername: str, ciphertext: bytes) -> bytes:
+ """Decrypt ciphertext. Returns the plaintext."""
+ ...
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/encrypted.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/encrypted.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f517e40551974671830a32151b1ee4f830082aa
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/encrypted.py
@@ -0,0 +1,80 @@
+import os
+from typing import Any
+
+from langgraph.checkpoint.serde.base import CipherProtocol, SerializerProtocol
+from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
+
+
+class EncryptedSerializer(SerializerProtocol):
+ """Serializer that encrypts and decrypts data using an encryption protocol."""
+
+ def __init__(
+ self, cipher: CipherProtocol, serde: SerializerProtocol = JsonPlusSerializer()
+ ) -> None:
+ self.cipher = cipher
+ self.serde = serde
+
+ def dumps_typed(self, obj: Any) -> tuple[str, bytes]:
+ """Serialize an object to a tuple `(type, bytes)` and encrypt the bytes."""
+ # serialize data
+ typ, data = self.serde.dumps_typed(obj)
+ # encrypt data
+ ciphername, ciphertext = self.cipher.encrypt(data)
+ # add cipher name to type
+ return f"{typ}+{ciphername}", ciphertext
+
+ def loads_typed(self, data: tuple[str, bytes]) -> Any:
+ enc_cipher, ciphertext = data
+ # unencrypted data
+ if "+" not in enc_cipher:
+ return self.serde.loads_typed(data)
+ # extract cipher name
+ typ, ciphername = enc_cipher.split("+", 1)
+ # decrypt data
+ decrypted_data = self.cipher.decrypt(ciphername, ciphertext)
+ # deserialize data
+ return self.serde.loads_typed((typ, decrypted_data))
+
+ @classmethod
+ def from_pycryptodome_aes(
+ cls, serde: SerializerProtocol = JsonPlusSerializer(), **kwargs: Any
+ ) -> "EncryptedSerializer":
+ """Create an `EncryptedSerializer` using AES encryption."""
+ try:
+ from Crypto.Cipher import AES
+ except ImportError:
+ raise ImportError(
+ "Pycryptodome is not installed. Please install it with `pip install pycryptodome`."
+ ) from None
+
+ # check if AES key is provided
+ if "key" in kwargs:
+ key: bytes = kwargs.pop("key")
+ else:
+ key_str = os.getenv("LANGGRAPH_AES_KEY")
+ if key_str is None:
+ raise ValueError("LANGGRAPH_AES_KEY environment variable is not set.")
+ key = key_str.encode()
+ if len(key) not in (16, 24, 32):
+ raise ValueError("LANGGRAPH_AES_KEY must be 16, 24, or 32 bytes long.")
+
+ # set default mode to EAX if not provided
+ if kwargs.get("mode") is None:
+ kwargs["mode"] = AES.MODE_EAX
+
+ class PycryptodomeAesCipher(CipherProtocol):
+ def encrypt(self, plaintext: bytes) -> tuple[str, bytes]:
+ cipher = AES.new(key, **kwargs)
+ ciphertext, tag = cipher.encrypt_and_digest(plaintext)
+ return "aes", cipher.nonce + tag + ciphertext
+
+ def decrypt(self, ciphername: str, ciphertext: bytes) -> bytes:
+ assert ciphername == "aes", f"Unsupported cipher: {ciphername}"
+ nonce = ciphertext[:16]
+ tag = ciphertext[16:32]
+ actual_ciphertext = ciphertext[32:]
+
+ cipher = AES.new(key, **kwargs, nonce=nonce)
+ return cipher.decrypt_and_verify(actual_ciphertext, tag)
+
+ return cls(PycryptodomeAesCipher(), serde)
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/event_hooks.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/event_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ea0a5b496265f1c2fa4b1b08fd704395078a1ff
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/event_hooks.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from threading import Lock
+from typing import TypedDict
+
+from typing_extensions import NotRequired
+
+logger = logging.getLogger(__name__)
+
+
+class SerdeEvent(TypedDict):
+ kind: str
+ module: str
+ name: str
+ method: NotRequired[str]
+
+
+SerdeEventListener = Callable[[SerdeEvent], None]
+
+_listeners: list[SerdeEventListener] = []
+_listeners_lock = Lock()
+
+
+def register_serde_event_listener(listener: SerdeEventListener) -> Callable[[], None]:
+ """Register a listener for serde allowlist events."""
+ with _listeners_lock:
+ _listeners.append(listener)
+
+ def unregister() -> None:
+ with _listeners_lock:
+ try:
+ _listeners.remove(listener)
+ except ValueError:
+ pass
+
+ return unregister
+
+
+def emit_serde_event(event: SerdeEvent) -> None:
+ """Emit a serde event to all listeners.
+
+ Listener failures are isolated and logged.
+ """
+ with _listeners_lock:
+ listeners = tuple(_listeners)
+ for listener in listeners:
+ try:
+ listener(event)
+ except Exception:
+ logger.warning("Serde listener failed", exc_info=True)
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/jsonplus.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/jsonplus.py
new file mode 100644
index 0000000000000000000000000000000000000000..38ed3a0dc38dbc4d64258d2840fc9974b4dfcdf3
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/jsonplus.py
@@ -0,0 +1,903 @@
+from __future__ import annotations
+
+import copy
+import dataclasses
+import decimal
+import importlib
+import json
+import logging
+import pathlib
+import pickle
+import re
+import sys
+from collections import deque
+from collections.abc import Callable, Iterable, Sequence
+from datetime import date, datetime, time, timedelta, timezone
+from enum import Enum
+from inspect import isclass
+from ipaddress import (
+ IPv4Address,
+ IPv4Interface,
+ IPv4Network,
+ IPv6Address,
+ IPv6Interface,
+ IPv6Network,
+)
+from typing import TYPE_CHECKING, Any, Literal, cast
+from uuid import UUID
+from zoneinfo import ZoneInfo
+
+import ormsgpack
+from langchain_core.load.load import Reviver
+
+from langgraph.checkpoint.serde import _msgpack as _lg_msgpack
+from langgraph.checkpoint.serde.base import SerializerProtocol
+from langgraph.checkpoint.serde.event_hooks import emit_serde_event
+from langgraph.checkpoint.serde.types import (
+ SendProtocol,
+ _DeltaSnapshot,
+)
+from langgraph.store.base import Item
+
+if TYPE_CHECKING:
+ from langgraph.checkpoint.serde._msgpack import (
+ AllowedMsgpackModules,
+ )
+
+LC_REVIVER = Reviver(allowed_objects="core")
+EMPTY_BYTES = b""
+logger = logging.getLogger(__name__)
+
+# Dedup log warnings across process lifetime; cap bounds state if types are
+# dynamically generated (also acts as a circuit breaker on warning volume).
+# Dedup is best-effort: racing threads may each emit once for the same key,
+# and warnings are silently dropped once _MAX_WARNED_TYPES is reached.
+_MAX_WARNED_TYPES = 1000
+_warned_unregistered_types: set[tuple[str, str]] = set()
+_warned_blocked_types: set[tuple[str, str]] = set()
+
+
+def _is_safe_json_type(id_list: list[str]) -> bool:
+ """Return True if an lc=2 id refers to a type in SAFE_MSGPACK_TYPES.
+
+ Safe types bypass the ``allowed_json_modules`` gate so that old "json" format
+ checkpoints (written before the msgpack migration) can be resumed without
+ requiring users to configure an explicit allowlist.
+ """
+ if len(id_list) < 2:
+ return False
+ module_name = ".".join(id_list[:-1])
+ return (module_name, id_list[-1]) in _lg_msgpack.SAFE_MSGPACK_TYPES
+
+
+def _warn_once(
+ seen: set[tuple[str, str]], key: tuple[str, str], msg: str, *args: object
+) -> None:
+ if key in seen or len(seen) >= _MAX_WARNED_TYPES:
+ return
+ seen.add(key)
+ logger.warning(msg, *args)
+
+
+class JsonPlusSerializer(SerializerProtocol):
+ """Serializer that uses ormsgpack, with optional fallbacks.
+
+ !!! warning
+
+ Security note: This serializer is intended for use within the `BaseCheckpointSaver`
+ class and called within the Pregel loop. It should not be used on untrusted
+ python objects. If an attacker can write directly to your checkpoint database,
+ they may be able to trigger code execution when data is deserialized.
+
+ Set the environment variable ``LANGGRAPH_STRICT_MSGPACK=true`` to restrict
+ deserialization to a built-in allowlist of safe types. You can also pass
+ an explicit ``allowed_msgpack_modules`` to the constructor.
+ """
+
+ def __init__(
+ self,
+ *,
+ pickle_fallback: bool = False,
+ allowed_json_modules: Iterable[tuple[str, ...]] | Literal[True] | None = None,
+ allowed_msgpack_modules: (
+ AllowedMsgpackModules | Literal[True] | None
+ ) = _lg_msgpack._SENTINEL,
+ __unpack_ext_hook__: Callable[[int, bytes], Any] | None = None,
+ ) -> None:
+ if allowed_msgpack_modules is _lg_msgpack._SENTINEL:
+ if _lg_msgpack.STRICT_MSGPACK_ENABLED:
+ # Strict: only SAFE_MSGPACK_TYPES are allowed.
+ allowed_msgpack_modules = None
+ else:
+ # Permissive (default): all types allowed with a warning.
+ # Set LANGGRAPH_STRICT_MSGPACK=true to lock this down.
+ allowed_msgpack_modules = True
+ self.pickle_fallback = pickle_fallback
+ self._allowed_json_modules: set[tuple[str, ...]] | Literal[True] | None = (
+ _normalize_allowlist(allowed_json_modules)
+ )
+ self._allowed_msgpack_modules = _normalize_allowlist(allowed_msgpack_modules)
+
+ self._custom_unpack_ext_hook = __unpack_ext_hook__ is not None
+ self._unpack_ext_hook = (
+ __unpack_ext_hook__
+ if __unpack_ext_hook__ is not None
+ else _create_msgpack_ext_hook(self._allowed_msgpack_modules)
+ )
+
+ def with_msgpack_allowlist(
+ self, extra_allowlist: Iterable[tuple[str, ...] | type]
+ ) -> JsonPlusSerializer:
+ """Return a new serializer with a merged msgpack allowlist."""
+ base_allowlist = self._allowed_msgpack_modules
+ if base_allowlist is True or base_allowlist is False:
+ return self
+ elif base_allowlist:
+ base_allowlist = set(base_allowlist)
+ else:
+ base_allowlist = set()
+ extra = _normalize_module_keys(tuple(extra_allowlist))
+ merged = base_allowlist | extra
+ if merged == base_allowlist:
+ return self
+ allowed_msgpack_modules: AllowedMsgpackModules | Literal[True] | None
+ if merged:
+ allowed_msgpack_modules = tuple(merged)
+ elif isinstance(self._allowed_msgpack_modules, set):
+ allowed_msgpack_modules = tuple(self._allowed_msgpack_modules)
+ else:
+ allowed_msgpack_modules = self._allowed_msgpack_modules
+
+ clone = copy.copy(self)
+ clone._allowed_json_modules = _normalize_allowlist(self._allowed_json_modules)
+ clone._allowed_msgpack_modules = _normalize_allowlist(allowed_msgpack_modules)
+ if not clone._custom_unpack_ext_hook:
+ clone._unpack_ext_hook = _create_msgpack_ext_hook(
+ clone._allowed_msgpack_modules
+ )
+ return clone
+
+ def _encode_constructor_args(
+ self,
+ constructor: Callable | type[Any],
+ *,
+ method: None | str | Sequence[None | str] = None,
+ args: Sequence[Any] | None = None,
+ kwargs: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ out = {
+ "lc": 2,
+ "type": "constructor",
+ "id": (*constructor.__module__.split("."), constructor.__name__),
+ }
+ if method is not None:
+ out["method"] = method
+ if args is not None:
+ out["args"] = args
+ if kwargs is not None:
+ out["kwargs"] = kwargs
+ return out
+
+ def _reviver(self, value: dict[str, Any]) -> Any:
+ if (
+ value.get("lc", None) == 2
+ and value.get("type", None) == "constructor"
+ and value.get("id", None) is not None
+ ):
+ id_list = value["id"]
+ is_safe = _is_safe_json_type(id_list)
+ if self._allowed_json_modules or is_safe:
+ try:
+ return self._revive_lc2(value)
+ except InvalidModuleError as e:
+ if not is_safe:
+ logger.warning(
+ "Object %s is not in the deserialization allowlist.\n%s",
+ value["id"],
+ e.message,
+ )
+
+ return LC_REVIVER(value)
+
+ def _revive_lc2(self, value: dict[str, Any]) -> Any:
+ self._check_allowed_json_modules(value)
+
+ [*module, name] = value["id"]
+ try:
+ mod = importlib.import_module(".".join(module))
+ cls = getattr(mod, name)
+ method = value.get("method")
+ if isinstance(method, str):
+ methods = [getattr(cls, method)]
+ elif isinstance(method, list):
+ methods = [cls if m is None else getattr(cls, m) for m in method]
+ else:
+ methods = [cls]
+ args = value.get("args")
+ kwargs = value.get("kwargs")
+ for method in methods:
+ try:
+ if isclass(method) and issubclass(method, BaseException):
+ return None
+ if args and kwargs:
+ return method(*args, **kwargs)
+ elif args:
+ return method(*args)
+ elif kwargs:
+ return method(**kwargs)
+ else:
+ return method()
+ except Exception:
+ continue
+ except Exception:
+ return None
+
+ def _check_allowed_json_modules(self, value: dict[str, Any]) -> None:
+ needed = tuple(value["id"])
+ method = value.get("method")
+ if isinstance(method, list):
+ method_display = ",".join(m or "" for m in method)
+ elif isinstance(method, str):
+ method_display = method
+ else:
+ method_display = ""
+
+ dotted = ".".join(needed)
+ # Safe types (the same set already allowed for msgpack deserialization) are
+ # permitted without an explicit allowlist — they are known-safe LangGraph and
+ # LangChain types. This restores backwards-compat for old "json" checkpoints
+ # that pre-date the msgpack migration without reopening the broader security gate.
+ if _is_safe_json_type(list(needed)):
+ return
+
+ if not self._allowed_json_modules:
+ raise InvalidModuleError(
+ f"Refused to deserialize JSON constructor: {dotted} (method: {method_display}). "
+ "No allowed_json_modules configured.\n\n"
+ "Unblock with ONE of:\n"
+ f" • JsonPlusSerializer(allowed_json_modules=[{needed!r}, ...])\n"
+ " • (DANGEROUS) JsonPlusSerializer(allowed_json_modules=True)\n\n"
+ "Note: Prefix allowlists are intentionally unsupported; prefer exact symbols "
+ "or plain-JSON representations revived without import-time side effects."
+ )
+
+ if self._allowed_json_modules is True:
+ return
+ if needed in self._allowed_json_modules:
+ return
+
+ raise InvalidModuleError(
+ f"Refused to deserialize JSON constructor: {dotted} (method: {method_display}). "
+ "Symbol is not in the deserialization allowlist.\n\n"
+ "Add exactly this symbol to unblock:\n"
+ f" JsonPlusSerializer(allowed_json_modules=[{needed!r}, ...])\n"
+ "Or, as a last resort (DANGEROUS):\n"
+ " JsonPlusSerializer(allowed_json_modules=True)"
+ )
+
+ def dumps_typed(self, obj: Any) -> tuple[str, bytes]:
+ if obj is None:
+ return "null", EMPTY_BYTES
+ elif isinstance(obj, bytes):
+ return "bytes", obj
+ elif isinstance(obj, bytearray):
+ return "bytearray", obj
+ else:
+ try:
+ return "msgpack", _msgpack_enc(obj)
+ except ormsgpack.MsgpackEncodeError as exc:
+ if self.pickle_fallback:
+ return "pickle", pickle.dumps(obj)
+ raise exc
+
+ def loads_typed(self, data: tuple[str, bytes]) -> Any:
+ type_, data_ = data
+ if type_ == "null":
+ return None
+ elif type_ == "bytes":
+ return data_
+ elif type_ == "bytearray":
+ return bytearray(data_)
+ elif type_ == "json":
+ return json.loads(data_, object_hook=self._reviver)
+ elif type_ == "msgpack":
+ return ormsgpack.unpackb(
+ data_, ext_hook=self._unpack_ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ elif self.pickle_fallback and type_ == "pickle":
+ return pickle.loads(data_)
+ else:
+ raise NotImplementedError(f"Unknown serialization type: {type_}")
+
+
+# --- msgpack ---
+
+EXT_CONSTRUCTOR_SINGLE_ARG = 0
+EXT_CONSTRUCTOR_POS_ARGS = 1
+EXT_CONSTRUCTOR_KW_ARGS = 2
+EXT_METHOD_SINGLE_ARG = 3
+EXT_PYDANTIC_V1 = 4
+EXT_PYDANTIC_V2 = 5
+EXT_NUMPY_ARRAY = 6
+EXT_DELTA_SNAPSHOT = 7
+
+
+def _msgpack_default(obj: Any) -> str | ormsgpack.Ext:
+ if isinstance(obj, _DeltaSnapshot):
+ return ormsgpack.Ext(EXT_DELTA_SNAPSHOT, _msgpack_enc(obj.value))
+ elif hasattr(obj, "model_dump") and callable(obj.model_dump): # pydantic v2
+ return ormsgpack.Ext(
+ EXT_PYDANTIC_V2,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj.model_dump(),
+ "model_validate_json",
+ ),
+ ),
+ )
+ elif hasattr(obj, "get_secret_value") and callable(obj.get_secret_value):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj.get_secret_value(),
+ ),
+ ),
+ )
+ elif hasattr(obj, "dict") and callable(obj.dict): # pydantic v1
+ return ormsgpack.Ext(
+ EXT_PYDANTIC_V1,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj.dict(),
+ ),
+ ),
+ )
+ elif hasattr(obj, "_asdict") and callable(obj._asdict): # namedtuple
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_KW_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj._asdict(),
+ ),
+ ),
+ )
+ elif isinstance(obj, pathlib.Path):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, obj.parts),
+ ),
+ )
+ elif isinstance(obj, re.Pattern):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ ("re", "compile", (obj.pattern, obj.flags)),
+ ),
+ )
+ elif isinstance(obj, UUID):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, obj.hex),
+ ),
+ )
+ elif isinstance(obj, decimal.Decimal):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, str(obj)),
+ ),
+ )
+ elif isinstance(obj, (set, frozenset, deque)):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, tuple(obj)),
+ ),
+ )
+ elif isinstance(obj, (IPv4Address, IPv4Interface, IPv4Network)):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, str(obj)),
+ ),
+ )
+ elif isinstance(obj, (IPv6Address, IPv6Interface, IPv6Network)):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, str(obj)),
+ ),
+ )
+ elif isinstance(obj, datetime):
+ return ormsgpack.Ext(
+ EXT_METHOD_SINGLE_ARG,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj.isoformat(),
+ "fromisoformat",
+ ),
+ ),
+ )
+ elif isinstance(obj, timedelta):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ (obj.days, obj.seconds, obj.microseconds),
+ ),
+ ),
+ )
+ elif isinstance(obj, date):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ (obj.year, obj.month, obj.day),
+ ),
+ ),
+ )
+ elif isinstance(obj, time):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_KW_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ {
+ "hour": obj.hour,
+ "minute": obj.minute,
+ "second": obj.second,
+ "microsecond": obj.microsecond,
+ "tzinfo": obj.tzinfo,
+ "fold": obj.fold,
+ },
+ ),
+ ),
+ )
+ elif isinstance(obj, timezone):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ obj.__getinitargs__(), # type: ignore[attr-defined]
+ ),
+ ),
+ )
+ elif isinstance(obj, ZoneInfo):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, obj.key),
+ ),
+ )
+ elif isinstance(obj, Enum):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_SINGLE_ARG,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, obj.value),
+ ),
+ )
+ elif isinstance(obj, SendProtocol):
+ args: tuple[Any, ...] = (obj.node, obj.arg)
+ if (timeout := getattr(obj, "timeout", None)) is not None:
+ args = (obj.node, obj.arg, timeout)
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_POS_ARGS,
+ _msgpack_enc(
+ (obj.__class__.__module__, obj.__class__.__name__, args),
+ ),
+ )
+ elif dataclasses.is_dataclass(obj):
+ # doesn't use dataclasses.asdict to avoid deepcopy and recursion
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_KW_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ {
+ field.name: getattr(obj, field.name)
+ for field in dataclasses.fields(obj)
+ },
+ ),
+ ),
+ )
+ elif isinstance(obj, Item):
+ return ormsgpack.Ext(
+ EXT_CONSTRUCTOR_KW_ARGS,
+ _msgpack_enc(
+ (
+ obj.__class__.__module__,
+ obj.__class__.__name__,
+ {k: getattr(obj, k) for k in obj.__slots__},
+ ),
+ ),
+ )
+ elif (np_mod := sys.modules.get("numpy")) is not None and isinstance(
+ obj, np_mod.ndarray
+ ):
+ order = "F" if obj.flags.f_contiguous and not obj.flags.c_contiguous else "C"
+ if obj.flags.c_contiguous:
+ mv = memoryview(obj)
+ try:
+ meta = (obj.dtype.str, obj.shape, order, mv)
+ return ormsgpack.Ext(EXT_NUMPY_ARRAY, _msgpack_enc(meta))
+ finally:
+ mv.release()
+ else:
+ buf = obj.tobytes(order="A")
+ meta = (obj.dtype.str, obj.shape, order, buf)
+ return ormsgpack.Ext(EXT_NUMPY_ARRAY, _msgpack_enc(meta))
+
+ elif isinstance(obj, BaseException):
+ return repr(obj)
+ else:
+ raise TypeError(f"Object of type {obj.__class__.__name__} is not serializable")
+
+
+def _send_from_args(args: Sequence[Any]) -> Any:
+ # ya we have a cyclic import here ¯\_(ツ)_/¯
+ from langgraph.types import Send # type: ignore
+
+ if len(args) == 2:
+ return Send(*args)
+ return Send(args[0], args[1], timeout=args[2])
+
+
+def _create_msgpack_ext_hook(
+ allowed_modules: set[tuple[str, ...]] | Literal[True] | None,
+) -> Callable[[int, bytes], Any]:
+ """Create msgpack ext hook with allowlist.
+
+ Args:
+ allowed_modules: Set of (module, name) tuples that are allowed to be
+ deserialized, or True to allow all with warnings for unregistered types, or None to only allow safe types.
+
+ Returns:
+ An ext_hook function for use with ormsgpack.unpackb.
+ """
+
+ def _check_allowed(module: str, name: str) -> bool:
+ """Check if type is allowed. Returns True if allowed, False if blocked."""
+ key = (module, name)
+
+ if key in _lg_msgpack.SAFE_MSGPACK_TYPES:
+ return True
+
+ if allowed_modules is True:
+ # default is to warn but allow unregistered types
+ emit_serde_event(
+ {
+ "kind": "msgpack_unregistered_allowed",
+ "module": module,
+ "name": name,
+ }
+ )
+ _warn_once(
+ _warned_unregistered_types,
+ key,
+ "Deserializing unregistered type %s.%s from checkpoint. "
+ "This will be blocked in a future version. "
+ "Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add "
+ "to allowed_msgpack_modules to allow explicitly: [(%r, %r)]",
+ module,
+ name,
+ module,
+ name,
+ )
+ return True
+ if allowed_modules is not None:
+ if key in allowed_modules:
+ return True
+ # strict mode blocks unregistered types
+ emit_serde_event(
+ {
+ "kind": "msgpack_blocked",
+ "module": module,
+ "name": name,
+ }
+ )
+ _warn_once(
+ _warned_blocked_types,
+ key,
+ "Blocked deserialization of %s.%s - not in allowed_msgpack_modules. "
+ "Add to allowed_msgpack_modules to allow: [(%r, %r)]",
+ module,
+ name,
+ module,
+ name,
+ )
+ return False
+
+ def _check_allowed_method(module: str, name: str, method: str) -> bool:
+ """Check if a method invocation is allowed."""
+ key = (module, name, method)
+ if key in _lg_msgpack.SAFE_MSGPACK_METHODS:
+ return True
+ emit_serde_event(
+ {
+ "kind": "msgpack_method_blocked",
+ "module": module,
+ "name": name,
+ "method": method,
+ }
+ )
+ logger.warning(
+ "Blocked deserialization of method call %s.%s.%s - "
+ "not in allowed methods set.",
+ module,
+ name,
+ method,
+ )
+ return False
+
+ def ext_hook(code: int, data: bytes) -> Any:
+ if code == EXT_DELTA_SNAPSHOT:
+ return _DeltaSnapshot(
+ ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ )
+ elif code == EXT_CONSTRUCTOR_SINGLE_ARG:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed(tup[0], tup[1]):
+ # We default to returning the raw data. If the user
+ # is using this in the context of a pydantic state, etc., then
+ # it would be validated upon construction.
+ return tup[2]
+ # module, name, arg
+ return getattr(importlib.import_module(tup[0]), tup[1])(tup[2])
+ except Exception:
+ return None
+ elif code == EXT_CONSTRUCTOR_POS_ARGS:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed(tup[0], tup[1]):
+ return tup[2]
+ if tup[0] == "langgraph.types" and tup[1] == "Send":
+ return _send_from_args(tup[2])
+ # module, name, args
+ return getattr(importlib.import_module(tup[0]), tup[1])(*tup[2])
+ except Exception:
+ return None
+ elif code == EXT_CONSTRUCTOR_KW_ARGS:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed(tup[0], tup[1]):
+ return tup[2]
+ # module, name, kwargs
+ return getattr(importlib.import_module(tup[0]), tup[1])(**tup[2])
+ except Exception:
+ return None
+ elif code == EXT_METHOD_SINGLE_ARG:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed_method(tup[0], tup[1], tup[3]):
+ return tup[2]
+ # module, name, arg, method
+ return getattr(
+ getattr(importlib.import_module(tup[0]), tup[1]), tup[3]
+ )(tup[2])
+ except Exception:
+ return None
+ elif code == EXT_PYDANTIC_V1:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed(tup[0], tup[1]):
+ return tup[2]
+ # module, name, kwargs
+ cls = getattr(importlib.import_module(tup[0]), tup[1])
+ try:
+ return cls(**tup[2])
+ except Exception:
+ return cls.construct(**tup[2])
+ except Exception:
+ # for pydantic objects we can't find/reconstruct
+ # let's return the kwargs dict instead
+ try:
+ return tup[2]
+ except NameError:
+ return None
+ elif code == EXT_PYDANTIC_V2:
+ try:
+ tup = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ if not _check_allowed(tup[0], tup[1]):
+ return tup[2]
+ # module, name, kwargs, method
+ cls = getattr(importlib.import_module(tup[0]), tup[1])
+ try:
+ return cls(**tup[2])
+ except Exception:
+ return cls.model_construct(**tup[2])
+ except Exception:
+ # for pydantic objects we can't find/reconstruct
+ # let's return the kwargs dict instead
+ try:
+ return tup[2]
+ except NameError:
+ return None
+ elif code == EXT_NUMPY_ARRAY:
+ try:
+ import numpy as _np
+
+ dtype_str, shape, order, buf = ormsgpack.unpackb(
+ data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS
+ )
+ arr = _np.frombuffer(buf, dtype=_np.dtype(dtype_str))
+ return arr.reshape(shape, order=order)
+ except Exception:
+ return None
+ return None
+
+ return ext_hook
+
+
+# Aliasing in case anyone imported it directly
+_msgpack_ext_hook = _create_msgpack_ext_hook(allowed_modules=None)
+
+
+def _msgpack_ext_hook_to_json(code: int, data: bytes) -> Any:
+ if code == EXT_CONSTRUCTOR_SINGLE_ARG:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ if tup[0] == "uuid" and tup[1] == "UUID":
+ hex_ = tup[2]
+ return (
+ f"{hex_[:8]}-{hex_[8:12]}-{hex_[12:16]}-{hex_[16:20]}-{hex_[20:]}"
+ )
+ # module, name, arg
+ return tup[2]
+ except Exception:
+ return
+ elif code == EXT_CONSTRUCTOR_POS_ARGS:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ if tup[0] == "langgraph.types" and tup[1] == "Send":
+ return _send_from_args(tup[2])
+ # module, name, args
+ return tup[2]
+ except Exception:
+ return
+ elif code == EXT_CONSTRUCTOR_KW_ARGS:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ # module, name, args
+ return tup[2]
+ except Exception:
+ return
+ elif code == EXT_METHOD_SINGLE_ARG:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ # module, name, arg, method
+ return tup[2]
+ except Exception:
+ return
+ elif code == EXT_PYDANTIC_V1:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ # module, name, kwargs
+ return tup[2]
+ except Exception:
+ # for pydantic objects we can't find/reconstruct
+ # let's return the kwargs dict instead
+ return
+ elif code == EXT_PYDANTIC_V2:
+ try:
+ tup = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ # module, name, kwargs, method
+ return tup[2]
+ except Exception:
+ return
+ elif code == EXT_NUMPY_ARRAY:
+ try:
+ import numpy as _np
+
+ dtype_str, shape, order, buf = ormsgpack.unpackb(
+ data,
+ ext_hook=_msgpack_ext_hook_to_json,
+ option=ormsgpack.OPT_NON_STR_KEYS,
+ )
+ arr = _np.frombuffer(buf, dtype=_np.dtype(dtype_str))
+ return arr.reshape(shape, order=order).tolist()
+ except Exception:
+ return
+
+
+class InvalidModuleError(Exception):
+ """Exception raised when a module is not in the allowlist."""
+
+ def __init__(self, message: str):
+ self.message = message
+
+
+_option = (
+ ormsgpack.OPT_NON_STR_KEYS
+ | ormsgpack.OPT_PASSTHROUGH_DATACLASS
+ | ormsgpack.OPT_PASSTHROUGH_DATETIME
+ | ormsgpack.OPT_PASSTHROUGH_ENUM
+ | ormsgpack.OPT_PASSTHROUGH_UUID
+ | ormsgpack.OPT_REPLACE_SURROGATES
+)
+
+
+def _msgpack_enc(data: Any) -> bytes:
+ return ormsgpack.packb(data, default=_msgpack_default, option=_option)
+
+
+def _normalize_allowlist(
+ allowlist: AllowedMsgpackModules | Literal[True] | None,
+) -> set[tuple[str, ...]] | Literal[True] | None:
+ if allowlist is True:
+ return allowlist
+ elif allowlist:
+ return _normalize_module_keys(allowlist)
+ else:
+ return None
+
+
+def _normalize_module_keys(
+ modules: AllowedMsgpackModules,
+) -> set[tuple[str, ...]]:
+ normalized: set[tuple[str, ...]] = set()
+ for module in modules:
+ if isclass(module):
+ normalized.add((module.__module__, module.__name__))
+ else:
+ normalized.add(cast(tuple[str, ...], module))
+ return normalized
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/py.typed b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/types.py b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..72e37206462758bef1adf3abbe2d43e58a034532
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/checkpoint/serde/types.py
@@ -0,0 +1,68 @@
+from collections.abc import Sequence
+from typing import (
+ Any,
+ NamedTuple,
+ Protocol,
+ TypeVar,
+ runtime_checkable,
+)
+
+from typing_extensions import Self
+
+ERROR = "__error__"
+SCHEDULED = "__scheduled__"
+INTERRUPT = "__interrupt__"
+RESUME = "__resume__"
+TASKS = "__pregel_tasks"
+
+
+class _DeltaSnapshot(NamedTuple):
+ """Snapshot blob for a DeltaChannel with finite snapshot_frequency.
+
+ Stored in checkpoint_blobs via the `EXT_DELTA_SNAPSHOT` msgpack ext code.
+ The ancestor walk in `BaseCheckpointSaver.get_delta_channel_history` terminates
+ when it encounters this type (any non-empty channel_values entry stops
+ the walk for that channel).
+
+ `from_checkpoint` reconstructs the channel value directly from `.value`
+ without replaying writes — the snapshot IS the accumulated state.
+ """
+
+ value: Any
+
+
+Value = TypeVar("Value", covariant=True)
+Update = TypeVar("Update", contravariant=True)
+C = TypeVar("C")
+
+
+class ChannelProtocol(Protocol[Value, Update, C]):
+ # Mirrors langgraph.channels.base.BaseChannel
+ @property
+ def ValueType(self) -> Any: ...
+
+ @property
+ def UpdateType(self) -> Any: ...
+
+ def checkpoint(self) -> C | None: ...
+
+ def from_checkpoint(self, checkpoint: C | None) -> Self: ...
+
+ def update(self, values: Sequence[Update]) -> bool: ...
+
+ def get(self) -> Value: ...
+
+ def consume(self) -> bool: ...
+
+
+@runtime_checkable
+class SendProtocol(Protocol):
+ # Mirrors langgraph.constants.Send
+ node: str
+ arg: Any
+
+ def __hash__(self) -> int: ...
+
+ def __repr__(self) -> str: ...
+
+ def __eq__(self, value: object) -> bool: ...
diff --git a/python/user_packages/Python313/site-packages/langgraph/func/__init__.py b/python/user_packages/Python313/site-packages/langgraph/func/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..be310f0f8bac79efd9f19cd8983776f697d0f676
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/func/__init__.py
@@ -0,0 +1,620 @@
+from __future__ import annotations
+
+import functools
+import inspect
+import warnings
+from collections.abc import Awaitable, Callable, Sequence
+from dataclasses import dataclass
+from datetime import timedelta
+from typing import (
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+ get_args,
+ get_origin,
+ overload,
+)
+
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import BaseCheckpointSaver
+from langgraph.store.base import BaseStore
+from typing_extensions import Unpack
+
+from langgraph._internal import _serde
+from langgraph._internal._constants import CACHE_NS_WRITES, PREVIOUS
+from langgraph._internal._runnable import is_async_callable
+from langgraph._internal._timeout import (
+ coerce_timeout_policy,
+ sync_timeout_unsupported,
+)
+from langgraph._internal._typing import MISSING, DeprecatedKwargs
+from langgraph.channels.ephemeral_value import EphemeralValue
+from langgraph.channels.last_value import LastValue
+from langgraph.constants import END, START
+from langgraph.pregel import Pregel
+from langgraph.pregel._call import (
+ P,
+ SyncAsyncFuture,
+ T,
+ _call_with_options,
+ get_runnable_for_entrypoint,
+ identifier,
+)
+from langgraph.pregel._read import PregelNode
+from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
+from langgraph.types import (
+ _DC_KWARGS,
+ CachePolicy,
+ RetryPolicy,
+ StreamMode,
+ TimeoutPolicy,
+)
+from langgraph.typing import ContextT
+from langgraph.warnings import LangGraphDeprecatedSinceV05, LangGraphDeprecatedSinceV10
+
+__all__ = ("task", "entrypoint")
+
+
+class _TaskFunction(Generic[P, T]):
+ def __init__(
+ self,
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ *,
+ retry_policy: Sequence[RetryPolicy],
+ cache_policy: CachePolicy[Callable[P, str | bytes]] | None = None,
+ timeout: TimeoutPolicy | None = None,
+ name: str | None = None,
+ ) -> None:
+ if name is not None:
+ if hasattr(func, "__func__"):
+ # handle class methods
+ # NOTE: we're modifying the instance method to avoid modifying
+ # the original class method in case it's shared across multiple tasks
+ instance_method = functools.partial(func.__func__, func.__self__) # type: ignore [union-attr]
+ instance_method.__name__ = name # type: ignore [attr-defined]
+ func = instance_method
+ else:
+ # handle regular functions / partials / callable classes, etc.
+ func.__name__ = name
+ self.func = func
+ self.retry_policy = retry_policy
+ self.cache_policy = cache_policy
+ self.timeout = timeout
+ functools.update_wrapper(self, func)
+
+ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> SyncAsyncFuture[T]:
+ return _call_with_options(
+ self.func,
+ args,
+ kwargs,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ timeout=self.timeout,
+ )
+
+ def clear_cache(self, cache: BaseCache) -> None:
+ """Clear the cache for this task."""
+ if self.cache_policy is not None:
+ cache.clear(((CACHE_NS_WRITES, identifier(self.func) or "__dynamic__"),))
+
+ async def aclear_cache(self, cache: BaseCache) -> None:
+ """Clear the cache for this task."""
+ if self.cache_policy is not None:
+ await cache.aclear(
+ ((CACHE_NS_WRITES, identifier(self.func) or "__dynamic__"),)
+ )
+
+
+@overload
+def task(
+ __func_or_none__: None = None,
+ *,
+ name: str | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy[Callable[P, str | bytes]] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+) -> Callable[
+ [Callable[P, Awaitable[T]] | Callable[P, T]],
+ _TaskFunction[P, T],
+]: ...
+
+
+@overload
+def task(__func_or_none__: Callable[P, Awaitable[T]]) -> _TaskFunction[P, T]: ...
+
+
+@overload
+def task(__func_or_none__: Callable[P, T]) -> _TaskFunction[P, T]: ...
+
+
+def task(
+ __func_or_none__: Callable[P, Awaitable[T]] | Callable[P, T] | None = None,
+ *,
+ name: str | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy[Callable[P, str | bytes]] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+) -> (
+ Callable[[Callable[P, Awaitable[T]] | Callable[P, T]], _TaskFunction[P, T]]
+ | _TaskFunction[P, T]
+):
+ """Define a LangGraph task using the `task` decorator.
+
+ !!! important "Requires python 3.11 or higher for async functions"
+ The `task` decorator supports both sync and async functions. To use async
+ functions, ensure that you are using Python 3.11 or higher.
+
+ Tasks can only be called from within an [`entrypoint`][langgraph.func.entrypoint] or
+ from within a `StateGraph`. A task can be called like a regular function with the
+ following differences:
+
+ - When a checkpointer is enabled, the function inputs and outputs must be serializable.
+ - The decorated function can only be called from within an entrypoint or `StateGraph`.
+ - Calling the function produces a future. This makes it easy to parallelize tasks.
+
+ Args:
+ name: An optional name for the task. If not provided, the function name will be used.
+ retry_policy: An optional retry policy (or list of policies) to use for the task in case of a failure.
+ cache_policy: An optional cache policy to use for the task. This allows caching of the task results.
+ timeout: Timeout for each task attempt. A number or `timedelta` is a hard
+ wall-clock cap and is not refreshed. Use `TimeoutPolicy` to configure
+ both a wall-clock `run_timeout` and an `idle_timeout` refreshed by
+ progress signals. For long-running work that doesn't naturally emit
+ progress, call `runtime.heartbeat()` from inside the task. When the
+ timeout fires, `NodeTimeoutError` is raised and the retry policy (if
+ any) decides whether to retry. Supported only for async tasks; sync
+ tasks cannot be safely cancelled in-process.
+
+ Returns:
+ A callable function when used as a decorator.
+
+ Example: Sync Task
+ ```python
+ from langgraph.func import entrypoint, task
+
+
+ @task
+ def add_one_task(a: int) -> int:
+ return a + 1
+
+
+ @entrypoint()
+ def add_one(numbers: list[int]) -> list[int]:
+ futures = [add_one_task(n) for n in numbers]
+ results = [f.result() for f in futures]
+ return results
+
+
+ # Call the entrypoint
+ add_one.invoke([1, 2, 3]) # Returns [2, 3, 4]
+ ```
+
+ Example: Async Task
+ ```python
+ import asyncio
+ from langgraph.func import entrypoint, task
+
+
+ @task
+ async def add_one_task(a: int) -> int:
+ return a + 1
+
+
+ @entrypoint()
+ async def add_one(numbers: list[int]) -> list[int]:
+ futures = [add_one_task(n) for n in numbers]
+ return asyncio.gather(*futures)
+
+
+ # Call the entrypoint
+ await add_one.ainvoke([1, 2, 3]) # Returns [2, 3, 4]
+ ```
+ """
+ if (retry := kwargs.get("retry", MISSING)) is not MISSING:
+ warnings.warn(
+ "`retry` is deprecated and will be removed. Please use `retry_policy` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ stacklevel=2,
+ )
+ if retry_policy is None:
+ retry_policy = retry # type: ignore[assignment]
+ timeout_policy = coerce_timeout_policy(timeout)
+
+ retry_policies: Sequence[RetryPolicy] = (
+ ()
+ if retry_policy is None
+ else (retry_policy,)
+ if isinstance(retry_policy, RetryPolicy)
+ else retry_policy
+ )
+
+ def decorator(
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ ) -> Callable[P, SyncAsyncFuture[T]]:
+ if timeout_policy is not None and not is_async_callable(func):
+ name_ = name or getattr(func, "__name__", func.__class__.__name__)
+ raise sync_timeout_unsupported(str(name_), kind="Task")
+ return _TaskFunction(
+ func,
+ retry_policy=retry_policies,
+ cache_policy=cache_policy,
+ timeout=timeout_policy,
+ name=name,
+ )
+
+ if __func_or_none__ is not None:
+ return decorator(__func_or_none__)
+
+ return decorator
+
+
+R = TypeVar("R")
+S = TypeVar("S")
+
+
+# The decorator was wrapped in a class to support the `final` attribute.
+# In this form, the `final` attribute should play nicely with IDE autocompletion,
+# and type checking tools.
+# In addition, we'll be able to surface this information in the API Reference.
+class entrypoint(Generic[ContextT]):
+ """Define a LangGraph workflow using the `entrypoint` decorator.
+
+ ### Function signature
+
+ The decorated function must accept a **single parameter**, which serves as the input
+ to the function. This input parameter can be of any type. Use a dictionary
+ to pass **multiple parameters** to the function.
+
+ ### Injectable parameters
+
+ The decorated function can request access to additional parameters
+ that will be injected automatically at run time. These parameters include:
+
+ | Parameter | Description |
+ |------------------|------------------------------------------------------------------------------------------------------|
+ | **`config`** | A configuration object (aka `RunnableConfig`) that holds run-time configuration values. |
+ | **`previous`** | The previous return value for the given thread (available only when a checkpointer is provided). |
+ | **`runtime`** | A `Runtime` object that contains information about the current run, including context, store, writer |
+
+ The entrypoint decorator can be applied to sync functions or async functions.
+
+ ### State management
+
+ The **`previous`** parameter can be used to access the return value of the previous
+ invocation of the entrypoint on the same thread id. This value is only available
+ when a checkpointer is provided.
+
+ If you want **`previous`** to be different from the return value, you can use the
+ `entrypoint.final` object to return a value while saving a different value to the
+ checkpoint.
+
+ Args:
+ checkpointer: Specify a checkpointer to create a workflow that can persist
+ its state across runs.
+ store: A generalized key-value store. Some implementations may support
+ semantic search capabilities through an optional `index` configuration.
+ cache: A cache to use for caching the results of the workflow.
+ context_schema: Specifies the schema for the context object that will be
+ passed to the workflow.
+ cache_policy: A cache policy to use for caching the results of the workflow.
+ retry_policy: A retry policy (or list of policies) to use for the workflow in case of a failure.
+ timeout: Timeout for each workflow attempt. A number or `timedelta` is a
+ hard wall-clock cap and is not refreshed. Use `TimeoutPolicy` to
+ configure both a wall-clock `run_timeout` and an `idle_timeout`
+ refreshed by progress signals. For long-running work that doesn't
+ naturally emit progress, call `runtime.heartbeat()` from inside the
+ workflow. When the timeout fires, `NodeTimeoutError` is raised and
+ the retry policy (if any) decides whether to retry. Supported only
+ for async workflows; sync workflows cannot be safely cancelled
+ in-process.
+
+ !!! warning "`config_schema` Deprecated"
+ The `config_schema` parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
+ Please use `context_schema` instead to specify the schema for run-scoped context.
+
+
+ Example: Using entrypoint and tasks
+ ```python
+ import time
+
+ from langgraph.func import entrypoint, task
+ from langgraph.types import interrupt, Command
+ from langgraph.checkpoint.memory import InMemorySaver
+
+ @task
+ def compose_essay(topic: str) -> str:
+ time.sleep(1.0) # Simulate slow operation
+ return f"An essay about {topic}"
+
+ @entrypoint(checkpointer=InMemorySaver())
+ def review_workflow(topic: str) -> dict:
+ \"\"\"Manages the workflow for generating and reviewing an essay.
+
+ The workflow includes:
+ 1. Generating an essay about the given topic.
+ 2. Interrupting the workflow for human review of the generated essay.
+
+ Upon resuming the workflow, compose_essay task will not be re-executed
+ as its result is cached by the checkpointer.
+
+ Args:
+ topic: The subject of the essay.
+
+ Returns:
+ dict: A dictionary containing the generated essay and the human review.
+ \"\"\"
+ essay_future = compose_essay(topic)
+ essay = essay_future.result()
+ human_review = interrupt({
+ \"question\": \"Please provide a review\",
+ \"essay\": essay
+ })
+ return {
+ \"essay\": essay,
+ \"review\": human_review,
+ }
+
+ # Example configuration for the workflow
+ config = {
+ \"configurable\": {
+ \"thread_id\": \"some_thread\"
+ }
+ }
+
+ # Topic for the essay
+ topic = \"cats\"
+
+ # Stream the workflow to generate the essay and await human review
+ for result in review_workflow.stream(topic, config):
+ print(result)
+
+ # Example human review provided after the interrupt
+ human_review = \"This essay is great.\"
+
+ # Resume the workflow with the provided human review
+ for result in review_workflow.stream(Command(resume=human_review), config):
+ print(result)
+ ```
+
+ Example: Accessing the previous return value
+ When a checkpointer is enabled the function can access the previous return value
+ of the previous invocation on the same thread id.
+
+ ```python
+ from typing import Optional
+
+ from langgraph.checkpoint.memory import MemorySaver
+
+ from langgraph.func import entrypoint
+
+
+ @entrypoint(checkpointer=InMemorySaver())
+ def my_workflow(input_data: str, previous: Optional[str] = None) -> str:
+ return "world"
+
+
+ config = {"configurable": {"thread_id": "some_thread"}}
+ my_workflow.invoke("hello", config)
+ ```
+
+ Example: Using `entrypoint.final` to save a value
+ The `entrypoint.final` object allows you to return a value while saving
+ a different value to the checkpoint. This value will be accessible
+ in the next invocation of the entrypoint via the `previous` parameter, as
+ long as the same thread id is used.
+
+ ```python
+ from typing import Any
+
+ from langgraph.checkpoint.memory import MemorySaver
+
+ from langgraph.func import entrypoint
+
+
+ @entrypoint(checkpointer=InMemorySaver())
+ def my_workflow(
+ number: int,
+ *,
+ previous: Any = None,
+ ) -> entrypoint.final[int, int]:
+ previous = previous or 0
+ # This will return the previous value to the caller, saving
+ # 2 * number to the checkpoint, which will be used in the next invocation
+ # for the `previous` parameter.
+ return entrypoint.final(value=previous, save=2 * number)
+
+
+ config = {"configurable": {"thread_id": "some_thread"}}
+
+ my_workflow.invoke(3, config) # 0 (previous was None)
+ my_workflow.invoke(1, config) # 6 (previous was 3 * 2 from the previous invocation)
+ ```
+ """
+
+ def __init__(
+ self,
+ checkpointer: BaseCheckpointSaver | None = None,
+ store: BaseStore | None = None,
+ cache: BaseCache | None = None,
+ context_schema: type[ContextT] | None = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> None:
+ """Initialize the entrypoint decorator."""
+ if (config_schema := kwargs.get("config_schema", MISSING)) is not MISSING:
+ warnings.warn(
+ "`config_schema` is deprecated and will be removed. Please use `context_schema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if context_schema is None:
+ context_schema = cast(type[ContextT], config_schema)
+
+ if (retry := kwargs.get("retry", MISSING)) is not MISSING:
+ warnings.warn(
+ "`retry` is deprecated and will be removed. Please use `retry_policy` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ stacklevel=2,
+ )
+ if retry_policy is None:
+ retry_policy = cast("RetryPolicy | Sequence[RetryPolicy]", retry)
+
+ self.checkpointer = checkpointer
+ self.store = store
+ self.cache = cache
+ self.cache_policy = cache_policy
+ self.retry_policy = retry_policy
+ self.timeout = coerce_timeout_policy(timeout)
+ self.context_schema = context_schema
+
+ @dataclass(**_DC_KWARGS)
+ class final(Generic[R, S]):
+ """A primitive that can be returned from an entrypoint.
+
+ This primitive allows to save a value to the checkpointer distinct from the
+ return value from the entrypoint.
+
+ Example: Decoupling the return value and the save value
+ ```python
+ from langgraph.checkpoint.memory import InMemorySaver
+ from langgraph.func import entrypoint
+
+
+ @entrypoint(checkpointer=InMemorySaver())
+ def my_workflow(
+ number: int,
+ *,
+ previous: Any = None,
+ ) -> entrypoint.final[int, int]:
+ previous = previous or 0
+ # This will return the previous value to the caller, saving
+ # 2 * number to the checkpoint, which will be used in the next invocation
+ # for the `previous` parameter.
+ return entrypoint.final(value=previous, save=2 * number)
+
+
+ config = {"configurable": {"thread_id": "1"}}
+
+ my_workflow.invoke(3, config) # 0 (previous was None)
+ my_workflow.invoke(1, config) # 6 (previous was 3 * 2 from the previous invocation)
+ ```
+ """
+
+ value: R
+ """Value to return. A value will always be returned even if it is `None`."""
+ save: S
+ """The value for the state for the next checkpoint.
+
+ A value will always be saved even if it is `None`.
+ """
+
+ def __call__(self, func: Callable[..., Any]) -> Pregel:
+ """Convert a function into a Pregel graph.
+
+ Args:
+ func: The function to convert. Support both sync and async functions.
+
+ Returns:
+ A Pregel graph.
+ """
+ # wrap generators in a function that writes to StreamWriter
+ if inspect.isgeneratorfunction(func) or inspect.isasyncgenfunction(func):
+ raise NotImplementedError(
+ "Generators are not supported in the Functional API."
+ )
+
+ bound = get_runnable_for_entrypoint(func)
+ stream_mode: StreamMode = "updates"
+
+ # get input and output types
+ sig = inspect.signature(func)
+ first_parameter_name = next(iter(sig.parameters.keys()), None)
+ if not first_parameter_name:
+ raise ValueError("Entrypoint function must have at least one parameter")
+ input_type = (
+ sig.parameters[first_parameter_name].annotation
+ if sig.parameters[first_parameter_name].annotation
+ is not inspect.Signature.empty
+ else Any
+ )
+
+ def _pluck_return_value(value: Any) -> Any:
+ """Extract the return_ value the entrypoint.final object or passthrough."""
+ return value.value if isinstance(value, entrypoint.final) else value
+
+ def _pluck_save_value(value: Any) -> Any:
+ """Get save value from the entrypoint.final object or passthrough."""
+ return value.save if isinstance(value, entrypoint.final) else value
+
+ output_type, save_type = Any, Any
+ if sig.return_annotation is not inspect.Signature.empty:
+ # User does not parameterize entrypoint.final properly
+ if (
+ sig.return_annotation is entrypoint.final
+ ): # Un-parameterized entrypoint.final
+ output_type = save_type = Any
+ else:
+ origin = get_origin(sig.return_annotation)
+ if origin is entrypoint.final:
+ type_annotations = get_args(sig.return_annotation)
+ if len(type_annotations) != 2:
+ raise TypeError(
+ "Please an annotation for both the return_ and "
+ "the save values."
+ "For example, `-> entrypoint.final[int, str]` would assign a "
+ "return_ a type of `int` and save the type `str`."
+ )
+ output_type, save_type = get_args(sig.return_annotation)
+ else:
+ output_type = save_type = sig.return_annotation
+
+ graph: Pregel[Any, ContextT, Any, Any] = Pregel(
+ nodes={
+ func.__name__: PregelNode(
+ bound=bound,
+ triggers=[START],
+ channels=START,
+ timeout=self.timeout,
+ writers=[
+ ChannelWrite(
+ [
+ ChannelWriteEntry(END, mapper=_pluck_return_value),
+ ChannelWriteEntry(PREVIOUS, mapper=_pluck_save_value),
+ ]
+ )
+ ],
+ )
+ },
+ channels={
+ START: EphemeralValue(input_type),
+ END: LastValue(output_type, END),
+ PREVIOUS: LastValue(save_type, PREVIOUS),
+ },
+ input_channels=START,
+ output_channels=END,
+ stream_channels=END,
+ stream_mode=stream_mode,
+ stream_eager=True,
+ checkpointer=self.checkpointer,
+ store=self.store,
+ cache=self.cache,
+ cache_policy=self.cache_policy,
+ retry_policy=self.retry_policy or (),
+ context_schema=self.context_schema,
+ )
+ if _serde.STRICT_MSGPACK_ENABLED:
+ serde_allowlist = _serde.build_serde_allowlist(
+ schemas=[input_type, output_type, save_type]
+ + ([self.context_schema] if self.context_schema is not None else []),
+ channels=graph.channels,
+ )
+ graph._serde_allowlist = serde_allowlist
+ graph.checkpointer = _serde.apply_checkpointer_allowlist(
+ graph.checkpointer, serde_allowlist
+ )
+ return graph
diff --git a/python/user_packages/Python313/site-packages/langgraph/func/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/func/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd1e0ebda100f483f4880ebdfc81ff4d5336b215
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/func/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__init__.py b/python/user_packages/Python313/site-packages/langgraph/graph/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bea3fc8294fa3f0fc60451d46e40fa1d74c28fd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/__init__.py
@@ -0,0 +1,12 @@
+from langgraph.constants import END, START
+from langgraph.graph.message import MessageGraph, MessagesState, add_messages
+from langgraph.graph.state import StateGraph
+
+__all__ = (
+ "END",
+ "START",
+ "StateGraph",
+ "add_messages",
+ "MessagesState",
+ "MessageGraph",
+)
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f76a8e59674963fea1751a072c6876bb680edd4f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_branch.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_branch.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7004467d5e5173cd7bbcfd9f28cd47e5a29e44a1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_branch.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_node.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_node.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f4bcdc6236741fe3cb3258cb1d77c2d4149a6b8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/_node.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/message.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/message.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90533595528ae02a26237b7f786609f64ee8b336
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/message.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/state.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/state.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af2340f83a95ef7e7d88cdd4cc85674697919348
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/state.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/ui.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/ui.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34ac6af2a33491e62c16c708a0b4fb78b99e1bf9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/graph/__pycache__/ui.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/_branch.py b/python/user_packages/Python313/site-packages/langgraph/graph/_branch.py
new file mode 100644
index 0000000000000000000000000000000000000000..df5136d5f741742a9e25f9ea6315d0eefe744f07
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/_branch.py
@@ -0,0 +1,225 @@
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable, Hashable, Sequence
+from inspect import (
+ isfunction,
+ ismethod,
+ signature,
+)
+from itertools import zip_longest
+from types import FunctionType
+from typing import (
+ Any,
+ Literal,
+ NamedTuple,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+from langchain_core.runnables import (
+ Runnable,
+ RunnableConfig,
+ RunnableLambda,
+)
+
+from langgraph._internal._runnable import (
+ RunnableCallable,
+)
+from langgraph.constants import END, START
+from langgraph.errors import InvalidUpdateError
+from langgraph.pregel._write import PASSTHROUGH, ChannelWrite, ChannelWriteEntry
+from langgraph.types import Send
+
+_Writer = Callable[
+ [Sequence[str | Send], bool],
+ Sequence[ChannelWriteEntry | Send],
+]
+
+
+def _get_branch_path_input_schema(
+ path: Callable[..., Hashable | Sequence[Hashable]]
+ | Callable[..., Awaitable[Hashable | Sequence[Hashable]]]
+ | Runnable[Any, Hashable | Sequence[Hashable]],
+) -> type[Any] | None:
+ input = None
+ # detect input schema annotation in the branch callable
+ try:
+ callable_: (
+ Callable[..., Hashable | Sequence[Hashable]]
+ | Callable[..., Awaitable[Hashable | Sequence[Hashable]]]
+ | None
+ ) = None
+ if isinstance(path, (RunnableCallable, RunnableLambda)):
+ if isfunction(path.func) or ismethod(path.func):
+ callable_ = path.func
+ elif (callable_method := getattr(path.func, "__call__", None)) and ismethod(
+ callable_method
+ ):
+ callable_ = callable_method
+ elif isfunction(path.afunc) or ismethod(path.afunc):
+ callable_ = path.afunc
+ elif (
+ callable_method := getattr(path.afunc, "__call__", None)
+ ) and ismethod(callable_method):
+ callable_ = callable_method
+ elif callable(path):
+ callable_ = path
+
+ if callable_ is not None and (hints := get_type_hints(callable_)):
+ first_parameter_name = next(
+ iter(signature(cast(FunctionType, callable_)).parameters.keys())
+ )
+ if input_hint := hints.get(first_parameter_name):
+ if isinstance(input_hint, type) and get_type_hints(input_hint):
+ input = input_hint
+ except (TypeError, StopIteration):
+ pass
+
+ return input
+
+
+class BranchSpec(NamedTuple):
+ path: Runnable[Any, Hashable | list[Hashable]]
+ ends: dict[Hashable, str] | None
+ input_schema: type[Any] | None = None
+
+ @classmethod
+ def from_path(
+ cls,
+ path: Runnable[Any, Hashable | list[Hashable]],
+ path_map: dict[Hashable, str] | list[str] | None,
+ infer_schema: bool = False,
+ ) -> BranchSpec:
+ # coerce path_map to a dictionary
+ path_map_: dict[Hashable, str] | None = None
+ try:
+ if isinstance(path_map, dict):
+ path_map_ = path_map.copy()
+ elif isinstance(path_map, list):
+ path_map_ = {name: name for name in path_map}
+ else:
+ # find func
+ func: Callable | None = None
+ if isinstance(path, (RunnableCallable, RunnableLambda)):
+ func = path.func or path.afunc
+ if func is not None:
+ # find callable method
+ if (cal := getattr(path, "__call__", None)) and ismethod(cal):
+ func = cal
+ # get the return type
+ if rtn_type := get_type_hints(func).get("return"):
+ if get_origin(rtn_type) is Literal:
+ path_map_ = {name: name for name in get_args(rtn_type)}
+ except Exception:
+ pass
+ # infer input schema
+ input_schema = _get_branch_path_input_schema(path) if infer_schema else None
+ # create branch
+ return cls(path=path, ends=path_map_, input_schema=input_schema)
+
+ def run(
+ self,
+ writer: _Writer,
+ reader: Callable[[RunnableConfig], Any] | None = None,
+ ) -> RunnableCallable:
+ return ChannelWrite.register_writer(
+ RunnableCallable(
+ func=self._route,
+ afunc=self._aroute,
+ writer=writer,
+ reader=reader,
+ name=None,
+ trace=False,
+ ),
+ list(
+ zip_longest(
+ writer([e for e in self.ends.values()], True),
+ [str(la) for la, e in self.ends.items()],
+ )
+ )
+ if self.ends
+ else None,
+ )
+
+ def _route(
+ self,
+ input: Any,
+ config: RunnableConfig,
+ *,
+ reader: Callable[[RunnableConfig], Any] | None,
+ writer: _Writer,
+ ) -> Runnable:
+ if reader:
+ value = reader(config)
+ # passthrough additional keys from node to branch
+ # only doable when using dict states
+ if (
+ isinstance(value, dict)
+ and isinstance(input, dict)
+ and self.input_schema is None
+ ):
+ value = {**input, **value}
+ else:
+ value = input
+ result = self.path.invoke(value, config)
+ return self._finish(writer, input, result, config)
+
+ async def _aroute(
+ self,
+ input: Any,
+ config: RunnableConfig,
+ *,
+ reader: Callable[[RunnableConfig], Any] | None,
+ writer: _Writer,
+ ) -> Runnable:
+ if reader:
+ value = reader(config)
+ # passthrough additional keys from node to branch
+ # only doable when using dict states
+ if (
+ isinstance(value, dict)
+ and isinstance(input, dict)
+ and self.input_schema is None
+ ):
+ value = {**input, **value}
+ else:
+ value = input
+ result = await self.path.ainvoke(value, config)
+ return self._finish(writer, input, result, config)
+
+ def _finish(
+ self,
+ writer: _Writer,
+ input: Any,
+ result: Any,
+ config: RunnableConfig,
+ ) -> Runnable | Any:
+ if not isinstance(result, (list, tuple)):
+ result = [result]
+ if self.ends:
+ destinations: Sequence[Send | str] = [
+ r if isinstance(r, Send) else self.ends[r] for r in result
+ ]
+ else:
+ destinations = cast(Sequence[Send | str], result)
+ if any(dest is None or dest == START for dest in destinations):
+ raise ValueError("Branch did not return a valid destination")
+ if any(p.node == END for p in destinations if isinstance(p, Send)):
+ raise InvalidUpdateError("Cannot send a packet to the END node")
+ entries = writer(destinations, False)
+ if not entries:
+ return input
+ else:
+ need_passthrough = False
+ for e in entries:
+ if isinstance(e, ChannelWriteEntry):
+ if e.value is PASSTHROUGH:
+ need_passthrough = True
+ break
+ if need_passthrough:
+ return ChannelWrite(entries)
+ else:
+ ChannelWrite.do_write(config, entries)
+ return input
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/_node.py b/python/user_packages/Python313/site-packages/langgraph/graph/_node.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8238c2b3e6fd6fbe1547d5a0788cfea2e934ccc
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/_node.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import Any, Generic, Protocol, TypeAlias
+
+from langchain_core.runnables import Runnable, RunnableConfig
+from langgraph.store.base import BaseStore
+
+from langgraph._internal._typing import EMPTY_SEQ
+from langgraph.runtime import Runtime
+from langgraph.types import CachePolicy, RetryPolicy, StreamWriter, TimeoutPolicy
+from langgraph.typing import ContextT, NodeInputT, NodeInputT_contra
+
+
+class _Node(Protocol[NodeInputT_contra]):
+ def __call__(self, state: NodeInputT_contra) -> Any: ...
+
+
+class _NodeWithConfig(Protocol[NodeInputT_contra]):
+ def __call__(self, state: NodeInputT_contra, config: RunnableConfig) -> Any: ...
+
+
+class _NodeWithWriter(Protocol[NodeInputT_contra]):
+ def __call__(self, state: NodeInputT_contra, *, writer: StreamWriter) -> Any: ...
+
+
+class _NodeWithStore(Protocol[NodeInputT_contra]):
+ def __call__(self, state: NodeInputT_contra, *, store: BaseStore) -> Any: ...
+
+
+class _NodeWithWriterStore(Protocol[NodeInputT_contra]):
+ def __call__(
+ self, state: NodeInputT_contra, *, writer: StreamWriter, store: BaseStore
+ ) -> Any: ...
+
+
+class _NodeWithConfigWriter(Protocol[NodeInputT_contra]):
+ def __call__(
+ self, state: NodeInputT_contra, *, config: RunnableConfig, writer: StreamWriter
+ ) -> Any: ...
+
+
+class _NodeWithConfigStore(Protocol[NodeInputT_contra]):
+ def __call__(
+ self, state: NodeInputT_contra, *, config: RunnableConfig, store: BaseStore
+ ) -> Any: ...
+
+
+class _NodeWithConfigWriterStore(Protocol[NodeInputT_contra]):
+ def __call__(
+ self,
+ state: NodeInputT_contra,
+ *,
+ config: RunnableConfig,
+ writer: StreamWriter,
+ store: BaseStore,
+ ) -> Any: ...
+
+
+class _NodeWithRuntime(Protocol[NodeInputT_contra, ContextT]):
+ def __call__(
+ self, state: NodeInputT_contra, *, runtime: Runtime[ContextT]
+ ) -> Any: ...
+
+
+# TODO: we probably don't want to explicitly support the config / store signatures once
+# we move to adding a context arg. Maybe what we do is we add support for kwargs with param spec
+# this is purely for typing purposes though, so can easily change in the coming weeks.
+StateNode: TypeAlias = (
+ _Node[NodeInputT]
+ | _NodeWithConfig[NodeInputT]
+ | _NodeWithWriter[NodeInputT]
+ | _NodeWithStore[NodeInputT]
+ | _NodeWithWriterStore[NodeInputT]
+ | _NodeWithConfigWriter[NodeInputT]
+ | _NodeWithConfigStore[NodeInputT]
+ | _NodeWithConfigWriterStore[NodeInputT]
+ | _NodeWithRuntime[NodeInputT, ContextT]
+ | Runnable[NodeInputT, Any]
+)
+
+
+@dataclass(slots=True)
+class StateNodeSpec(Generic[NodeInputT, ContextT]):
+ runnable: StateNode[NodeInputT, ContextT]
+ metadata: dict[str, Any] | None
+ input_schema: type[NodeInputT]
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None
+ cache_policy: CachePolicy | None
+ is_error_handler: bool = False
+ error_handler_node: str | None = None
+ ends: tuple[str, ...] | dict[str, str] | None = EMPTY_SEQ
+ defer: bool = False
+ timeout: TimeoutPolicy | None = None
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/message.py b/python/user_packages/Python313/site-packages/langgraph/graph/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f375ad2ad52d97e199caea9964769b1ea19b7a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/message.py
@@ -0,0 +1,437 @@
+from __future__ import annotations
+
+import uuid
+import warnings
+from collections.abc import Callable, Sequence
+from functools import partial
+from typing import (
+ Annotated,
+ Any,
+ Literal,
+ cast,
+)
+
+from langchain_core.messages import (
+ AnyMessage,
+ BaseMessage,
+ BaseMessageChunk,
+ MessageLikeRepresentation,
+ RemoveMessage,
+ convert_to_messages,
+ message_chunk_to_message,
+)
+from typing_extensions import TypedDict, deprecated
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, NS_SEP
+from langgraph.graph.state import StateGraph
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+
+__all__ = (
+ "add_messages",
+ "MessagesState",
+ "MessageGraph",
+ "REMOVE_ALL_MESSAGES",
+)
+
+Messages = list[MessageLikeRepresentation] | MessageLikeRepresentation
+
+REMOVE_ALL_MESSAGES = "__remove_all__"
+
+
+def _add_messages_wrapper(func: Callable) -> Callable[[Messages, Messages], Messages]:
+ def _add_messages(
+ left: Messages | None = None, right: Messages | None = None, **kwargs: Any
+ ) -> Messages | Callable[[Messages, Messages], Messages]:
+ if left is not None and right is not None:
+ return func(left, right, **kwargs)
+ elif left is not None or right is not None:
+ msg = (
+ f"Must specify non-null arguments for both 'left' and 'right'. Only "
+ f"received: '{'left' if left else 'right'}'."
+ )
+ raise ValueError(msg)
+ else:
+ return partial(func, **kwargs)
+
+ _add_messages.__doc__ = func.__doc__
+ return cast(Callable[[Messages, Messages], Messages], _add_messages)
+
+
+@_add_messages_wrapper
+def add_messages(
+ left: Messages,
+ right: Messages,
+ *,
+ format: Literal["langchain-openai"] | None = None,
+) -> Messages:
+ """Merges two lists of messages, updating existing messages by ID.
+
+ By default, this ensures the state is "append-only", unless the
+ new message has the same ID as an existing message.
+
+ Args:
+ left: The base list of `Messages`.
+ right: The list of `Messages` (or single `Message`) to merge
+ into the base list.
+ format: The format to return messages in. If `None` then `Messages` will be
+ returned as is. If `langchain-openai` then `Messages` will be returned as
+ `BaseMessage` objects with their contents formatted to match OpenAI message
+ format, meaning contents can be string, `'text'` blocks, or `'image_url'` blocks
+ and tool responses are returned as their own `ToolMessage` objects.
+
+ !!! important "Requirement"
+
+ Must have `langchain-core>=0.3.11` installed to use this feature.
+
+ Returns:
+ A new list of messages with the messages from `right` merged into `left`.
+ If a message in `right` has the same ID as a message in `left`, the
+ message from `right` will replace the message from `left`.
+
+ Example: Basic usage
+ ```python
+ from langchain_core.messages import AIMessage, HumanMessage
+
+ msgs1 = [HumanMessage(content="Hello", id="1")]
+ msgs2 = [AIMessage(content="Hi there!", id="2")]
+ add_messages(msgs1, msgs2)
+ # [HumanMessage(content='Hello', id='1'), AIMessage(content='Hi there!', id='2')]
+ ```
+
+ Example: Overwrite existing message
+ ```python
+ msgs1 = [HumanMessage(content="Hello", id="1")]
+ msgs2 = [HumanMessage(content="Hello again", id="1")]
+ add_messages(msgs1, msgs2)
+ # [HumanMessage(content='Hello again', id='1')]
+ ```
+
+ Example: Use in a StateGraph
+ ```python
+ from typing import Annotated
+ from typing_extensions import TypedDict
+ from langgraph.graph import StateGraph
+
+
+ class State(TypedDict):
+ messages: Annotated[list, add_messages]
+
+
+ builder = StateGraph(State)
+ builder.add_node("chatbot", lambda state: {"messages": [("assistant", "Hello")]})
+ builder.set_entry_point("chatbot")
+ builder.set_finish_point("chatbot")
+ graph = builder.compile()
+ graph.invoke({})
+ # {'messages': [AIMessage(content='Hello', id=...)]}
+ ```
+
+ Example: Use OpenAI message format
+ ```python
+ from typing import Annotated
+ from typing_extensions import TypedDict
+ from langgraph.graph import StateGraph, add_messages
+
+
+ class State(TypedDict):
+ messages: Annotated[list, add_messages(format="langchain-openai")]
+
+
+ def chatbot_node(state: State) -> list:
+ return {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "Here's an image:",
+ "cache_control": {"type": "ephemeral"},
+ },
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/jpeg",
+ "data": "1234",
+ },
+ },
+ ],
+ },
+ ]
+ }
+
+
+ builder = StateGraph(State)
+ builder.add_node("chatbot", chatbot_node)
+ builder.set_entry_point("chatbot")
+ builder.set_finish_point("chatbot")
+ graph = builder.compile()
+ graph.invoke({"messages": []})
+ # {
+ # 'messages': [
+ # HumanMessage(
+ # content=[
+ # {"type": "text", "text": "Here's an image:"},
+ # {
+ # "type": "image_url",
+ # "image_url": {"url": "data:image/jpeg;base64,1234"},
+ # },
+ # ],
+ # ),
+ # ]
+ # }
+ ```
+
+ """
+ remove_all_idx = None
+ # coerce to list
+ if not isinstance(left, list):
+ left = [left] # type: ignore[assignment]
+ if not isinstance(right, list):
+ right = [right] # type: ignore[assignment]
+ # coerce to message
+ left = [
+ message_chunk_to_message(cast(BaseMessageChunk, m))
+ for m in convert_to_messages(left)
+ ]
+ right = [
+ message_chunk_to_message(cast(BaseMessageChunk, m))
+ for m in convert_to_messages(right)
+ ]
+ # assign missing ids
+ for m in left:
+ if m.id is None:
+ m.id = str(uuid.uuid4())
+ for idx, m in enumerate(right):
+ if m.id is None:
+ m.id = str(uuid.uuid4())
+ if isinstance(m, RemoveMessage) and m.id == REMOVE_ALL_MESSAGES:
+ remove_all_idx = idx
+
+ if remove_all_idx is not None:
+ return right[remove_all_idx + 1 :]
+
+ # merge
+ merged = left.copy()
+ merged_by_id = {m.id: i for i, m in enumerate(merged)}
+ ids_to_remove = set()
+ for m in right:
+ if (existing_idx := merged_by_id.get(m.id)) is not None:
+ if isinstance(m, RemoveMessage):
+ ids_to_remove.add(m.id)
+ else:
+ ids_to_remove.discard(m.id)
+ merged[existing_idx] = m
+ else:
+ if isinstance(m, RemoveMessage):
+ raise ValueError(
+ f"Attempting to delete a message with an ID that doesn't exist ('{m.id}')"
+ )
+
+ merged_by_id[m.id] = len(merged)
+ merged.append(m)
+ merged = [m for m in merged if m.id not in ids_to_remove]
+
+ if format == "langchain-openai":
+ merged = _format_messages(merged)
+ elif format:
+ msg = f"Unrecognized {format=}. Expected one of 'langchain-openai', None."
+ raise ValueError(msg)
+ else:
+ pass
+
+ return merged
+
+
+def _messages_delta_reducer(
+ state: list[AnyMessage], writes: list[list[AnyMessage]]
+) -> list[AnyMessage]:
+ """**Experimental.** Batch reducer for use with `DeltaChannel`.
+
+ Processes all writes in one pass — dedup by ID, `RemoveMessage`
+ tombstoning — without calling `add_messages`.
+
+ This reducer is batching-invariant, as required by `DeltaChannel`:
+ `reducer(reducer(state, xs), ys) == reducer(state, xs + ys)`.
+
+ Raw dict / string / tuple inputs are coerced to typed `BaseMessage`
+ objects so that HTTP-driven graphs work without a separate coercion
+ step. This is not full `add_messages` parity — `REMOVE_ALL_MESSAGES`,
+ unknown-id `RemoveMessage` errors, missing-id UUID assignment, and
+ `BaseMessageChunk` conversion are not handled here.
+
+ Example::
+
+ from typing import Annotated
+ from langgraph.channels.delta import DeltaChannel
+ from langgraph.graph.message import _messages_delta_reducer
+
+ class State(TypedDict):
+ messages: Annotated[list, DeltaChannel(_messages_delta_reducer)]
+ """
+
+ # Each write is either a list of message-likes or a single message-like
+ # (BaseMessage / dict / str / tuple). Only lists flatten; everything
+ # else is one message.
+ flat: list[Any] = []
+ for w in writes:
+ if isinstance(w, list):
+ flat.extend(w)
+ else:
+ flat.append(w)
+ # Steady state: the reducer's own output is already typed, so skip
+ # `convert_to_messages` on state when the first element is a BaseMessage.
+ # Only raw input (initial dicts, deserialized blobs) hits the slow path.
+ if state and isinstance(state[0], BaseMessage):
+ state_msgs = state
+ else:
+ state_msgs = cast("list[AnyMessage]", convert_to_messages(state))
+ msgs = cast("list[AnyMessage]", convert_to_messages(flat))
+
+ index: dict[str, int] = {
+ m.id: i for i, m in enumerate(state_msgs) if m.id is not None
+ }
+ result: list[AnyMessage | None] = list(state_msgs)
+ for msg in msgs:
+ mid = msg.id
+ if mid is None:
+ result.append(msg)
+ elif isinstance(msg, RemoveMessage):
+ if mid in index:
+ result[index[mid]] = None
+ del index[mid]
+ elif mid in index:
+ result[index[mid]] = msg
+ else:
+ index[mid] = len(result)
+ result.append(msg)
+ return [m for m in result if m is not None]
+
+
+@deprecated(
+ "MessageGraph is deprecated in langgraph 1.0.0, to be removed in 2.0.0. Please use StateGraph with a `messages` key instead.",
+ category=None,
+)
+class MessageGraph(StateGraph):
+ """A StateGraph where every node receives a list of messages as input and returns one or more messages as output.
+
+ MessageGraph is a subclass of StateGraph whose entire state is a single, append-only* list of messages.
+ Each node in a MessageGraph takes a list of messages as input and returns zero or more
+ messages as output. The `add_messages` function is used to merge the output messages from each node
+ into the existing list of messages in the graph's state.
+
+ Examples:
+ ```pycon
+ >>> from langgraph.graph.message import MessageGraph
+ ...
+ >>> builder = MessageGraph()
+ >>> builder.add_node("chatbot", lambda state: [("assistant", "Hello!")])
+ >>> builder.set_entry_point("chatbot")
+ >>> builder.set_finish_point("chatbot")
+ >>> builder.compile().invoke([("user", "Hi there.")])
+ [HumanMessage(content="Hi there.", id='...'), AIMessage(content="Hello!", id='...')]
+ ```
+
+ ```pycon
+ >>> from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
+ >>> from langgraph.graph.message import MessageGraph
+ ...
+ >>> builder = MessageGraph()
+ >>> builder.add_node(
+ ... "chatbot",
+ ... lambda state: [
+ ... AIMessage(
+ ... content="Hello!",
+ ... tool_calls=[{"name": "search", "id": "123", "args": {"query": "X"}}],
+ ... )
+ ... ],
+ ... )
+ >>> builder.add_node(
+ ... "search", lambda state: [ToolMessage(content="Searching...", tool_call_id="123")]
+ ... )
+ >>> builder.set_entry_point("chatbot")
+ >>> builder.add_edge("chatbot", "search")
+ >>> builder.set_finish_point("search")
+ >>> builder.compile().invoke([HumanMessage(content="Hi there. Can you search for X?")])
+ {'messages': [HumanMessage(content="Hi there. Can you search for X?", id='b8b7d8f4-7f4d-4f4d-9c1d-f8b8d8f4d9c1'),
+ AIMessage(content="Hello!", id='f4d9c1d8-8d8f-4d9c-b8b7-d8f4f4d9c1d8'),
+ ToolMessage(content="Searching...", id='d8f4f4d9-c1d8-4f4d-b8b7-d8f4f4d9c1d8', tool_call_id="123")]}
+ ```
+ """
+
+ def __init__(self) -> None:
+ warnings.warn(
+ "MessageGraph is deprecated in LangGraph v1.0.0, to be removed in v2.0.0. Please use StateGraph with a `messages` key instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ super().__init__(Annotated[list[AnyMessage], add_messages]) # type: ignore[arg-type]
+
+
+class MessagesState(TypedDict):
+ messages: Annotated[list[AnyMessage], add_messages]
+
+
+def _format_messages(messages: Sequence[BaseMessage]) -> list[BaseMessage]:
+ try:
+ from langchain_core.messages import convert_to_openai_messages
+ except ImportError:
+ msg = (
+ "Must have langchain-core>=0.3.11 installed to use automatic message "
+ "formatting (format='langchain-openai'). Please update your langchain-core "
+ "version or remove the 'format' flag. Returning un-formatted "
+ "messages."
+ )
+ warnings.warn(msg)
+ return list(messages)
+ else:
+ return convert_to_messages(convert_to_openai_messages(messages))
+
+
+def push_message(
+ message: MessageLikeRepresentation | BaseMessageChunk,
+ *,
+ state_key: str | None = "messages",
+) -> AnyMessage:
+ """Write a message manually to the `messages` / `messages-tuple` stream mode.
+
+ Will automatically write to the channel specified in the `state_key` unless `state_key` is `None`.
+ """
+
+ from langchain_core.callbacks.base import (
+ BaseCallbackHandler,
+ BaseCallbackManager,
+ )
+
+ from langgraph.config import get_config
+ from langgraph.pregel._messages import StreamMessagesHandler
+
+ config = get_config()
+ message = next(x for x in convert_to_messages([message]))
+
+ if message.id is None:
+ raise ValueError("Message ID is required")
+
+ if isinstance(config["callbacks"], BaseCallbackManager):
+ manager = config["callbacks"]
+ handlers = manager.handlers
+ elif isinstance(config["callbacks"], list) and all(
+ isinstance(x, BaseCallbackHandler) for x in config["callbacks"]
+ ):
+ handlers = config["callbacks"]
+
+ if stream_handler := next(
+ (x for x in handlers if isinstance(x, StreamMessagesHandler)), None
+ ):
+ metadata = config["metadata"]
+ message_meta = (
+ tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP)),
+ metadata,
+ )
+ stream_handler._emit(message_meta, message, dedupe=False)
+
+ if state_key:
+ config[CONF][CONFIG_KEY_SEND]([(state_key, message)])
+
+ return message
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/state.py b/python/user_packages/Python313/site-packages/langgraph/graph/state.py
new file mode 100644
index 0000000000000000000000000000000000000000..deb0e9e9406ad035a5140d959dd0c39aea444d46
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/state.py
@@ -0,0 +1,1964 @@
+from __future__ import annotations
+
+import inspect
+import logging
+import typing
+import warnings
+from collections import defaultdict
+from collections.abc import Awaitable, Callable, Hashable, Sequence
+from dataclasses import dataclass, is_dataclass
+from datetime import timedelta
+from functools import partial
+from inspect import isclass, isfunction, ismethod, signature
+from types import FunctionType
+from types import NoneType as NoneType
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ TypeVar,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+ overload,
+)
+
+from langchain_core.runnables import Runnable, RunnableConfig
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import Checkpoint
+from langgraph.store.base import BaseStore
+from pydantic import BaseModel, TypeAdapter
+from typing_extensions import NotRequired, Required, Self, Unpack, is_typeddict
+
+from langgraph._internal import _serde
+from langgraph._internal._constants import (
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ TASKS,
+)
+from langgraph._internal._fields import (
+ get_cached_annotated_keys,
+ get_field_default,
+ get_update_as_tuples,
+)
+from langgraph._internal._pydantic import create_model
+from langgraph._internal._runnable import coerce_to_runnable
+from langgraph._internal._timeout import coerce_timeout_policy
+from langgraph._internal._typing import EMPTY_SEQ, MISSING, DeprecatedKwargs
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.binop import BinaryOperatorAggregate
+from langgraph.channels.delta import DeltaChannel
+from langgraph.channels.ephemeral_value import EphemeralValue
+from langgraph.channels.last_value import LastValue, LastValueAfterFinish
+from langgraph.channels.named_barrier_value import (
+ NamedBarrierValue,
+ NamedBarrierValueAfterFinish,
+)
+from langgraph.constants import END, START, TAG_HIDDEN
+from langgraph.errors import (
+ ErrorCode,
+ InvalidUpdateError,
+ ParentCommand,
+ create_error_message,
+)
+from langgraph.graph._branch import BranchSpec
+from langgraph.graph._node import StateNode, StateNodeSpec
+from langgraph.managed.base import (
+ ManagedValueSpec,
+ is_managed_value,
+)
+from langgraph.pregel import Pregel
+from langgraph.pregel._read import ChannelRead, PregelNode
+from langgraph.pregel._write import (
+ ChannelWrite,
+ ChannelWriteEntry,
+ ChannelWriteTupleEntry,
+)
+from langgraph.types import (
+ All,
+ CachePolicy,
+ Checkpointer,
+ Command,
+ RetryPolicy,
+ Send,
+ TimeoutPolicy,
+ ensure_valid_checkpointer,
+)
+from langgraph.typing import ContextT, InputT, NodeInputT, OutputT, StateT
+from langgraph.warnings import LangGraphDeprecatedSinceV05, LangGraphDeprecatedSinceV10
+
+__all__ = ("StateGraph", "CompiledStateGraph")
+
+logger = logging.getLogger(__name__)
+
+_CHANNEL_BRANCH_TO = "branch:to:{}"
+_DEFAULT_ERROR_HANDLER_NODE = "__default_error_handler__"
+
+
+@dataclass(slots=True)
+class _NodeDefaults:
+ """Default node policies applied to every node at compile time."""
+
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None
+ cache_policy: CachePolicy | None = None
+ error_handler: StateNode[Any, Any] | None = None
+ timeout: TimeoutPolicy | None = None
+
+
+def _warn_invalid_state_schema(schema: type[Any] | Any) -> None:
+ if isinstance(schema, type):
+ return
+ if typing.get_args(schema):
+ return
+ warnings.warn(
+ f"Invalid state_schema: {schema}. Expected a type or Annotated[type, reducer]. "
+ "Please provide a valid schema to ensure correct updates.\n"
+ " See: https://langchain-ai.github.io/langgraph/reference/graphs/#stategraph"
+ )
+
+
+def _get_node_name(node: StateNode[Any, ContextT]) -> str:
+ try:
+ return getattr(node, "__name__", node.__class__.__name__)
+ except AttributeError:
+ raise TypeError(f"Unsupported node type: {type(node)}")
+
+
+class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):
+ """A graph whose nodes communicate by reading and writing to a shared state.
+
+ The signature of each node is `State -> Partial`.
+
+ Each state key can optionally be annotated with a reducer function that
+ will be used to aggregate the values of that key received from multiple nodes.
+ The signature of a reducer function is `(Value, Value) -> Value`.
+
+ !!! warning
+
+ `StateGraph` is a builder class and cannot be used directly for execution.
+ You must first call `.compile()` to create an executable graph that supports
+ methods like `invoke()`, `stream()`, `astream()`, and `ainvoke()`. See the
+ `CompiledStateGraph` documentation for more details.
+
+ Args:
+ state_schema: The schema class that defines the state.
+ context_schema: The schema class that defines the runtime context.
+
+ Use this to expose immutable context data to your nodes, like `user_id`, `db_conn`, etc.
+ input_schema: The schema class that defines the input to the graph.
+ output_schema: The schema class that defines the output from the graph.
+
+ !!! warning "`config_schema` Deprecated"
+ The `config_schema` parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
+ Please use `context_schema` instead to specify the schema for run-scoped context.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableConfig
+ from typing_extensions import Annotated, TypedDict
+ from langgraph.checkpoint.memory import InMemorySaver
+ from langgraph.graph import StateGraph
+ from langgraph.runtime import Runtime
+
+
+ def reducer(a: list, b: int | None) -> list:
+ if b is not None:
+ return a + [b]
+ return a
+
+
+ class State(TypedDict):
+ x: Annotated[list, reducer]
+
+
+ class Context(TypedDict):
+ r: float
+
+
+ graph = StateGraph(state_schema=State, context_schema=Context)
+
+
+ def node(state: State, runtime: Runtime[Context]) -> dict:
+ r = runtime.context.get("r", 1.0)
+ x = state["x"][-1]
+ next_value = x * r * (1 - x)
+ return {"x": next_value}
+
+
+ graph.add_node("A", node)
+ graph.set_entry_point("A")
+ graph.set_finish_point("A")
+ compiled = graph.compile()
+
+ step1 = compiled.invoke({"x": 0.5}, context={"r": 3.0})
+ # {'x': [0.5, 0.75]}
+ ```
+ """
+
+ edges: set[tuple[str, str]]
+ nodes: dict[str, StateNodeSpec[Any, ContextT]]
+ branches: defaultdict[str, dict[str, BranchSpec]]
+ channels: dict[str, BaseChannel]
+ managed: dict[str, ManagedValueSpec]
+ schemas: dict[type[Any], dict[str, BaseChannel | ManagedValueSpec]]
+ waiting_edges: set[tuple[tuple[str, ...], str]]
+
+ compiled: bool
+ state_schema: type[StateT]
+ context_schema: type[ContextT] | None
+ input_schema: type[InputT]
+ output_schema: type[OutputT]
+
+ def __init__(
+ self,
+ state_schema: type[StateT],
+ context_schema: type[ContextT] | None = None,
+ *,
+ input_schema: type[InputT] | None = None,
+ output_schema: type[OutputT] | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> None:
+ if (config_schema := kwargs.get("config_schema", MISSING)) is not MISSING:
+ warnings.warn(
+ "`config_schema` is deprecated and will be removed. Please use `context_schema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if context_schema is None:
+ context_schema = cast(type[ContextT], config_schema)
+
+ if (input_ := kwargs.get("input", MISSING)) is not MISSING:
+ warnings.warn(
+ "`input` is deprecated and will be removed. Please use `input_schema` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ stacklevel=2,
+ )
+ if input_schema is None:
+ input_schema = cast(type[InputT], input_)
+
+ if (output := kwargs.get("output", MISSING)) is not MISSING:
+ warnings.warn(
+ "`output` is deprecated and will be removed. Please use `output_schema` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ stacklevel=2,
+ )
+ if output_schema is None:
+ output_schema = cast(type[OutputT], output)
+
+ self.nodes = {}
+ self.edges = set()
+ self.branches = defaultdict(dict)
+ self.schemas = {}
+ self.channels = {}
+ self.managed = {}
+ self.compiled = False
+ self.waiting_edges = set()
+
+ self.state_schema = state_schema
+ self.input_schema = cast(type[InputT], input_schema or state_schema)
+ self.output_schema = cast(type[OutputT], output_schema or state_schema)
+ self.context_schema = context_schema
+
+ self._node_defaults: _NodeDefaults = _NodeDefaults()
+
+ self._add_schema(self.state_schema)
+ self._add_schema(self.input_schema, allow_managed=False)
+ self._add_schema(self.output_schema, allow_managed=False)
+
+ def set_node_defaults(
+ self,
+ *,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ ) -> Self:
+ """Set default node policies that apply to every node in this graph.
+
+ Per-node values passed to `add_node` always take precedence over these
+ defaults. Defaults are applied at `compile()` time. Policies set here
+ are **not** inherited by subgraphs.
+
+ `retry_policy` and `timeout` defaults apply to **all** nodes,
+ including error-handler nodes. `cache_policy` and `error_handler`
+ defaults only apply to regular nodes -- caching error-handler results
+ is unsafe, and handlers must never catch themselves.
+
+ Args:
+ retry_policy: Default retry policy for nodes that don't specify
+ their own via `add_node(..., retry_policy=...)`. Also applies
+ to error-handler nodes.
+ cache_policy: Default cache policy for nodes that don't specify
+ their own via `add_node(..., cache_policy=...)`. Does **not**
+ apply to error-handler nodes.
+ error_handler: Default error handler invoked when any regular node
+ raises and does not have its own `error_handler` set via
+ `add_node`. The handler is **not** invoked when an
+ error-handler node itself raises -- handler failures fail the
+ run.
+ timeout: Default timeout policy for nodes that don't specify their
+ own via `add_node(..., timeout=...)`. Also applies to
+ error-handler nodes. Accepts a `TimeoutPolicy`, a number of
+ seconds (`float`), or a `timedelta`.
+
+ Returns:
+ Self: The builder instance, for chaining.
+
+ Example:
+ ```python
+ graph = (
+ StateGraph(State)
+ .set_node_defaults(
+ retry_policy=RetryPolicy(max_attempts=3),
+ error_handler=my_fallback_handler,
+ )
+ .add_node("a", node_a)
+ .add_node("b", node_b, retry_policy=custom_retry) # overrides default
+ .add_edge(START, "a")
+ .compile()
+ )
+ ```
+ """
+ defaults = self._node_defaults
+ if retry_policy is not None:
+ defaults.retry_policy = retry_policy
+ if cache_policy is not None:
+ defaults.cache_policy = cache_policy
+ if error_handler is not None:
+ defaults.error_handler = error_handler
+ if timeout is not None:
+ defaults.timeout = coerce_timeout_policy(timeout)
+ return self
+
+ @property
+ def _all_edges(self) -> set[tuple[str, str]]:
+ return self.edges | {
+ (start, end) for starts, end in self.waiting_edges for start in starts
+ }
+
+ def _add_schema(self, schema: type[Any], /, allow_managed: bool = True) -> None:
+ if schema not in self.schemas:
+ _warn_invalid_state_schema(schema)
+ channels, managed, type_hints = _get_channels(schema)
+ if managed and not allow_managed:
+ names = ", ".join(managed)
+ schema_name = getattr(schema, "__name__", "")
+ raise ValueError(
+ f"Invalid managed channels detected in {schema_name}: {names}."
+ " Managed channels are not permitted in Input/Output schema."
+ )
+ self.schemas[schema] = {**channels, **managed}
+ for key, channel in channels.items():
+ if key in self.channels:
+ if self.channels[key] != channel:
+ if isinstance(channel, LastValue):
+ pass
+ else:
+ raise ValueError(
+ f"Channel '{key}' already exists with a different type"
+ )
+ else:
+ self.channels[key] = channel
+ for key, managed in managed.items():
+ if key in self.managed:
+ if self.managed[key] != managed:
+ raise ValueError(
+ f"Managed value '{key}' already exists with a different type"
+ )
+ else:
+ self.managed[key] = managed
+
+ @overload
+ def add_node(
+ self,
+ node: StateNode[NodeInputT, ContextT],
+ *,
+ defer: bool = False,
+ metadata: dict[str, Any] | None = None,
+ input_schema: None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ destinations: dict[str, str] | tuple[str, ...] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Self:
+ """Add a new node to the `StateGraph`, input schema is inferred as the state schema.
+
+ Will take the name of the function/runnable as the node name.
+
+ Args:
+ node: The function or runnable this node will run.
+ defer: Whether to defer the execution of the node until the run is about to end.
+ metadata: The metadata associated with the node.
+ input_schema: The input schema for the node. (Default: the graph's state schema)
+ retry_policy: The retry policy for the node.
+
+ If a sequence is provided, the first matching policy will be applied.
+ cache_policy: The cache policy for the node.
+ destinations: Destinations that indicate where a node can route to.
+
+ Useful for edgeless graphs with nodes that return `Command` objects.
+
+ If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.
+
+ If a `tuple` is provided, the values will be used as the target node names.
+
+ !!! warning
+
+ This is only used for graph rendering and doesn't have any effect on the graph execution.
+
+ Example:
+ ```python
+ from typing_extensions import TypedDict
+
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.graph import START, StateGraph
+
+
+ class State(TypedDict):
+ x: int
+
+
+ def my_node(state: State, config: RunnableConfig) -> State:
+ return {"x": state["x"] + 1}
+
+
+ builder = StateGraph(State)
+ builder.add_node(my_node) # node name will be 'my_node'
+ builder.add_edge(START, "my_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ ...
+
+ @overload
+ def add_node(
+ self,
+ node: StateNode[NodeInputT, ContextT],
+ *,
+ defer: bool = False,
+ metadata: dict[str, Any] | None = None,
+ input_schema: type[NodeInputT],
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ destinations: dict[str, str] | tuple[str, ...] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Self:
+ """Add a new node to the `StateGraph` where input schema is specified.
+
+ Will take the name of the function/runnable as the node name.
+
+ Args:
+ node: The function or runnable this node will run.
+ defer: Whether to defer the execution of the node until the run is about to end.
+ metadata: The metadata associated with the node.
+ input_schema: The input schema for the node.
+ retry_policy: The retry policy for the node.
+
+ If a sequence is provided, the first matching policy will be applied.
+ cache_policy: The cache policy for the node.
+ destinations: Destinations that indicate where a node can route to.
+
+ Useful for edgeless graphs with nodes that return `Command` objects.
+
+ If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.
+
+ If a `tuple` is provided, the values will be used as the target node names.
+
+ !!! warning
+
+ This is only used for graph rendering and doesn't have any effect on the graph execution.
+
+ Example:
+ ```python
+ from typing_extensions import TypedDict
+
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.graph import START, StateGraph
+
+
+ class State(TypedDict):
+ x: int
+
+
+ class NodeInput(TypedDict):
+ x: int
+
+
+ def my_node(state: NodeInput, config: RunnableConfig) -> State:
+ return {"x": state["x"] + 1}
+
+
+ builder = StateGraph(State)
+ builder.add_node(my_node, input_schema=NodeInput) # node name will be 'my_node'
+ builder.add_edge(START, "my_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ ...
+
+ @overload
+ def add_node(
+ self,
+ node: str,
+ action: StateNode[NodeInputT, ContextT],
+ *,
+ defer: bool = False,
+ metadata: dict[str, Any] | None = None,
+ input_schema: None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ destinations: dict[str, str] | tuple[str, ...] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Self:
+ """Add a new node to the `StateGraph`, input schema is inferred as the state schema.
+
+ Args:
+ node: The name of the node.
+ action: The function or runnable this node will run.
+ defer: Whether to defer the execution of the node until the run is about to end.
+ metadata: The metadata associated with the node.
+ input_schema: The input schema for the node. (Default: the graph's state schema)
+ retry_policy: The retry policy for the node.
+
+ If a sequence is provided, the first matching policy will be applied.
+ cache_policy: The cache policy for the node.
+ destinations: Destinations that indicate where a node can route to.
+
+ Useful for edgeless graphs with nodes that return `Command` objects.
+
+ If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.
+
+ If a `tuple` is provided, the values will be used as the target node names.
+
+ !!! warning
+
+ This is only used for graph rendering and doesn't have any effect on the graph execution.
+
+ Example:
+ ```python
+ from typing_extensions import TypedDict
+
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.graph import START, StateGraph
+
+
+ class State(TypedDict):
+ x: int
+
+
+ def my_node(state: State, config: RunnableConfig) -> State:
+ return {"x": state["x"] + 1}
+
+
+ builder = StateGraph(State)
+ builder.add_node("my_fair_node", my_node)
+ builder.add_edge(START, "my_fair_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ ...
+
+ @overload
+ def add_node(
+ self,
+ node: str | StateNode[NodeInputT, ContextT],
+ action: StateNode[NodeInputT, ContextT] | None = None,
+ *,
+ defer: bool = False,
+ metadata: dict[str, Any] | None = None,
+ input_schema: type[NodeInputT],
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ destinations: dict[str, str] | tuple[str, ...] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Self:
+ """Add a new node to the `StateGraph`, input schema is specified.
+
+ Args:
+ node: The function or runnable this node will run.
+
+ If a string is provided, it will be used as the node name, and action will be used as the function or runnable.
+ action: The action associated with the node.
+
+ Will be used as the node function or runnable if `node` is a string (node name).
+ defer: Whether to defer the execution of the node until the run is about to end.
+ metadata: The metadata associated with the node.
+ input_schema: The input schema for the node.
+ retry_policy: The retry policy for the node.
+
+ If a sequence is provided, the first matching policy will be applied.
+ cache_policy: The cache policy for the node.
+ destinations: Destinations that indicate where a node can route to.
+
+ Useful for edgeless graphs with nodes that return `Command` objects.
+
+ If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.
+
+ If a `tuple` is provided, the values will be used as the target node names.
+
+ !!! warning
+
+ This is only used for graph rendering and doesn't have any effect on the graph execution.
+
+ Example:
+ ```python
+ from typing_extensions import TypedDict
+
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.graph import START, StateGraph
+
+
+ class State(TypedDict):
+ x: int
+
+
+ class NodeInput(TypedDict):
+ x: int
+
+
+ def my_node(state: NodeInput, config: RunnableConfig) -> State:
+ return {"x": state["x"] + 1}
+
+
+ builder = StateGraph(State)
+ builder.add_node("my_fair_node", my_node, input_schema=NodeInput)
+ builder.add_edge(START, "my_fair_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ ...
+
+ def add_node(
+ self,
+ node: str | StateNode[NodeInputT, ContextT],
+ action: StateNode[NodeInputT, ContextT] | None = None,
+ *,
+ defer: bool = False,
+ metadata: dict[str, Any] | None = None,
+ input_schema: type[NodeInputT] | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ error_handler: StateNode[Any, ContextT] | None = None,
+ destinations: dict[str, str] | tuple[str, ...] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Self:
+ """Add a new node to the `StateGraph`.
+
+ Args:
+ node: The function or runnable this node will run.
+
+ If a string is provided, it will be used as the node name, and action will be used as the function or runnable.
+ action: The action associated with the node.
+
+ Will be used as the node function or runnable if `node` is a string (node name).
+ defer: Whether to defer the execution of the node until the run is about to end.
+ metadata: The metadata associated with the node.
+ input_schema: The input schema for the node. (Default: the graph's state schema)
+ retry_policy: The retry policy for the node.
+
+ If a sequence is provided, the first matching policy will be applied.
+ cache_policy: The cache policy for the node.
+ error_handler: Optional node-level error handler callable for this node.
+ destinations: Destinations that indicate where a node can route to.
+
+ Useful for edgeless graphs with nodes that return `Command` objects.
+
+ If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.
+
+ If a `tuple` is provided, the values will be used as the target node names.
+
+ !!! warning
+
+ This is only used for graph rendering and doesn't have any effect on the graph execution.
+ timeout: Timeout for each node attempt. A number or `timedelta` is
+ a hard wall-clock cap and is not refreshed. Use `TimeoutPolicy`
+ to configure both a wall-clock `run_timeout` and an
+ `idle_timeout` refreshed by progress signals. When exceeded, a
+ [`NodeTimeoutError`][langgraph.errors.NodeTimeoutError] is raised
+ and the retry policy (if any) decides whether to retry. Timeouts
+ are supported only for async nodes; sync nodes cannot be safely
+ cancelled in-process.
+
+ Example:
+ ```python
+ from typing_extensions import TypedDict
+
+ from langchain_core.runnables import RunnableConfig
+ from langgraph.graph import START, StateGraph
+
+
+ class State(TypedDict):
+ x: int
+
+
+ def my_node(state: State, config: RunnableConfig) -> State:
+ return {"x": state["x"] + 1}
+
+
+ builder = StateGraph(State)
+ builder.add_node(my_node) # node name will be 'my_node'
+ builder.add_edge(START, "my_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Example: Customize the name:
+ ```python
+ builder = StateGraph(State)
+ builder.add_node("my_fair_node", my_node)
+ builder.add_edge(START, "my_fair_node")
+ graph = builder.compile()
+ graph.invoke({"x": 1})
+ # {'x': 2}
+ ```
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ if (retry := kwargs.get("retry", MISSING)) is not MISSING:
+ warnings.warn(
+ "`retry` is deprecated and will be removed. Please use `retry_policy` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ )
+ if retry_policy is None:
+ retry_policy = retry # type: ignore[assignment]
+
+ if (input_ := kwargs.get("input", MISSING)) is not MISSING:
+ warnings.warn(
+ "`input` is deprecated and will be removed. Please use `input_schema` instead.",
+ category=LangGraphDeprecatedSinceV05,
+ )
+ if input_schema is None:
+ input_schema = cast(type[NodeInputT] | None, input_)
+ timeout = coerce_timeout_policy(timeout)
+
+ if not isinstance(node, str):
+ action = node
+ if isinstance(action, Runnable):
+ node = action.get_name()
+ else:
+ node = getattr(action, "__name__", action.__class__.__name__)
+ if node is None:
+ raise ValueError(
+ "Node name must be provided if action is not a function"
+ )
+ if self.compiled:
+ logger.warning(
+ "Adding a node to a graph that has already been compiled. This will "
+ "not be reflected in the compiled graph."
+ )
+ if not isinstance(node, str):
+ action = node
+ node = cast(str, getattr(action, "name", getattr(action, "__name__", None)))
+ if node is None:
+ raise ValueError(
+ "Node name must be provided if action is not a function"
+ )
+ if action is None:
+ raise RuntimeError
+ if node in self.nodes:
+ raise ValueError(f"Node `{node}` already present.")
+ if node == END or node == START:
+ raise ValueError(f"Node `{node}` is reserved.")
+
+ for character in (NS_SEP, NS_END):
+ if character in node:
+ raise ValueError(
+ f"'{character}' is a reserved character and is not allowed in the node names."
+ )
+
+ inferred_input_schema = None
+
+ ends: tuple[str, ...] | dict[str, str] = EMPTY_SEQ
+ try:
+ if (
+ isfunction(action)
+ or ismethod(action)
+ or ismethod(getattr(action, "__call__", None))
+ ) and (
+ hints := get_type_hints(getattr(action, "__call__"))
+ or get_type_hints(action)
+ ):
+ if input_schema is None:
+ first_parameter_name = next(
+ iter(
+ inspect.signature(
+ cast(FunctionType, action)
+ ).parameters.keys()
+ )
+ )
+ if input_hint := hints.get(first_parameter_name):
+ if isinstance(input_hint, type) and get_type_hints(input_hint):
+ inferred_input_schema = input_hint
+ if rtn := hints.get("return"):
+ # Handle Union types
+ rtn_origin = get_origin(rtn)
+ if rtn_origin is Union:
+ rtn_args = get_args(rtn)
+ # Look for Command in the union
+ for arg in rtn_args:
+ arg_origin = get_origin(arg)
+ if arg_origin is Command:
+ rtn = arg
+ rtn_origin = arg_origin
+ break
+
+ # Check if it's a Command type
+ if (
+ rtn_origin is Command
+ and (rargs := get_args(rtn))
+ and get_origin(rargs[0]) is Literal
+ and (vals := get_args(rargs[0]))
+ ):
+ ends = vals
+ except (NameError, TypeError, StopIteration):
+ pass
+
+ if destinations is not None:
+ ends = destinations
+
+ resolved_input_schema: type[Any] = (
+ input_schema or inferred_input_schema or self.state_schema
+ )
+ handler_node_name: str | None = None
+ if error_handler is not None:
+ handler_node_name = f"__error_handler__{node}"
+ if handler_node_name in self.nodes:
+ raise ValueError(
+ f"Auto-generated error handler node `{handler_node_name}` already exists."
+ )
+ self.nodes[handler_node_name] = StateNodeSpec[Any, ContextT](
+ coerce_to_runnable(error_handler, name=handler_node_name, trace=False), # type: ignore[arg-type]
+ metadata=None,
+ input_schema=resolved_input_schema,
+ retry_policy=None,
+ cache_policy=None,
+ is_error_handler=True,
+ )
+
+ if input_schema is not None:
+ self.nodes[node] = StateNodeSpec[NodeInputT, ContextT](
+ coerce_to_runnable(action, name=node, trace=False), # type: ignore[arg-type]
+ metadata,
+ input_schema=input_schema,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ error_handler_node=handler_node_name,
+ ends=ends,
+ defer=defer,
+ timeout=timeout,
+ )
+ elif inferred_input_schema is not None:
+ self.nodes[node] = StateNodeSpec(
+ coerce_to_runnable(action, name=node, trace=False), # type: ignore[arg-type]
+ metadata,
+ input_schema=inferred_input_schema,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ error_handler_node=handler_node_name,
+ ends=ends,
+ defer=defer,
+ timeout=timeout,
+ )
+ else:
+ self.nodes[node] = StateNodeSpec[StateT, ContextT](
+ coerce_to_runnable(action, name=node, trace=False), # type: ignore[arg-type]
+ metadata,
+ input_schema=self.state_schema,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ error_handler_node=handler_node_name,
+ ends=ends,
+ defer=defer,
+ timeout=timeout,
+ )
+
+ input_schema = input_schema or inferred_input_schema
+ if input_schema is not None:
+ self._add_schema(input_schema)
+
+ return self
+
+ def add_edge(self, start_key: str | list[str], end_key: str) -> Self:
+ """Add a directed edge from the start node (or list of start nodes) to the end node.
+
+ When a single start node is provided, the graph will wait for that node to complete
+ before executing the end node. When multiple start nodes are provided,
+ the graph will wait for ALL of the start nodes to complete before executing the end node.
+
+ Args:
+ start_key: The key(s) of the start node(s) of the edge.
+ end_key: The key of the end node of the edge.
+
+ Raises:
+ ValueError: If the start key is `'END'` or if the start key or end key is not present in the graph.
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ if self.compiled:
+ logger.warning(
+ "Adding an edge to a graph that has already been compiled. This will "
+ "not be reflected in the compiled graph."
+ )
+
+ if isinstance(start_key, str):
+ if start_key == END:
+ raise ValueError("END cannot be a start node")
+ if end_key == START:
+ raise ValueError("START cannot be an end node")
+
+ # run this validation only for non-StateGraph graphs
+ if not hasattr(self, "channels") and start_key in set(
+ start for start, _ in self.edges
+ ):
+ raise ValueError(
+ f"Already found path for node '{start_key}'.\n"
+ "For multiple edges, use StateGraph with an Annotated state key."
+ )
+
+ self.edges.add((start_key, end_key))
+ return self
+
+ for start in start_key:
+ if start == END:
+ raise ValueError("END cannot be a start node")
+ if start not in self.nodes:
+ raise ValueError(f"Need to add_node `{start}` first")
+ if end_key == START:
+ raise ValueError("START cannot be an end node")
+ if end_key != END and end_key not in self.nodes:
+ raise ValueError(f"Need to add_node `{end_key}` first")
+
+ self.waiting_edges.add((tuple(start_key), end_key))
+ return self
+
+ def add_conditional_edges(
+ self,
+ source: str,
+ path: Callable[..., Hashable | Sequence[Hashable]]
+ | Callable[..., Awaitable[Hashable | Sequence[Hashable]]]
+ | Runnable[Any, Hashable | Sequence[Hashable]],
+ path_map: dict[Hashable, str] | list[str] | None = None,
+ ) -> Self:
+ """Add a conditional edge from the starting node to any number of destination nodes.
+
+ Args:
+ source: The starting node. This conditional edge will run when
+ exiting this node.
+ path: The callable that determines the next node or nodes.
+
+ If not specifying `path_map` it should return one or more nodes.
+
+ If it returns `'END'`, the graph will stop execution.
+ path_map: Optional mapping of paths to node names.
+
+ If omitted the paths returned by `path` should be node names.
+
+ Returns:
+ Self: The instance of the graph, allowing for method chaining.
+
+ !!! warning
+ Without type hints on the `path` function's return value (e.g., `-> Literal["foo", "__end__"]:`)
+ or a path_map, the graph visualization assumes the edge could transition to any node in the graph.
+
+ """ # noqa: E501
+ if self.compiled:
+ logger.warning(
+ "Adding an edge to a graph that has already been compiled. This will "
+ "not be reflected in the compiled graph."
+ )
+
+ # find a name for the condition
+ path = coerce_to_runnable(path, name=None, trace=True)
+ name = path.name or "condition"
+ # validate the condition
+ if name in self.branches[source]:
+ raise ValueError(
+ f"Branch with name `{path.name}` already exists for node `{source}`"
+ )
+ # save it
+ self.branches[source][name] = BranchSpec.from_path(path, path_map, True)
+ if schema := self.branches[source][name].input_schema:
+ self._add_schema(schema)
+ return self
+
+ def add_sequence(
+ self,
+ nodes: Sequence[
+ StateNode[NodeInputT, ContextT]
+ | tuple[str, StateNode[NodeInputT, ContextT]]
+ ],
+ ) -> Self:
+ """Add a sequence of nodes that will be executed in the provided order.
+
+ Args:
+ nodes: A sequence of `StateNode` (callables that accept a `state` arg) or `(name, StateNode)` tuples.
+
+ If no names are provided, the name will be inferred from the node object (e.g. a `Runnable` or a `Callable` name).
+
+ Each node will be executed in the order provided.
+
+ Raises:
+ ValueError: If the sequence is empty.
+ ValueError: If the sequence contains duplicate node names.
+
+ Returns:
+ Self: The instance of the `StateGraph`, allowing for method chaining.
+ """
+ if len(nodes) < 1:
+ raise ValueError("Sequence requires at least one node.")
+
+ previous_name: str | None = None
+ for node in nodes:
+ if isinstance(node, tuple) and len(node) == 2:
+ name, node = node
+ else:
+ name = _get_node_name(node)
+
+ if name in self.nodes:
+ raise ValueError(
+ f"Node names must be unique: node with the name '{name}' already exists. "
+ "If you need to use two different runnables/callables with the same name (for example, using `lambda`), please provide them as tuples (name, runnable/callable)."
+ )
+
+ self.add_node(name, node)
+ if previous_name is not None:
+ self.add_edge(previous_name, name)
+
+ previous_name = name
+
+ return self
+
+ def set_entry_point(self, key: str) -> Self:
+ """Specifies the first node to be called in the graph.
+
+ Equivalent to calling `add_edge(START, key)`.
+
+ Parameters:
+ key (str): The key of the node to set as the entry point.
+
+ Returns:
+ Self: The instance of the graph, allowing for method chaining.
+ """
+ return self.add_edge(START, key)
+
+ def set_conditional_entry_point(
+ self,
+ path: Callable[..., Hashable | Sequence[Hashable]]
+ | Callable[..., Awaitable[Hashable | Sequence[Hashable]]]
+ | Runnable[Any, Hashable | Sequence[Hashable]],
+ path_map: dict[Hashable, str] | list[str] | None = None,
+ ) -> Self:
+ """Sets a conditional entry point in the graph.
+
+ Args:
+ path: The callable that determines the next node or nodes.
+
+ If not specifying `path_map` it should return one or more nodes.
+
+ If it returns END, the graph will stop execution.
+ path_map: Optional mapping of paths to node names.
+
+ If omitted the paths returned by `path` should be node names.
+
+ Returns:
+ Self: The instance of the graph, allowing for method chaining.
+ """
+ return self.add_conditional_edges(START, path, path_map)
+
+ def set_finish_point(self, key: str) -> Self:
+ """Marks a node as a finish point of the graph.
+
+ If the graph reaches this node, it will cease execution.
+
+ Parameters:
+ key (str): The key of the node to set as the finish point.
+
+ Returns:
+ Self: The instance of the graph, allowing for method chaining.
+ """
+ return self.add_edge(key, END)
+
+ def validate(self, interrupt: Sequence[str] | None = None) -> Self:
+ # assemble sources
+ all_sources = {src for src, _ in self._all_edges}
+ for start, branches in self.branches.items():
+ all_sources.add(start)
+ for name, spec in self.nodes.items():
+ if spec.ends:
+ all_sources.add(name)
+ # validate sources
+ for source in all_sources:
+ if source not in self.nodes and source != START:
+ raise ValueError(f"Found edge starting at unknown node '{source}'")
+
+ if START not in all_sources:
+ raise ValueError(
+ "Graph must have an entrypoint: add at least one edge from START to another node"
+ )
+
+ # assemble targets
+ all_targets = {end for _, end in self._all_edges}
+ for start, branches in self.branches.items():
+ for cond, branch in branches.items():
+ if branch.ends is not None:
+ for end in branch.ends.values():
+ if end not in self.nodes and end != END:
+ raise ValueError(
+ f"At '{start}' node, '{cond}' branch found unknown target '{end}'"
+ )
+ all_targets.add(end)
+ else:
+ all_targets.add(END)
+ for node in self.nodes:
+ if node != start:
+ all_targets.add(node)
+ for name, spec in self.nodes.items():
+ if spec.ends:
+ all_targets.update(spec.ends)
+ for target in all_targets:
+ if target not in self.nodes and target != END:
+ raise ValueError(f"Found edge ending at unknown node `{target}`")
+ # validate interrupts
+ if interrupt:
+ for node in interrupt:
+ if node not in self.nodes:
+ raise ValueError(f"Interrupt node `{node}` not found")
+ self.compiled = True
+ return self
+
+ def compile(
+ self,
+ checkpointer: Checkpointer = None,
+ *,
+ cache: BaseCache | None = None,
+ store: BaseStore | None = None,
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ debug: bool = False,
+ name: str | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ ) -> CompiledStateGraph[StateT, ContextT, InputT, OutputT]:
+ """Compiles the `StateGraph` into a `CompiledStateGraph` object.
+
+ The compiled graph implements the `Runnable` interface and can be invoked,
+ streamed, batched, and run asynchronously.
+
+ Args:
+ checkpointer: A checkpoint saver object or flag.
+
+ If provided, this `Checkpointer` serves as a fully versioned "short-term memory" for the graph,
+ allowing it to be paused, resumed, and replayed from any point.
+
+ If `None`, it may inherit the parent graph's checkpointer when used as a subgraph.
+
+ If `False`, it will not use or inherit any checkpointer.
+
+ **Important**: When a checkpointer is enabled, you should pass a `thread_id`
+ in the config when invoking the graph:
+
+ ```python
+ config = {"configurable": {"thread_id": "my-thread"}}
+ graph.invoke(inputs, config)
+ ```
+
+ The `thread_id` is the key used to store and retrieve checkpoints. Use a
+ unique ID for independent runs, or reuse the same ID to accumulate state
+ across invocations (e.g., for conversation memory).
+
+ interrupt_before: An optional list of node names to interrupt before.
+ interrupt_after: An optional list of node names to interrupt after.
+ debug: A flag indicating whether to enable debug mode.
+ name: The name to use for the compiled graph.
+ transformers: Optional sequence of `StreamTransformer` classes or
+ configured factories. Classes and factories are instantiated
+ per run whenever `stream_events(version="v3")` / `astream_events(version="v3")` is called and are
+ propagated to subgraph scopes. Custom factories should follow
+ the standard `StreamTransformer` constructor shape by
+ accepting `scope` as their first argument. Appended after the
+ built-in stream transformers.
+
+ Returns:
+ CompiledStateGraph: The compiled `StateGraph`.
+ """
+ checkpointer = ensure_valid_checkpointer(checkpointer)
+
+ serde_allowlist: set[tuple[str, ...]] | None = None
+ if _serde.STRICT_MSGPACK_ENABLED:
+ schema_types: list[type[Any]] = [
+ self.state_schema,
+ self.input_schema,
+ self.output_schema,
+ ]
+ if self.context_schema is not None:
+ schema_types.append(self.context_schema)
+ for node in self.nodes.values():
+ schema_types.append(node.input_schema)
+ for branches in self.branches.values():
+ for branch in branches.values():
+ if branch.input_schema is not None:
+ schema_types.append(branch.input_schema)
+ serde_allowlist = _serde.build_serde_allowlist(
+ schemas=schema_types,
+ channels=self.channels,
+ )
+ checkpointer = _serde.apply_checkpointer_allowlist(
+ checkpointer, serde_allowlist
+ )
+
+ # assign default values
+ interrupt_before = interrupt_before or []
+ interrupt_after = interrupt_after or []
+
+ # validate the graph
+ self.validate(
+ interrupt=(
+ (interrupt_before if interrupt_before != "*" else []) + interrupt_after
+ if interrupt_after != "*"
+ else []
+ )
+ )
+
+ # prepare output channels
+ output_channels = (
+ "__root__"
+ if len(self.schemas[self.output_schema]) == 1
+ and "__root__" in self.schemas[self.output_schema]
+ else [
+ key
+ for key, val in self.schemas[self.output_schema].items()
+ if not is_managed_value(val)
+ ]
+ )
+ stream_channels = (
+ "__root__"
+ if len(self.channels) == 1 and "__root__" in self.channels
+ else [
+ key for key, val in self.channels.items() if not is_managed_value(val)
+ ]
+ )
+ # Apply builder defaults to node specs. Per-node values always win.
+ # Error-handler routing and cache_policy are only assigned to regular
+ # nodes. Retry and timeout defaults also apply to error-handler nodes.
+ defaults = self._node_defaults
+ default_handler_name: str | None = None
+ if defaults.error_handler is not None:
+ if _DEFAULT_ERROR_HANDLER_NODE in self.nodes:
+ raise ValueError(
+ f"Auto-generated default error handler node "
+ f"`{_DEFAULT_ERROR_HANDLER_NODE}` already exists."
+ )
+ default_handler_name = _DEFAULT_ERROR_HANDLER_NODE
+ self.nodes[default_handler_name] = StateNodeSpec[Any, ContextT](
+ coerce_to_runnable(
+ defaults.error_handler, # type: ignore[arg-type]
+ name=default_handler_name,
+ trace=False,
+ ),
+ metadata=None,
+ input_schema=self.state_schema,
+ retry_policy=None,
+ cache_policy=None,
+ is_error_handler=True,
+ )
+
+ # Apply builder defaults to node specs. Per-node values always win.
+ for spec in self.nodes.values():
+ # error_handler: regular nodes only — handlers must never
+ # catch themselves or other handlers.
+ if (
+ not spec.is_error_handler
+ and default_handler_name is not None
+ and spec.error_handler_node is None
+ ):
+ spec.error_handler_node = default_handler_name
+ # retry: all nodes — handlers should be retried on transient
+ # failures just like regular nodes.
+ if defaults.retry_policy is not None and spec.retry_policy is None:
+ spec.retry_policy = defaults.retry_policy
+ # cache: regular nodes only — caching an error-handler result
+ # is unsafe because the input (failed-node state) may differ
+ # across failures even when the cache key matches.
+ if (
+ not spec.is_error_handler
+ and defaults.cache_policy is not None
+ and spec.cache_policy is None
+ ):
+ spec.cache_policy = defaults.cache_policy
+ # timeout: all nodes — a stuck handler should be cancelled the
+ # same way a stuck regular node would be.
+ if defaults.timeout is not None and spec.timeout is None:
+ spec.timeout = defaults.timeout
+
+ node_error_handler_map = {
+ node_name: spec.error_handler_node
+ for node_name, spec in self.nodes.items()
+ if not spec.is_error_handler and spec.error_handler_node is not None
+ }
+
+ compiled = CompiledStateGraph[StateT, ContextT, InputT, OutputT](
+ builder=self,
+ schema_to_mapper={},
+ context_schema=self.context_schema,
+ nodes={},
+ channels={
+ **self.channels,
+ **self.managed,
+ START: EphemeralValue(self.input_schema),
+ },
+ input_channels=START,
+ stream_mode="updates",
+ output_channels=output_channels,
+ stream_channels=stream_channels,
+ checkpointer=checkpointer,
+ interrupt_before_nodes=interrupt_before,
+ interrupt_after_nodes=interrupt_after,
+ auto_validate=False,
+ debug=debug,
+ store=store,
+ cache=cache,
+ node_error_handler_map=node_error_handler_map,
+ name=name or "LangGraph",
+ stream_transformers=transformers,
+ )
+ compiled._serde_allowlist = serde_allowlist
+
+ compiled.attach_node(START, None)
+ for key, node in self.nodes.items():
+ compiled.attach_node(key, node)
+
+ # Record output/state mappers for v2 stream coercion (pydantic/dataclass only)
+ compiled._output_mapper = _pick_mapper(
+ list(output_channels)
+ if isinstance(output_channels, list)
+ else [output_channels],
+ self.output_schema,
+ )
+ compiled._state_mapper = _pick_mapper(
+ list(stream_channels)
+ if isinstance(stream_channels, list)
+ else [stream_channels],
+ self.state_schema,
+ )
+
+ for start, end in self.edges:
+ compiled.attach_edge(start, end)
+
+ for starts, end in self.waiting_edges:
+ compiled.attach_edge(starts, end)
+
+ for start, branches in self.branches.items():
+ for name, branch in branches.items():
+ compiled.attach_branch(start, name, branch)
+
+ return compiled.validate()
+
+
+class CompiledStateGraph(
+ Pregel[StateT, ContextT, InputT, OutputT],
+ Generic[StateT, ContextT, InputT, OutputT],
+):
+ builder: StateGraph[StateT, ContextT, InputT, OutputT]
+ schema_to_mapper: dict[type[Any], Callable[[Any], Any] | None]
+ _output_mapper: Callable[[Any], Any] | None
+ _state_mapper: Callable[[Any], Any] | None
+
+ def __init__(
+ self,
+ *,
+ builder: StateGraph[StateT, ContextT, InputT, OutputT],
+ schema_to_mapper: dict[type[Any], Callable[[Any], Any] | None],
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.builder = builder
+ self.schema_to_mapper = schema_to_mapper
+
+ def get_input_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ return _get_json_schema(
+ typ=self.builder.input_schema,
+ schemas=self.builder.schemas,
+ channels=self.builder.channels,
+ name=self.get_name("Input"),
+ )
+
+ def get_output_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ return _get_json_schema(
+ typ=self.builder.output_schema,
+ schemas=self.builder.schemas,
+ channels=self.builder.channels,
+ name=self.get_name("Output"),
+ )
+
+ def attach_node(self, key: str, node: StateNodeSpec[Any, ContextT] | None) -> None:
+ if key == START:
+ output_keys = [
+ k
+ for k, v in self.builder.schemas[self.builder.input_schema].items()
+ if not is_managed_value(v)
+ ]
+ else:
+ output_keys = list(self.builder.channels) + [
+ k for k, v in self.builder.managed.items()
+ ]
+
+ def _get_updates(
+ input: None | dict | Any,
+ ) -> Sequence[tuple[str, Any]] | None:
+ if input is None:
+ return None
+ elif isinstance(input, dict):
+ return [(k, v) for k, v in input.items() if k in output_keys]
+ elif isinstance(input, Command):
+ if input.graph == Command.PARENT:
+ return None
+ return [
+ (k, v) for k, v in input._update_as_tuples() if k in output_keys
+ ]
+ elif (
+ isinstance(input, (list, tuple))
+ and input
+ and any(isinstance(i, Command) for i in input)
+ ):
+ updates: list[tuple[str, Any]] = []
+ for i in input:
+ if isinstance(i, Command):
+ if i.graph == Command.PARENT:
+ continue
+ updates.extend(
+ (k, v) for k, v in i._update_as_tuples() if k in output_keys
+ )
+ else:
+ updates.extend(_get_updates(i) or ())
+ return updates
+ elif (t := type(input)) and get_cached_annotated_keys(t):
+ return get_update_as_tuples(input, output_keys)
+ else:
+ msg = create_error_message(
+ message=f"Expected dict, got {input}",
+ error_code=ErrorCode.INVALID_GRAPH_NODE_RETURN_VALUE,
+ )
+ raise InvalidUpdateError(msg)
+
+ # state updaters
+ write_entries: tuple[ChannelWriteEntry | ChannelWriteTupleEntry, ...] = (
+ ChannelWriteTupleEntry(
+ mapper=_get_root if output_keys == ["__root__"] else _get_updates
+ ),
+ ChannelWriteTupleEntry(
+ mapper=_control_branch,
+ static=_control_static(node.ends)
+ if node is not None and node.ends is not None
+ else None,
+ ),
+ )
+
+ # add node and output channel
+ if key == START:
+ self.nodes[key] = PregelNode(
+ tags=[TAG_HIDDEN],
+ triggers=[START],
+ channels=START,
+ writers=[ChannelWrite(write_entries)],
+ )
+ elif node is not None:
+ input_schema = node.input_schema if node else self.builder.state_schema
+ input_channels = list(self.builder.schemas[input_schema])
+ is_single_input = len(input_channels) == 1 and "__root__" in input_channels
+ if input_schema in self.schema_to_mapper:
+ mapper = self.schema_to_mapper[input_schema]
+ else:
+ mapper = _pick_mapper(input_channels, input_schema)
+ self.schema_to_mapper[input_schema] = mapper
+
+ branch_channel = _CHANNEL_BRANCH_TO.format(key)
+ self.channels[branch_channel] = (
+ LastValueAfterFinish(Any)
+ if node.defer
+ else EphemeralValue(Any, guard=False)
+ )
+ self.nodes[key] = PregelNode(
+ triggers=[branch_channel],
+ # read state keys and managed values
+ channels=("__root__" if is_single_input else input_channels),
+ # coerce state dict to schema class (eg. pydantic model)
+ mapper=mapper,
+ # publish to state keys
+ writers=[ChannelWrite(write_entries)],
+ metadata=node.metadata,
+ retry_policy=node.retry_policy,
+ cache_policy=node.cache_policy,
+ is_error_handler=node.is_error_handler,
+ error_handler_node=node.error_handler_node,
+ bound=node.runnable, # type: ignore[arg-type]
+ timeout=node.timeout,
+ )
+ else:
+ raise RuntimeError
+
+ def attach_edge(self, starts: str | Sequence[str], end: str) -> None:
+ if isinstance(starts, str):
+ # subscribe to start channel
+ if end != END:
+ self.nodes[starts].writers.append(
+ ChannelWrite(
+ (ChannelWriteEntry(_CHANNEL_BRANCH_TO.format(end), None),)
+ )
+ )
+ elif end != END:
+ channel_name = f"join:{'+'.join(starts)}:{end}"
+ # register channel
+ if self.builder.nodes[end].defer:
+ self.channels[channel_name] = NamedBarrierValueAfterFinish(
+ str, set(starts)
+ )
+ else:
+ self.channels[channel_name] = NamedBarrierValue(str, set(starts))
+ # subscribe to channel
+ self.nodes[end].triggers.append(channel_name)
+ # publish to channel
+ for start in starts:
+ self.nodes[start].writers.append(
+ ChannelWrite((ChannelWriteEntry(channel_name, start),))
+ )
+
+ def attach_branch(
+ self, start: str, name: str, branch: BranchSpec, *, with_reader: bool = True
+ ) -> None:
+ def get_writes(
+ packets: Sequence[str | Send], static: bool = False
+ ) -> Sequence[ChannelWriteEntry | Send]:
+ writes = [
+ (
+ ChannelWriteEntry(
+ p if p == END else _CHANNEL_BRANCH_TO.format(p), None
+ )
+ if not isinstance(p, Send)
+ else p
+ )
+ for p in packets
+ if (True if static else p != END)
+ ]
+ if not writes:
+ return []
+ return writes
+
+ if with_reader:
+ # get schema
+ schema = branch.input_schema or (
+ self.builder.nodes[start].input_schema
+ if start in self.builder.nodes
+ else self.builder.state_schema
+ )
+ channels = list(self.builder.schemas[schema])
+ # get mapper
+ if schema in self.schema_to_mapper:
+ mapper = self.schema_to_mapper[schema]
+ else:
+ mapper = _pick_mapper(channels, schema)
+ self.schema_to_mapper[schema] = mapper
+ # create reader
+ reader: Callable[[RunnableConfig], Any] | None = partial(
+ ChannelRead.do_read,
+ select=channels[0] if channels == ["__root__"] else channels,
+ fresh=True,
+ # coerce state dict to schema class (eg. pydantic model)
+ mapper=mapper,
+ )
+ else:
+ reader = None
+
+ # attach branch publisher
+ self.nodes[start].writers.append(branch.run(get_writes, reader))
+
+ def _migrate_checkpoint(self, checkpoint: Checkpoint) -> None:
+ """Migrate a checkpoint to new channel layout."""
+ super()._migrate_checkpoint(checkpoint)
+
+ values = checkpoint["channel_values"]
+ versions = checkpoint["channel_versions"]
+ seen = checkpoint["versions_seen"]
+
+ # empty checkpoints do not need migration
+ if not versions:
+ return
+
+ # current version
+ if checkpoint["v"] >= 3:
+ return
+
+ # Migrate from start:node to branch:to:node
+ for k in list(versions):
+ if k.startswith("start:"):
+ # confirm node is present
+ node = k.split(":")[1]
+ if node not in self.nodes:
+ continue
+ # get next version
+ new_k = f"branch:to:{node}"
+ new_v = (
+ max(versions[new_k], versions.pop(k))
+ if new_k in versions
+ else versions.pop(k)
+ )
+ # update seen
+ for ss in (seen.get(node, {}), seen.get(INTERRUPT, {})):
+ if k in ss:
+ s = ss.pop(k)
+ if new_k in ss:
+ ss[new_k] = max(s, ss[new_k])
+ else:
+ ss[new_k] = s
+ # update value
+ if new_k not in values and k in values:
+ values[new_k] = values.pop(k)
+ # update version
+ versions[new_k] = new_v
+
+ # Migrate from branch:source:condition:node to branch:to:node
+ for k in list(versions):
+ if k.startswith("branch:") and k.count(":") == 3:
+ # confirm node is present
+ node = k.split(":")[-1]
+ if node not in self.nodes:
+ continue
+ # get next version
+ new_k = f"branch:to:{node}"
+ new_v = (
+ max(versions[new_k], versions.pop(k))
+ if new_k in versions
+ else versions.pop(k)
+ )
+ # update seen
+ for ss in (seen.get(node, {}), seen.get(INTERRUPT, {})):
+ if k in ss:
+ s = ss.pop(k)
+ if new_k in ss:
+ ss[new_k] = max(s, ss[new_k])
+ else:
+ ss[new_k] = s
+ # update value
+ if new_k not in values and k in values:
+ values[new_k] = values.pop(k)
+ # update version
+ versions[new_k] = new_v
+
+ if not set(self.nodes).isdisjoint(versions):
+ # Migrate from "node" to "branch:to:node"
+ source_to_target = defaultdict(list)
+ for start, end in self.builder.edges:
+ if start != START and end != END:
+ source_to_target[start].append(end)
+ for k in list(versions):
+ if k == START:
+ continue
+ if k in self.nodes:
+ v = versions.pop(k)
+ c = values.pop(k, MISSING)
+ for end in source_to_target[k]:
+ # get next version
+ new_k = f"branch:to:{end}"
+ new_v = max(versions[new_k], v) if new_k in versions else v
+ # update seen
+ for ss in (seen.get(end, {}), seen.get(INTERRUPT, {})):
+ if k in ss:
+ s = ss.pop(k)
+ if new_k in ss:
+ ss[new_k] = max(s, ss[new_k])
+ else:
+ ss[new_k] = s
+ # update value
+ if new_k not in values and c is not MISSING:
+ values[new_k] = c
+ # update version
+ versions[new_k] = new_v
+ # pop interrupt seen
+ if INTERRUPT in seen:
+ seen[INTERRUPT].pop(k, MISSING)
+
+
+def _pick_mapper(
+ state_keys: Sequence[str], schema: type[Any]
+) -> Callable[[Any], Any] | None:
+ if state_keys == ["__root__"]:
+ return None
+ if isclass(schema) and (issubclass(schema, BaseModel) or is_dataclass(schema)):
+ return partial(_coerce_state, schema)
+ return None
+
+
+_S = TypeVar("_S")
+
+
+def _coerce_state(schema: type[_S], input: dict[str, Any]) -> _S:
+ return schema(**input)
+
+
+def _control_branch(value: Any) -> Sequence[tuple[str, Any]]:
+ if isinstance(value, Send):
+ return ((TASKS, value),)
+ commands: list[Command] = []
+ if isinstance(value, Command):
+ commands.append(value)
+ elif isinstance(value, (list, tuple)):
+ for cmd in value:
+ if isinstance(cmd, Command):
+ commands.append(cmd)
+ rtn: list[tuple[str, Any]] = []
+ for command in commands:
+ if command.graph == Command.PARENT:
+ raise ParentCommand(command)
+
+ goto_targets = (
+ [command.goto] if isinstance(command.goto, (Send, str)) else command.goto
+ )
+
+ for go in goto_targets:
+ if isinstance(go, Send):
+ rtn.append((TASKS, go))
+ elif isinstance(go, str) and go != END:
+ # END is a special case, it's not actually a node in a practical sense
+ # but rather a special terminal node that we don't need to branch to
+ rtn.append((_CHANNEL_BRANCH_TO.format(go), None))
+ return rtn
+
+
+def _control_static(
+ ends: tuple[str, ...] | dict[str, str],
+) -> Sequence[tuple[str, Any, str | None]]:
+ if isinstance(ends, dict):
+ return [
+ (k if k == END else _CHANNEL_BRANCH_TO.format(k), None, label)
+ for k, label in ends.items()
+ ]
+ else:
+ return [
+ (e if e == END else _CHANNEL_BRANCH_TO.format(e), None, None) for e in ends
+ ]
+
+
+def _get_root(input: Any) -> Sequence[tuple[str, Any]] | None:
+ if isinstance(input, Command):
+ if input.graph == Command.PARENT:
+ return ()
+ return input._update_as_tuples()
+ elif (
+ isinstance(input, (list, tuple))
+ and input
+ and any(isinstance(i, Command) for i in input)
+ ):
+ updates: list[tuple[str, Any]] = []
+ for i in input:
+ if isinstance(i, Command):
+ if i.graph == Command.PARENT:
+ continue
+ updates.extend(i._update_as_tuples())
+ else:
+ updates.append(("__root__", i))
+ return updates
+ elif input is not None:
+ return [("__root__", input)]
+
+
+def _get_channels(
+ schema: type[dict],
+) -> tuple[dict[str, BaseChannel], dict[str, ManagedValueSpec], dict[str, Any]]:
+ if not hasattr(schema, "__annotations__"):
+ return (
+ {"__root__": _get_channel("__root__", schema, allow_managed=False)},
+ {},
+ {},
+ )
+
+ type_hints = get_type_hints(schema, include_extras=True)
+ all_keys = {
+ name: _get_channel(name, typ)
+ for name, typ in type_hints.items()
+ if name != "__slots__"
+ }
+ return (
+ {k: v for k, v in all_keys.items() if isinstance(v, BaseChannel)},
+ {k: v for k, v in all_keys.items() if is_managed_value(v)},
+ type_hints,
+ )
+
+
+@overload
+def _get_channel(
+ name: str, annotation: Any, *, allow_managed: Literal[False]
+) -> BaseChannel: ...
+
+
+@overload
+def _get_channel(
+ name: str, annotation: Any, *, allow_managed: Literal[True] = True
+) -> BaseChannel | ManagedValueSpec: ...
+
+
+def _get_channel(
+ name: str, annotation: Any, *, allow_managed: bool = True
+) -> BaseChannel | ManagedValueSpec:
+ # Strip out Required and NotRequired wrappers
+ if hasattr(annotation, "__origin__") and annotation.__origin__ in (
+ Required,
+ NotRequired,
+ ):
+ annotation = annotation.__args__[0]
+ if manager := _is_field_managed_value(name, annotation):
+ if allow_managed:
+ return manager
+ else:
+ raise ValueError(f"This {annotation} not allowed in this position")
+ elif channel := _is_field_channel(annotation):
+ channel.key = name
+ return channel
+ elif channel := _is_field_binop(annotation):
+ channel.key = name
+ return channel
+
+ fallback: LastValue = LastValue(annotation)
+ fallback.key = name
+ return fallback
+
+
+def _is_field_channel(typ: type[Any]) -> BaseChannel | None:
+ if hasattr(typ, "__metadata__"):
+ meta = typ.__metadata__
+ # Search through all annotated medata to find channel annotations
+ for item in meta:
+ if isinstance(item, BaseChannel):
+ if isinstance(item, DeltaChannel) and hasattr(typ, "__origin__"):
+ origin = typ.__origin__
+ # Unwrap parameterized Required[X]/NotRequired[X] to X
+ # (e.g. Annotated[NotRequired[dict[...]], ...]).
+ if hasattr(origin, "__origin__") and origin.__origin__ in (
+ Required,
+ NotRequired,
+ ):
+ origin = origin.__args__[0]
+ item = item.__class__(
+ item.reducer,
+ origin,
+ snapshot_frequency=item.snapshot_frequency,
+ )
+ return item
+ elif isclass(item) and issubclass(item, BaseChannel):
+ # ex, Annotated[int, EphemeralValue, SomeOtherAnnotation]
+ # would return EphemeralValue(int)
+ return item(typ.__origin__ if hasattr(typ, "__origin__") else typ)
+ return None
+
+
+def _is_field_binop(typ: type[Any]) -> BinaryOperatorAggregate | None:
+ if hasattr(typ, "__metadata__"):
+ meta = typ.__metadata__
+ if len(meta) >= 1 and callable(meta[-1]):
+ sig = signature(meta[-1])
+ params = list(sig.parameters.values())
+ if (
+ sum(
+ p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
+ for p in params
+ )
+ == 2
+ ):
+ return BinaryOperatorAggregate(typ, meta[-1])
+ else:
+ raise ValueError(
+ f"Invalid reducer signature. Expected (a, b) -> c. Got {sig}"
+ )
+ return None
+
+
+def _is_field_managed_value(name: str, typ: type[Any]) -> ManagedValueSpec | None:
+ if hasattr(typ, "__metadata__"):
+ meta = typ.__metadata__
+ if len(meta) >= 1:
+ decoration = get_origin(meta[-1]) or meta[-1]
+ if is_managed_value(decoration):
+ return decoration
+
+ # Handle Required, NotRequired, etc wrapped types by extracting the inner type
+ if (
+ get_origin(typ) is not None
+ and (args := get_args(typ))
+ and (inner_type := args[0])
+ ):
+ return _is_field_managed_value(name, inner_type)
+
+ return None
+
+
+def _get_json_schema(
+ typ: type,
+ schemas: dict,
+ channels: dict,
+ name: str,
+) -> dict[str, Any]:
+ if isclass(typ) and issubclass(typ, BaseModel):
+ return typ.model_json_schema()
+ elif is_typeddict(typ):
+ return TypeAdapter(typ).json_schema()
+ else:
+ keys = list(schemas[typ].keys())
+ if len(keys) == 1 and keys[0] == "__root__":
+ return create_model(
+ name,
+ root=(channels[keys[0]].UpdateType, None),
+ ).model_json_schema()
+ else:
+ return create_model(
+ name,
+ field_definitions={
+ k: (
+ channels[k].UpdateType,
+ (
+ get_field_default(
+ k,
+ channels[k].UpdateType,
+ typ,
+ )
+ ),
+ )
+ for k in schemas[typ]
+ if k in channels and isinstance(channels[k], BaseChannel)
+ },
+ ).model_json_schema()
diff --git a/python/user_packages/Python313/site-packages/langgraph/graph/ui.py b/python/user_packages/Python313/site-packages/langgraph/graph/ui.py
new file mode 100644
index 0000000000000000000000000000000000000000..847b2c7fac4087e0dc5d25d70bf5d9272b718928
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/graph/ui.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+from typing import Any, Literal, cast
+from uuid import uuid4
+
+from langchain_core.messages import AnyMessage
+from typing_extensions import TypedDict
+
+from langgraph.config import get_config, get_stream_writer
+from langgraph.constants import CONF
+
+__all__ = (
+ "UIMessage",
+ "RemoveUIMessage",
+ "AnyUIMessage",
+ "push_ui_message",
+ "delete_ui_message",
+ "ui_message_reducer",
+)
+
+
+class UIMessage(TypedDict):
+ """A message type for UI updates in LangGraph.
+
+ This TypedDict represents a UI message that can be sent to update the UI state.
+ It contains information about the UI component to render and its properties.
+
+ Attributes:
+ type: Literal type indicating this is a UI message.
+ id: Unique identifier for the UI message.
+ name: Name of the UI component to render.
+ props: Properties to pass to the UI component.
+ metadata: Additional metadata about the UI message.
+ """
+
+ type: Literal["ui"]
+ id: str
+ name: str
+ props: dict[str, Any]
+ metadata: dict[str, Any]
+
+
+class RemoveUIMessage(TypedDict):
+ """A message type for removing UI components in LangGraph.
+
+ This TypedDict represents a message that can be sent to remove a UI component
+ from the current state.
+
+ Attributes:
+ type: Literal type indicating this is a remove-ui message.
+ id: Unique identifier of the UI message to remove.
+ """
+
+ type: Literal["remove-ui"]
+ id: str
+
+
+AnyUIMessage = UIMessage | RemoveUIMessage
+
+
+def push_ui_message(
+ name: str,
+ props: dict[str, Any],
+ *,
+ id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ message: AnyMessage | None = None,
+ state_key: str | None = "ui",
+ merge: bool = False,
+) -> UIMessage:
+ """Push a new UI message to update the UI state.
+
+ This function creates and sends a UI message that will be rendered in the UI.
+ It also updates the graph state with the new UI message.
+
+ Args:
+ name: Name of the UI component to render.
+ props: Properties to pass to the UI component.
+ id: Optional unique identifier for the UI message.
+ If not provided, a random UUID will be generated.
+ metadata: Optional additional metadata about the UI message.
+ message: Optional message object to associate with the UI message.
+ state_key: Key in the graph state where the UI messages are stored.
+ merge: Whether to merge props with existing UI message (True) or replace
+ them (False).
+
+ Returns:
+ The created UI message.
+
+ Example:
+ ```python
+ push_ui_message(
+ name="component-name",
+ props={"content": "Hello world"},
+ )
+ ```
+
+ """
+ from langgraph._internal._constants import CONFIG_KEY_SEND
+
+ writer = get_stream_writer()
+ config = get_config()
+
+ message_id = None
+ if message:
+ if isinstance(message, dict) and "id" in message:
+ message_id = message.get("id")
+ elif hasattr(message, "id"):
+ message_id = message.id
+
+ evt: UIMessage = {
+ "type": "ui",
+ "id": id or str(uuid4()),
+ "name": name,
+ "props": props,
+ "metadata": {
+ "merge": merge,
+ "run_id": config.get("run_id", None),
+ "tags": config.get("tags", None),
+ "name": config.get("run_name", None),
+ **(metadata or {}),
+ **({"message_id": message_id} if message_id else {}),
+ },
+ }
+
+ writer(evt)
+ if state_key:
+ config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
+
+ return evt
+
+
+def delete_ui_message(id: str, *, state_key: str = "ui") -> RemoveUIMessage:
+ """Delete a UI message by ID from the UI state.
+
+ This function creates and sends a message to remove a UI component from the current state.
+ It also updates the graph state to remove the UI message.
+
+ Args:
+ id: Unique identifier of the UI component to remove.
+ state_key: Key in the graph state where the UI messages are stored. Defaults to "ui".
+
+ Returns:
+ The remove UI message.
+
+ Example:
+ ```python
+ delete_ui_message("message-123")
+ ```
+
+ """
+ from langgraph._internal._constants import CONFIG_KEY_SEND
+
+ writer = get_stream_writer()
+ config = get_config()
+
+ evt: RemoveUIMessage = {"type": "remove-ui", "id": id}
+
+ writer(evt)
+ config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
+
+ return evt
+
+
+def ui_message_reducer(
+ left: list[AnyUIMessage] | AnyUIMessage,
+ right: list[AnyUIMessage] | AnyUIMessage,
+) -> list[AnyUIMessage]:
+ """Merge two lists of UI messages, supporting removing UI messages.
+
+ This function combines two lists of UI messages, handling both regular UI messages
+ and `remove-ui` messages. When a `remove-ui` message is encountered, it removes any
+ UI message with the matching ID from the current state.
+
+ Args:
+ left: First list of UI messages or single UI message.
+ right: Second list of UI messages or single UI message.
+
+ Returns:
+ Combined list of UI messages with removals applied.
+
+ Example:
+ ```python
+ messages = ui_message_reducer(
+ [{"type": "ui", "id": "1", "name": "Chat", "props": {}}],
+ {"type": "remove-ui", "id": "1"},
+ )
+ ```
+
+ """
+ if not isinstance(left, list):
+ left = [left]
+
+ if not isinstance(right, list):
+ right = [right]
+
+ # merge messages
+ merged = left.copy()
+ merged_by_id = {m.get("id"): i for i, m in enumerate(merged)}
+ ids_to_remove = set()
+
+ for msg in right:
+ msg_id = msg.get("id")
+
+ if (existing_idx := merged_by_id.get(msg_id)) is not None:
+ if msg.get("type") == "remove-ui":
+ ids_to_remove.add(msg_id)
+ else:
+ ids_to_remove.discard(msg_id)
+
+ if cast(UIMessage, msg).get("metadata", {}).get("merge", False):
+ prev_msg = merged[existing_idx]
+ msg = msg.copy()
+ msg["props"] = {**prev_msg["props"], **msg["props"]}
+
+ merged[existing_idx] = msg
+ else:
+ if msg.get("type") == "remove-ui":
+ raise ValueError(
+ f"Attempting to delete an UI message with an ID that doesn't exist ('{msg_id}')"
+ )
+
+ merged_by_id[msg_id] = len(merged)
+ merged.append(msg)
+
+ merged = [m for m in merged if m.get("id") not in ids_to_remove]
+ return merged
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/__init__.py b/python/user_packages/Python313/site-packages/langgraph/managed/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d50f323b2703f9747a7450d07f6eac868c665fd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/managed/__init__.py
@@ -0,0 +1,3 @@
+from langgraph.managed.is_last_step import IsLastStep, RemainingSteps
+
+__all__ = ("IsLastStep", "RemainingSteps")
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c76dd0bc98b40092ebe364398392650e113c5296
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/base.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..893747606acf0a30e7d1fc15fb680ef7829e5434
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/base.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/is_last_step.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/is_last_step.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..281beab5fd07e9a126d3b44227aaadf493e8b067
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/managed/__pycache__/is_last_step.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/base.py b/python/user_packages/Python313/site-packages/langgraph/managed/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..7205967f29744a429a187a1b63dcb7f04a762ba2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/managed/base.py
@@ -0,0 +1,31 @@
+from abc import ABC, abstractmethod
+from inspect import isclass
+from typing import (
+ Any,
+ Generic,
+ TypeGuard,
+ TypeVar,
+)
+
+from langgraph._internal._scratchpad import PregelScratchpad
+
+V = TypeVar("V")
+U = TypeVar("U")
+
+__all__ = ("ManagedValueSpec", "ManagedValueMapping")
+
+
+class ManagedValue(ABC, Generic[V]):
+ @staticmethod
+ @abstractmethod
+ def get(scratchpad: PregelScratchpad) -> V: ...
+
+
+ManagedValueSpec = type[ManagedValue]
+
+
+def is_managed_value(value: Any) -> TypeGuard[ManagedValueSpec]:
+ return isclass(value) and issubclass(value, ManagedValue)
+
+
+ManagedValueMapping = dict[str, ManagedValueSpec]
diff --git a/python/user_packages/Python313/site-packages/langgraph/managed/is_last_step.py b/python/user_packages/Python313/site-packages/langgraph/managed/is_last_step.py
new file mode 100644
index 0000000000000000000000000000000000000000..e53058db3660bca50e4c93ba4438ea02e25e1a07
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/managed/is_last_step.py
@@ -0,0 +1,24 @@
+from typing import Annotated
+
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph.managed.base import ManagedValue
+
+__all__ = ("IsLastStep", "RemainingStepsManager")
+
+
+class IsLastStepManager(ManagedValue[bool]):
+ @staticmethod
+ def get(scratchpad: PregelScratchpad) -> bool:
+ return scratchpad.step == scratchpad.stop - 1
+
+
+IsLastStep = Annotated[bool, IsLastStepManager]
+
+
+class RemainingStepsManager(ManagedValue[int]):
+ @staticmethod
+ def get(scratchpad: PregelScratchpad) -> int:
+ return scratchpad.stop - scratchpad.step
+
+
+RemainingSteps = Annotated[int, RemainingStepsManager]
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__init__.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d879526272880963cf851928e5d718dfe1f6a5f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__init__.py
@@ -0,0 +1,23 @@
+"""langgraph.prebuilt exposes a higher-level API for creating and executing agents and tools."""
+
+from langgraph.prebuilt._tool_call_transformer import ToolCallTransformer
+from langgraph.prebuilt.chat_agent_executor import create_react_agent
+from langgraph.prebuilt.tool_node import (
+ InjectedState,
+ InjectedStore,
+ ToolNode,
+ ToolRuntime,
+ tools_condition,
+)
+from langgraph.prebuilt.tool_validator import ValidationNode
+
+__all__ = [
+ "create_react_agent",
+ "ToolNode",
+ "ToolCallTransformer",
+ "tools_condition",
+ "ValidationNode",
+ "InjectedState",
+ "InjectedStore",
+ "ToolRuntime",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8fb58e24a38c1f489363154081405366054d459
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a758380d0d9f925cd57041eab38eb2a290cca69a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_transformer.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_transformer.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9841c4d244c982c567339294eb247d5a2f9bf00a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/_tool_call_transformer.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/chat_agent_executor.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/chat_agent_executor.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5274b117903ef9bbec52522432fb8856f877ca8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/chat_agent_executor.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/interrupt.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/interrupt.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce0e9dd47e1e59979578ab0b618ad8f1db3c3b19
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/interrupt.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_node.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_node.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47755b5ce90ab472d98a30ac1a6334db0ceea383
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_node.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_validator.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_validator.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ab3c3413b0f80c384c14aa5bbe28ef9e0cae021
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/prebuilt/__pycache__/tool_validator.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_stream.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..da2e1c737f3c960f7d79e090aa4c16fa9ae87d32
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_stream.py
@@ -0,0 +1,117 @@
+"""In-process handle for a single tool call's streaming execution.
+
+Mirrors the shape of `ChatModelStream` from langchain-core but simpler —
+a tool has one output channel, no content-block multiplexing. Populated
+by `ToolCallTransformer` as `tool-started` / `tool-output-delta` /
+`tool-finished` / `tool-error` events flow in on the `tools` channel.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Iterator
+from typing import Any
+
+from langgraph.stream.stream_channel import StreamChannel
+
+
+class ToolCallStream:
+ """Scoped view of a single tool call's lifecycle.
+
+ Yielded on `run.tool_calls` once per `tool-started` event. Fields
+ are populated as events arrive:
+
+ - `tool_call_id`, `tool_name`, `input`: stable from the start event.
+ - `output_deltas`: a `StreamChannel` of delta chunks. Iterate (sync or
+ async) to consume partial output in arrival order.
+ - `output`: terminal payload from `tool-finished`, or `None` if the
+ call failed or is still in flight.
+ - `error`: terminal error string from `tool-error`, or `None` if the
+ call succeeded or is still in flight.
+ - `completed`: True once a terminal event (`tool-finished` or
+ `tool-error`) has been observed.
+
+ `ToolCallStream` is not meant to be constructed by end users — it's
+ produced by `ToolCallTransformer` as events flow through the mux.
+ """
+
+ def __init__(
+ self,
+ tool_call_id: str,
+ tool_name: str,
+ input: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize a fresh handle for a tool call.
+
+ Args:
+ tool_call_id: The `tool_call_id` from the AIMessage.
+ tool_name: The tool's name.
+ input: The tool's input arguments (as reported by
+ `on_tool_start`), or `None` if none were captured.
+ """
+ self.tool_call_id = tool_call_id
+ self.tool_name = tool_name
+ self.input = input
+ self._output_deltas: StreamChannel[Any] = StreamChannel()
+ self.output: Any = None
+ self.error: str | None = None
+ self.completed = False
+
+ @property
+ def output_deltas(self) -> StreamChannel[Any]:
+ """The channel of streamed `tool-output-delta` payloads.
+
+ Iterate (sync or async depending on how the run was started)
+ to consume partial output in arrival order. The log closes when
+ the tool finishes or errors.
+ """
+ return self._output_deltas
+
+ def _bind(self, *, is_async: bool) -> None:
+ """Bind the deltas log to sync or async iteration.
+
+ Called by `ToolCallTransformer` when constructing this handle so
+ the log matches the enclosing mux's mode.
+ """
+ self._output_deltas._bind(is_async=is_async)
+
+ def _push_delta(self, delta: Any) -> None:
+ self._output_deltas.push(delta)
+
+ def _finish(self, output: Any) -> None:
+ self.output = output
+ self.completed = True
+ self._output_deltas.close()
+
+ def _fail(self, message: str) -> None:
+ self.error = message
+ self.completed = True
+ self._output_deltas.close()
+
+ def __iter__(self) -> Iterator[Any]:
+ """Iterate delta chunks synchronously.
+
+ Equivalent to `iter(self.output_deltas)`. Raises `TypeError` if
+ the underlying log is bound to async mode.
+ """
+ return iter(self._output_deltas)
+
+ def __aiter__(self) -> AsyncIterator[Any]:
+ """Iterate delta chunks asynchronously.
+
+ Equivalent to `aiter(self.output_deltas)`. Raises `TypeError`
+ if the underlying log is bound to sync mode.
+ """
+ return self._output_deltas.__aiter__()
+
+ def __repr__(self) -> str:
+ status = (
+ "completed"
+ if self.completed and self.error is None
+ else "failed"
+ if self.completed
+ else "running"
+ )
+ return (
+ f"ToolCallStream(tool_call_id={self.tool_call_id!r}, "
+ f"tool_name={self.tool_name!r}, status={status})"
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_transformer.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..696dcdcab38f9fd0d6c2f0b797746cf87389cb04
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/_tool_call_transformer.py
@@ -0,0 +1,135 @@
+"""Transformer that projects `tools` channel events into `ToolCallStream`s."""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from langgraph.stream._types import ProtocolEvent, StreamTransformer
+from langgraph.stream.stream_channel import StreamChannel
+
+from langgraph.prebuilt._tool_call_stream import ToolCallStream
+
+
+class ToolCallTransformer(StreamTransformer):
+ """Project `tools` channel events into `ToolCallStream` handles.
+
+ Each `tool-started` event spawns a `ToolCallStream`, pushed onto
+ `run.tool_calls`. Subsequent `tool-output-delta` events append to
+ that stream's deltas log; `tool-finished` and `tool-error` close it.
+
+ Native transformer — the `tool_calls` projection is exposed as a
+ direct attribute on the run stream.
+
+ A nameless `StreamChannel[ToolCallStream]` is used (no protocol
+ auto-forwarding) because the live handles are not serializable and
+ should not be injected into the main event log. Wire consumers
+ subscribe to the `tools` channel instead, where the raw protocol
+ events flow through untouched by this transformer (`process`
+ returns `True`).
+
+ Registered explicitly by users at compile time via
+ `builder.compile(transformers=[ToolCallTransformer])` — not a
+ default built-in, so the `tools` channel is user-opt-in.
+ """
+
+ _native = True
+ required_stream_modes = ("tools",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[ToolCallStream] = StreamChannel()
+ self._active: dict[str, ToolCallStream] = {}
+ self._is_async = False
+ self._pump_fn: Callable[[], bool] | None = None
+ self._apump_fn: Callable[[], Awaitable[bool]] | None = None
+
+ def init(self) -> dict[str, Any]:
+ return {"tool_calls": self._log}
+
+ def _bind_pump(self, fn: Callable[[], bool]) -> None:
+ """Wire the sync pull callback onto this transformer.
+
+ Called by `StreamMux.bind_pump`. Stored so each new
+ `ToolCallStream` created by `process` can wire its deltas log
+ for pump-driven iteration.
+ """
+ self._pump_fn = fn
+ self._is_async = False
+
+ def _bind_apump(self, fn: Callable[[], Awaitable[bool]]) -> None:
+ """Async counterpart to `_bind_pump`."""
+ self._apump_fn = fn
+ self._is_async = True
+
+ def _new_stream(
+ self,
+ tool_call_id: str,
+ tool_name: str,
+ tool_input: dict[str, Any] | None,
+ ) -> ToolCallStream:
+ stream = ToolCallStream(tool_call_id, tool_name, tool_input)
+ stream._bind(is_async=self._is_async)
+ if self._apump_fn is not None:
+ stream._output_deltas._arequest_more = self._apump_fn
+ if self._pump_fn is not None:
+ stream._output_deltas._request_more = self._pump_fn
+ return stream
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "tools":
+ return True
+
+ # Only project events emitted at this transformer's scope. Subgraph
+ # events still flow through the parent's mux (the parent's main
+ # event log keeps them) but they belong to the child mini-mux's
+ # `tool_calls` projection, not the parent's.
+ if tuple(event["params"]["namespace"]) != self.scope:
+ return True
+
+ data = event["params"]["data"]
+ tool_call_id = data.get("tool_call_id")
+ if tool_call_id is None:
+ return True
+ event_type = data.get("event")
+
+ stream: ToolCallStream | None
+ if event_type == "tool-started":
+ stream = self._new_stream(
+ tool_call_id,
+ data.get("tool_name", ""),
+ data.get("input"),
+ )
+ self._active[tool_call_id] = stream
+ self._log.push(stream)
+ elif event_type == "tool-output-delta":
+ stream = self._active.get(tool_call_id)
+ if stream is not None:
+ stream._push_delta(data.get("delta"))
+ elif event_type == "tool-finished":
+ stream = self._active.pop(tool_call_id, None)
+ if stream is not None:
+ stream._finish(data.get("output"))
+ elif event_type == "tool-error":
+ stream = self._active.pop(tool_call_id, None)
+ if stream is not None:
+ stream._fail(data.get("message", ""))
+
+ # Pass-through — wire consumers subscribe to the `tools` channel
+ # directly and reconstruct handles client-side.
+ return True
+
+ def finalize(self) -> None:
+ """Close any still-active tool streams left open at run end."""
+ for stream in self._active.values():
+ if not stream.completed:
+ stream._finish(None)
+ self._active.clear()
+
+ def fail(self, err: BaseException) -> None:
+ """Fail any still-active tool streams when the run errors."""
+ message = str(err)
+ for stream in self._active.values():
+ if not stream.completed:
+ stream._fail(message)
+ self._active.clear()
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/chat_agent_executor.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/chat_agent_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c11c8847febbafd2b4fb3634868d40636c3b53b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/chat_agent_executor.py
@@ -0,0 +1,1015 @@
+import inspect
+import warnings
+from collections.abc import Awaitable, Callable, Sequence
+from typing import (
+ Annotated,
+ Any,
+ Literal,
+ TypeVar,
+ cast,
+ get_type_hints,
+)
+
+from langchain_core.language_models import (
+ BaseChatModel,
+ LanguageModelInput,
+ LanguageModelLike,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.runnables import (
+ Runnable,
+ RunnableBinding,
+ RunnableConfig,
+ RunnableSequence,
+)
+from langchain_core.tools import BaseTool
+from langgraph._internal._runnable import RunnableCallable, RunnableLike
+from langgraph._internal._typing import MISSING
+from langgraph.errors import ErrorCode, create_error_message
+from langgraph.graph import END, StateGraph
+from langgraph.graph.message import add_messages
+from langgraph.graph.state import CompiledStateGraph
+from langgraph.managed import RemainingSteps
+from langgraph.runtime import Runtime
+from langgraph.store.base import BaseStore
+from langgraph.types import Checkpointer, Send
+from langgraph.typing import ContextT
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+from pydantic import BaseModel
+from typing_extensions import NotRequired, TypedDict, deprecated
+
+from langgraph.prebuilt.tool_node import ToolCallWithContext, ToolNode
+
+StructuredResponse = dict | BaseModel
+StructuredResponseSchema = dict | type[BaseModel]
+
+
+@deprecated(
+ "AgentState has been moved to `langchain.agents`. Please update your import to `from langchain.agents import AgentState`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class AgentState(TypedDict):
+ """The state of the agent."""
+
+ messages: Annotated[Sequence[BaseMessage], add_messages]
+
+ remaining_steps: NotRequired[RemainingSteps]
+
+
+@deprecated(
+ "AgentStatePydantic has been deprecated in favor of AgentState in `langchain.agents`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class AgentStatePydantic(BaseModel):
+ """The state of the agent."""
+
+ messages: Annotated[Sequence[BaseMessage], add_messages]
+
+ remaining_steps: RemainingSteps = 25
+
+
+with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ category=LangGraphDeprecatedSinceV10,
+ message="AgentState has been moved to `langchain.agents`.*",
+ )
+
+ @deprecated(
+ "AgentStateWithStructuredResponse has been deprecated in favor of AgentState in `langchain.agents`.",
+ category=LangGraphDeprecatedSinceV10,
+ )
+ class AgentStateWithStructuredResponse(AgentState):
+ """The state of the agent with a structured response."""
+
+ structured_response: StructuredResponse
+
+
+with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ category=LangGraphDeprecatedSinceV10,
+ message="AgentStatePydantic has been deprecated in favor of AgentState in `langchain.agents`.",
+ )
+
+ @deprecated(
+ "AgentStateWithStructuredResponsePydantic has been deprecated in favor of AgentState in `langchain.agents`.",
+ category=LangGraphDeprecatedSinceV10,
+ )
+ class AgentStateWithStructuredResponsePydantic(AgentStatePydantic):
+ """The state of the agent with a structured response."""
+
+ structured_response: StructuredResponse
+
+
+with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ category=LangGraphDeprecatedSinceV10,
+ )
+ StateSchema = TypeVar("StateSchema", bound=AgentState | AgentStatePydantic)
+ StateSchemaType = type[StateSchema]
+
+PROMPT_RUNNABLE_NAME = "Prompt"
+
+Prompt = (
+ SystemMessage
+ | str
+ | Callable[[StateSchema], LanguageModelInput]
+ | Runnable[StateSchema, LanguageModelInput]
+)
+
+
+def _get_state_value(state: StateSchema, key: str, default: Any = None) -> Any:
+ return (
+ state.get(key, default)
+ if isinstance(state, dict)
+ else getattr(state, key, default)
+ )
+
+
+def _get_prompt_runnable(prompt: Prompt | None) -> Runnable:
+ prompt_runnable: Runnable
+ if prompt is None:
+ prompt_runnable = RunnableCallable(
+ lambda state: _get_state_value(state, "messages"), name=PROMPT_RUNNABLE_NAME
+ )
+ elif isinstance(prompt, str):
+ _system_message: BaseMessage = SystemMessage(content=prompt)
+ prompt_runnable = RunnableCallable(
+ lambda state: [_system_message] + _get_state_value(state, "messages"),
+ name=PROMPT_RUNNABLE_NAME,
+ )
+ elif isinstance(prompt, SystemMessage):
+ prompt_runnable = RunnableCallable(
+ lambda state: [prompt] + _get_state_value(state, "messages"),
+ name=PROMPT_RUNNABLE_NAME,
+ )
+ elif inspect.iscoroutinefunction(prompt):
+ prompt_runnable = RunnableCallable(
+ None,
+ prompt,
+ name=PROMPT_RUNNABLE_NAME,
+ )
+ elif callable(prompt):
+ prompt_runnable = RunnableCallable(
+ prompt,
+ name=PROMPT_RUNNABLE_NAME,
+ )
+ elif isinstance(prompt, Runnable):
+ prompt_runnable = prompt
+ else:
+ raise ValueError(f"Got unexpected type for `prompt`: {type(prompt)}")
+
+ return prompt_runnable
+
+
+def _should_bind_tools(
+ model: LanguageModelLike, tools: Sequence[BaseTool], num_builtin: int = 0
+) -> bool:
+ if isinstance(model, RunnableSequence):
+ model = next(
+ (
+ step
+ for step in model.steps
+ if isinstance(step, (RunnableBinding, BaseChatModel))
+ ),
+ model,
+ )
+
+ if not isinstance(model, RunnableBinding):
+ return True
+
+ if "tools" not in model.kwargs:
+ return True
+
+ bound_tools = model.kwargs["tools"]
+ if len(tools) != len(bound_tools) - num_builtin:
+ raise ValueError(
+ "Number of tools in the model.bind_tools() and tools passed to create_react_agent must match"
+ f" Got {len(tools)} tools, expected {len(bound_tools) - num_builtin}"
+ )
+
+ tool_names = set(tool.name for tool in tools)
+ bound_tool_names = set()
+ for bound_tool in bound_tools:
+ # OpenAI-style tool
+ if bound_tool.get("type") == "function":
+ bound_tool_name = bound_tool["function"]["name"]
+ # Anthropic-style tool
+ elif bound_tool.get("name"):
+ bound_tool_name = bound_tool["name"]
+ else:
+ # unknown tool type so we'll ignore it
+ continue
+
+ bound_tool_names.add(bound_tool_name)
+
+ if missing_tools := tool_names - bound_tool_names:
+ raise ValueError(f"Missing tools '{missing_tools}' in the model.bind_tools()")
+
+ return False
+
+
+def _get_model(model: LanguageModelLike) -> BaseChatModel:
+ """Get the underlying model from a RunnableBinding or return the model itself."""
+ if isinstance(model, RunnableSequence):
+ model = next(
+ (
+ step
+ for step in model.steps
+ if isinstance(step, (RunnableBinding, BaseChatModel))
+ ),
+ model,
+ )
+
+ if isinstance(model, RunnableBinding):
+ model = model.bound
+
+ if not isinstance(model, BaseChatModel):
+ raise TypeError(
+ f"Expected `model` to be a ChatModel or RunnableBinding (e.g. model.bind_tools(...)), got {type(model)}"
+ )
+
+ return model
+
+
+def _validate_chat_history(
+ messages: Sequence[BaseMessage],
+) -> None:
+ """Validate that all tool calls in AIMessages have a corresponding ToolMessage."""
+ all_tool_calls = [
+ tool_call
+ for message in messages
+ if isinstance(message, AIMessage)
+ for tool_call in message.tool_calls
+ ]
+ tool_call_ids_with_results = {
+ message.tool_call_id for message in messages if isinstance(message, ToolMessage)
+ }
+ tool_calls_without_results = [
+ tool_call
+ for tool_call in all_tool_calls
+ if tool_call["id"] not in tool_call_ids_with_results
+ ]
+ if not tool_calls_without_results:
+ return
+
+ error_message = create_error_message(
+ message="Found AIMessages with tool_calls that do not have a corresponding ToolMessage. "
+ f"Here are the first few of those tool calls: {tool_calls_without_results[:3]}.\n\n"
+ "Every tool call (LLM requesting to call a tool) in the message history MUST have a corresponding ToolMessage "
+ "(result of a tool invocation to return to the LLM) - this is required by most LLM providers.",
+ error_code=ErrorCode.INVALID_CHAT_HISTORY,
+ )
+ raise ValueError(error_message)
+
+
+@deprecated(
+ "create_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents import create_agent`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+def create_react_agent(
+ model: str
+ | LanguageModelLike
+ | Callable[[StateSchema, Runtime[ContextT]], BaseChatModel]
+ | Callable[[StateSchema, Runtime[ContextT]], Awaitable[BaseChatModel]]
+ | Callable[
+ [StateSchema, Runtime[ContextT]], Runnable[LanguageModelInput, BaseMessage]
+ ]
+ | Callable[
+ [StateSchema, Runtime[ContextT]],
+ Awaitable[Runnable[LanguageModelInput, BaseMessage]],
+ ],
+ tools: Sequence[BaseTool | Callable | dict[str, Any]] | ToolNode,
+ *,
+ prompt: Prompt | None = None,
+ response_format: StructuredResponseSchema
+ | tuple[str, StructuredResponseSchema]
+ | None = None,
+ pre_model_hook: RunnableLike | None = None,
+ post_model_hook: RunnableLike | None = None,
+ state_schema: StateSchemaType | None = None,
+ context_schema: type[Any] | None = None,
+ checkpointer: Checkpointer | None = None,
+ store: BaseStore | None = None,
+ interrupt_before: list[str] | None = None,
+ interrupt_after: list[str] | None = None,
+ debug: bool = False,
+ version: Literal["v1", "v2"] = "v2",
+ name: str | None = None,
+ **deprecated_kwargs: Any,
+) -> CompiledStateGraph:
+ """Creates an agent graph that calls tools in a loop until a stopping condition is met.
+
+ !!! warning
+
+ This function is deprecated in favor of
+ [`create_agent`][langchain.agents.create_agent] from the `langchain`
+ package, which provides an equivalent agent factory with a flexible
+ middleware system. For migration guidance, see
+ [Migrating from LangGraph v0](https://docs.langchain.com/oss/python/migrate/langgraph-v1).
+
+ Args:
+ model: The language model for the agent. Supports static and dynamic
+ model selection.
+
+ - **Static model**: A chat model instance (e.g.,
+ [`ChatOpenAI`][langchain_openai.ChatOpenAI]) or string identifier (e.g.,
+ `"openai:gpt-4"`)
+ - **Dynamic model**: A callable with signature
+ `(state, runtime) -> BaseChatModel` that returns different models
+ based on runtime context
+
+ If the model has tools bound via `bind_tools` or other configurations,
+ the return type should be a `Runnable[LanguageModelInput, BaseMessage]`
+ Coroutines are also supported, allowing for asynchronous model selection.
+
+ Dynamic functions receive graph state and runtime, enabling
+ context-dependent model selection. Must return a `BaseChatModel`
+ instance. For tool calling, bind tools using `.bind_tools()`.
+ Bound tools must be a subset of the `tools` parameter.
+
+ !!! example "Dynamic model"
+
+ ```python
+ from dataclasses import dataclass
+
+ @dataclass
+ class ModelContext:
+ model_name: str = "gpt-3.5-turbo"
+
+ # Instantiate models globally
+ gpt4_model = ChatOpenAI(model="gpt-4")
+ gpt35_model = ChatOpenAI(model="gpt-3.5-turbo")
+
+ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenAI:
+ model_name = runtime.context.model_name
+ model = gpt4_model if model_name == "gpt-4" else gpt35_model
+ return model.bind_tools(tools)
+ ```
+
+ !!! note "Dynamic Model Requirements"
+
+ Ensure returned models have appropriate tools bound via
+ `.bind_tools()` and support required functionality. Bound tools
+ must be a subset of those specified in the `tools` parameter.
+
+ tools: A list of tools or a `ToolNode` instance.
+ If an empty list is provided, the agent will consist of a single LLM node without tool calling.
+ prompt: An optional prompt for the LLM. Can take a few different forms:
+
+ - `str`: This is converted to a `SystemMessage` and added to the beginning of the list of messages in `state["messages"]`.
+ - `SystemMessage`: this is added to the beginning of the list of messages in `state["messages"]`.
+ - `Callable`: This function should take in full graph state and the output is then passed to the language model.
+ - `Runnable`: This runnable should take in full graph state and the output is then passed to the language model.
+
+ response_format: An optional schema for the final agent output.
+
+ If provided, output will be formatted to match the given schema and returned in the 'structured_response' state key.
+
+ If not provided, `structured_response` will not be present in the output state.
+
+ Can be passed in as:
+
+ - An OpenAI function/tool schema,
+ - A JSON Schema,
+ - A TypedDict class,
+ - A Pydantic class.
+ - A tuple `(prompt, schema)`, where schema is one of the above.
+ The prompt will be used together with the model that is being used to
+ generate the structured response.
+
+ !!! Important
+ `response_format` requires the model to support `.with_structured_output`
+
+ !!! Note
+ The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.
+ This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).
+
+ pre_model_hook: An optional node to add before the `agent` node (i.e., the node that calls the LLM).
+ Useful for managing long message histories (e.g., message trimming, summarization, etc.).
+ Pre-model hook must be a callable or a runnable that takes in current graph state and returns a state update in the form of
+ ```python
+ # At least one of `messages` or `llm_input_messages` MUST be provided
+ {
+ # If provided, will UPDATE the `messages` in the state
+ "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), ...],
+ # If provided, will be used as the input to the LLM,
+ # and will NOT UPDATE `messages` in the state
+ "llm_input_messages": [...],
+ # Any other state keys that need to be propagated
+ ...
+ }
+ ```
+
+ !!! Important
+ At least one of `messages` or `llm_input_messages` MUST be provided and will be used as an input to the `agent` node.
+ The rest of the keys will be added to the graph state.
+
+ !!! Warning
+ If you are returning `messages` in the pre-model hook, you should OVERWRITE the `messages` key by doing the following:
+
+ ```python
+ {
+ "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages]
+ ...
+ }
+ ```
+ post_model_hook: An optional node to add after the `agent` node (i.e., the node that calls the LLM).
+ Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.
+ Post-model hook must be a callable or a runnable that takes in current graph state and returns a state update.
+
+ !!! Note
+ Only available with `version="v2"`.
+ state_schema: An optional state schema that defines graph state.
+ Must have `messages` and `remaining_steps` keys.
+ Defaults to `AgentState` that defines those two keys.
+ !!! Note
+ `remaining_steps` is used to limit the number of steps the react agent can take.
+ Calculated roughly as `recursion_limit` - `total_steps_taken`.
+ If `remaining_steps` is less than 2 and tool calls are present in the response,
+ the react agent will return a final AI Message with
+ the content "Sorry, need more steps to process this request.".
+ No `GraphRecusionError` will be raised in this case.
+
+ context_schema: An optional schema for runtime context.
+ checkpointer: An optional checkpoint saver object. This is used for persisting
+ the state of the graph (e.g., as chat memory) for a single thread (e.g., a single conversation).
+ store: An optional store object. This is used for persisting data
+ across multiple threads (e.g., multiple conversations / users).
+ interrupt_before: An optional list of node names to interrupt before.
+ Should be one of the following: `"agent"`, `"tools"`.
+
+ This is useful if you want to add a user confirmation or other interrupt before taking an action.
+ interrupt_after: An optional list of node names to interrupt after.
+ Should be one of the following: `"agent"`, `"tools"`.
+
+ This is useful if you want to return directly or run additional processing on an output.
+ debug: A flag indicating whether to enable debug mode.
+ version: Determines the version of the graph to create.
+
+ Can be one of:
+
+ - `"v1"`: The tool node processes a single message. All tool
+ calls in the message are executed in parallel within the tool node.
+ - `"v2"`: The tool node processes a tool call.
+ Tool calls are distributed across multiple instances of the tool
+ node using the [Send](https://langchain-ai.github.io/langgraph/concepts/low_level/#send)
+ API.
+ name: An optional name for the `CompiledStateGraph`.
+ This name will be automatically used when adding ReAct agent graph to another graph as a subgraph node -
+ particularly useful for building multi-agent systems.
+
+ !!! warning "`config_schema` Deprecated"
+ The `config_schema` parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
+ Please use `context_schema` instead to specify the schema for run-scoped context.
+
+
+ Returns:
+ A compiled LangChain `Runnable` that can be used for chat interactions.
+
+ The "agent" node calls the language model with the messages list (after applying the prompt).
+ If the resulting AIMessage contains `tool_calls`, the graph will then call the ["tools"][langgraph.prebuilt.tool_node.ToolNode].
+ The "tools" node executes the tools (1 tool per `tool_call`) and adds the responses to the messages list
+ as `ToolMessage` objects. The agent node then calls the language model again.
+ The process repeats until no more `tool_calls` are present in the response.
+ The agent then returns the full list of messages as a dictionary containing the key `'messages'`.
+
+ ``` mermaid
+ sequenceDiagram
+ participant U as User
+ participant A as LLM
+ participant T as Tools
+ U->>A: Initial input
+ Note over A: Prompt + LLM
+ loop while tool_calls present
+ A->>T: Execute tools
+ T-->>A: ToolMessage for each tool_calls
+ end
+ A->>U: Return final state
+ ```
+
+ Example:
+ ```python
+ from langgraph.prebuilt import create_react_agent
+
+ def check_weather(location: str) -> str:
+ '''Return the weather forecast for the specified location.'''
+ return f"It's always sunny in {location}"
+
+ graph = create_react_agent(
+ "anthropic:claude-3-7-sonnet-latest",
+ tools=[check_weather],
+ prompt="You are a helpful assistant",
+ )
+ inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
+ for chunk in graph.stream(inputs, stream_mode="updates"):
+ print(chunk)
+ ```
+ """
+ if (
+ config_schema := deprecated_kwargs.pop("config_schema", MISSING)
+ ) is not MISSING:
+ warnings.warn(
+ "`config_schema` is deprecated and will be removed. Please use `context_schema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ )
+
+ if context_schema is None:
+ context_schema = config_schema
+
+ if len(deprecated_kwargs) > 0:
+ raise TypeError(
+ f"create_react_agent() got unexpected keyword arguments: {deprecated_kwargs}"
+ )
+
+ if version not in ("v1", "v2"):
+ raise ValueError(
+ f"Invalid version {version}. Supported versions are 'v1' and 'v2'."
+ )
+
+ if state_schema is not None:
+ required_keys = {"messages", "remaining_steps"}
+ if response_format is not None:
+ required_keys.add("structured_response")
+
+ schema_keys = set(get_type_hints(state_schema))
+ if missing_keys := required_keys - set(schema_keys):
+ raise ValueError(f"Missing required key(s) {missing_keys} in state_schema")
+
+ if state_schema is None:
+ state_schema = (
+ AgentStateWithStructuredResponse
+ if response_format is not None
+ else AgentState
+ )
+
+ llm_builtin_tools: list[dict] = []
+ if isinstance(tools, ToolNode):
+ tool_classes = list(tools.tools_by_name.values())
+ tool_node = tools
+ else:
+ llm_builtin_tools = [t for t in tools if isinstance(t, dict)]
+ tool_node = ToolNode([t for t in tools if not isinstance(t, dict)])
+ tool_classes = list(tool_node.tools_by_name.values())
+
+ is_dynamic_model = not isinstance(model, (str, Runnable)) and callable(model)
+ is_async_dynamic_model = is_dynamic_model and inspect.iscoroutinefunction(model)
+
+ tool_calling_enabled = len(tool_classes) > 0
+
+ if not is_dynamic_model:
+ if isinstance(model, str):
+ try:
+ from langchain.chat_models import ( # type: ignore[import-not-found]
+ init_chat_model,
+ )
+ except ImportError:
+ raise ImportError(
+ "Please install langchain (`pip install langchain`) to "
+ "use ':' string syntax for `model` parameter."
+ )
+
+ model = cast(BaseChatModel, init_chat_model(model))
+
+ if (
+ _should_bind_tools(model, tool_classes, num_builtin=len(llm_builtin_tools)) # type: ignore[arg-type]
+ and len(tool_classes + llm_builtin_tools) > 0
+ ):
+ model = cast(BaseChatModel, model).bind_tools(
+ tool_classes + llm_builtin_tools # type: ignore[operator]
+ )
+
+ static_model: Runnable | None = _get_prompt_runnable(prompt) | model # type: ignore[operator]
+ else:
+ # For dynamic models, we'll create the runnable at runtime
+ static_model = None
+
+ # If any of the tools are configured to return_directly after running,
+ # our graph needs to check if these were called
+ should_return_direct = {t.name for t in tool_classes if t.return_direct}
+
+ def _resolve_model(
+ state: StateSchema, runtime: Runtime[ContextT]
+ ) -> LanguageModelLike:
+ """Resolve the model to use, handling both static and dynamic models."""
+ if is_dynamic_model:
+ return _get_prompt_runnable(prompt) | model(state, runtime) # type: ignore[operator]
+ else:
+ return static_model
+
+ async def _aresolve_model(
+ state: StateSchema, runtime: Runtime[ContextT]
+ ) -> LanguageModelLike:
+ """Async resolve the model to use, handling both static and dynamic models."""
+ if is_async_dynamic_model:
+ resolved_model = await model(state, runtime) # type: ignore[misc,operator]
+ return _get_prompt_runnable(prompt) | resolved_model
+ elif is_dynamic_model:
+ return _get_prompt_runnable(prompt) | model(state, runtime) # type: ignore[operator]
+ else:
+ return static_model
+
+ def _are_more_steps_needed(state: StateSchema, response: BaseMessage) -> bool:
+ has_tool_calls = isinstance(response, AIMessage) and response.tool_calls
+ all_tools_return_direct = (
+ all(call["name"] in should_return_direct for call in response.tool_calls)
+ if isinstance(response, AIMessage)
+ else False
+ )
+ remaining_steps = _get_state_value(state, "remaining_steps", None)
+ if remaining_steps is not None:
+ if remaining_steps < 1 and all_tools_return_direct:
+ return True
+ elif remaining_steps < 2 and has_tool_calls:
+ return True
+
+ return False
+
+ def _get_model_input_state(state: StateSchema) -> StateSchema:
+ if pre_model_hook is not None:
+ messages = (
+ _get_state_value(state, "llm_input_messages")
+ ) or _get_state_value(state, "messages")
+ error_msg = f"Expected input to call_model to have 'llm_input_messages' or 'messages' key, but got {state}"
+ else:
+ messages = _get_state_value(state, "messages")
+ error_msg = (
+ f"Expected input to call_model to have 'messages' key, but got {state}"
+ )
+
+ if messages is None:
+ raise ValueError(error_msg)
+
+ _validate_chat_history(messages)
+ # we're passing messages under `messages` key, as this is expected by the prompt
+ if isinstance(state_schema, type) and issubclass(state_schema, BaseModel):
+ state.messages = messages # type: ignore
+ else:
+ state["messages"] = messages # type: ignore
+
+ return state
+
+ # Define the function that calls the model
+ def call_model(
+ state: StateSchema, runtime: Runtime[ContextT], config: RunnableConfig
+ ) -> StateSchema:
+ if is_async_dynamic_model:
+ msg = (
+ "Async model callable provided but agent invoked synchronously. "
+ "Use agent.ainvoke() or agent.astream(), or "
+ "provide a sync model callable."
+ )
+ raise RuntimeError(msg)
+
+ model_input = _get_model_input_state(state)
+
+ if is_dynamic_model:
+ # Resolve dynamic model at runtime and apply prompt
+ dynamic_model = _resolve_model(state, runtime)
+ response = cast(AIMessage, dynamic_model.invoke(model_input, config)) # type: ignore[arg-type]
+ else:
+ response = cast(AIMessage, static_model.invoke(model_input, config)) # type: ignore[union-attr]
+
+ # add agent name to the AIMessage
+ response.name = name
+
+ if _are_more_steps_needed(state, response):
+ return {
+ "messages": [
+ AIMessage(
+ id=response.id,
+ content="Sorry, need more steps to process this request.",
+ )
+ ]
+ }
+ # We return a list, because this will get added to the existing list
+ return {"messages": [response]}
+
+ async def acall_model(
+ state: StateSchema, runtime: Runtime[ContextT], config: RunnableConfig
+ ) -> StateSchema:
+ model_input = _get_model_input_state(state)
+
+ if is_dynamic_model:
+ # Resolve dynamic model at runtime and apply prompt
+ # (supports both sync and async)
+ dynamic_model = await _aresolve_model(state, runtime)
+ response = cast(AIMessage, await dynamic_model.ainvoke(model_input, config)) # type: ignore[arg-type]
+ else:
+ response = cast(AIMessage, await static_model.ainvoke(model_input, config)) # type: ignore[union-attr]
+
+ # add agent name to the AIMessage
+ response.name = name
+ if _are_more_steps_needed(state, response):
+ return {
+ "messages": [
+ AIMessage(
+ id=response.id,
+ content="Sorry, need more steps to process this request.",
+ )
+ ]
+ }
+ # We return a list, because this will get added to the existing list
+ return {"messages": [response]}
+
+ input_schema: StateSchemaType
+ if pre_model_hook is not None:
+ # Dynamically create a schema that inherits from state_schema and adds 'llm_input_messages'
+ if isinstance(state_schema, type) and issubclass(state_schema, BaseModel):
+ # For Pydantic schemas
+ from pydantic import create_model
+
+ input_schema = create_model(
+ "CallModelInputSchema",
+ llm_input_messages=(list[AnyMessage], ...),
+ __base__=state_schema,
+ )
+ else:
+ # For TypedDict schemas
+ class CallModelInputSchema(state_schema): # type: ignore
+ llm_input_messages: list[AnyMessage]
+
+ input_schema = CallModelInputSchema
+ else:
+ input_schema = state_schema
+
+ def generate_structured_response(
+ state: StateSchema, runtime: Runtime[ContextT], config: RunnableConfig
+ ) -> StateSchema:
+ if is_async_dynamic_model:
+ msg = (
+ "Async model callable provided but agent invoked synchronously. "
+ "Use agent.ainvoke() or agent.astream(), or provide a sync model callable."
+ )
+ raise RuntimeError(msg)
+
+ messages = _get_state_value(state, "messages")
+ structured_response_schema = response_format
+ if isinstance(response_format, tuple):
+ system_prompt, structured_response_schema = response_format
+ messages = [SystemMessage(content=system_prompt)] + list(messages)
+
+ resolved_model = _resolve_model(state, runtime)
+ model_with_structured_output = _get_model(
+ resolved_model
+ ).with_structured_output(
+ cast(StructuredResponseSchema, structured_response_schema)
+ )
+ response = model_with_structured_output.invoke(messages, config)
+ return {"structured_response": response}
+
+ async def agenerate_structured_response(
+ state: StateSchema, runtime: Runtime[ContextT], config: RunnableConfig
+ ) -> StateSchema:
+ messages = _get_state_value(state, "messages")
+ structured_response_schema = response_format
+ if isinstance(response_format, tuple):
+ system_prompt, structured_response_schema = response_format
+ messages = [SystemMessage(content=system_prompt)] + list(messages)
+
+ resolved_model = await _aresolve_model(state, runtime)
+ model_with_structured_output = _get_model(
+ resolved_model
+ ).with_structured_output(
+ cast(StructuredResponseSchema, structured_response_schema)
+ )
+ response = await model_with_structured_output.ainvoke(messages, config)
+ return {"structured_response": response}
+
+ if not tool_calling_enabled:
+ # Define a new graph
+ workflow = StateGraph(state_schema=state_schema, context_schema=context_schema)
+ workflow.add_node(
+ "agent",
+ RunnableCallable(call_model, acall_model),
+ input_schema=input_schema,
+ )
+ if pre_model_hook is not None:
+ workflow.add_node("pre_model_hook", pre_model_hook) # type: ignore[arg-type]
+ workflow.add_edge("pre_model_hook", "agent")
+ entrypoint = "pre_model_hook"
+ else:
+ entrypoint = "agent"
+
+ workflow.set_entry_point(entrypoint)
+
+ if post_model_hook is not None:
+ workflow.add_node("post_model_hook", post_model_hook) # type: ignore[arg-type]
+ workflow.add_edge("agent", "post_model_hook")
+
+ if response_format is not None:
+ workflow.add_node(
+ "generate_structured_response",
+ RunnableCallable(
+ generate_structured_response,
+ agenerate_structured_response,
+ ),
+ )
+ if post_model_hook is not None:
+ workflow.add_edge("post_model_hook", "generate_structured_response")
+ else:
+ workflow.add_edge("agent", "generate_structured_response")
+
+ return workflow.compile(
+ checkpointer=checkpointer,
+ store=store,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ debug=debug,
+ name=name,
+ )
+
+ # Define the function that determines whether to continue or not
+ def should_continue(state: StateSchema) -> str | list[Send]:
+ messages = _get_state_value(state, "messages")
+ last_message = messages[-1]
+ # If there is no function call, then we finish
+ if not isinstance(last_message, AIMessage) or not last_message.tool_calls:
+ if post_model_hook is not None:
+ return "post_model_hook"
+ elif response_format is not None:
+ return "generate_structured_response"
+ else:
+ return END
+ # Otherwise if there is, we continue
+ else:
+ if version == "v1":
+ return "tools"
+ elif version == "v2":
+ if post_model_hook is not None:
+ return "post_model_hook"
+ return [
+ Send(
+ "tools",
+ ToolCallWithContext(
+ __type="tool_call_with_context",
+ tool_call=call,
+ state=state,
+ ),
+ )
+ for call in last_message.tool_calls
+ ]
+
+ # Define a new graph
+ workflow = StateGraph(
+ state_schema=state_schema or AgentState, context_schema=context_schema
+ )
+
+ # Define the two nodes we will cycle between
+ workflow.add_node(
+ "agent",
+ RunnableCallable(call_model, acall_model),
+ input_schema=input_schema,
+ )
+ workflow.add_node("tools", tool_node)
+
+ # Optionally add a pre-model hook node that will be called
+ # every time before the "agent" (LLM-calling node)
+ if pre_model_hook is not None:
+ workflow.add_node("pre_model_hook", pre_model_hook) # type: ignore[arg-type]
+ workflow.add_edge("pre_model_hook", "agent")
+ entrypoint = "pre_model_hook"
+ else:
+ entrypoint = "agent"
+
+ # Set the entrypoint as `agent`
+ # This means that this node is the first one called
+ workflow.set_entry_point(entrypoint)
+
+ agent_paths = []
+ post_model_hook_paths = [entrypoint, "tools"]
+
+ # Add a post model hook node if post_model_hook is provided
+ if post_model_hook is not None:
+ workflow.add_node("post_model_hook", post_model_hook) # type: ignore[arg-type]
+ agent_paths.append("post_model_hook")
+ workflow.add_edge("agent", "post_model_hook")
+ else:
+ agent_paths.append("tools")
+
+ # Add a structured output node if response_format is provided
+ if response_format is not None:
+ workflow.add_node(
+ "generate_structured_response",
+ RunnableCallable(
+ generate_structured_response,
+ agenerate_structured_response,
+ ),
+ )
+ if post_model_hook is not None:
+ post_model_hook_paths.append("generate_structured_response")
+ else:
+ agent_paths.append("generate_structured_response")
+ else:
+ if post_model_hook is not None:
+ post_model_hook_paths.append(END)
+ else:
+ agent_paths.append(END)
+
+ if post_model_hook is not None:
+
+ def post_model_hook_router(state: StateSchema) -> str | list[Send]:
+ """Route to the next node after post_model_hook.
+
+ Routes to one of:
+ * "tools": if there are pending tool calls without a corresponding message.
+ * "generate_structured_response": if no pending tool calls exist and response_format is specified.
+ * END: if no pending tool calls exist and no response_format is specified.
+ """
+
+ messages = _get_state_value(state, "messages")
+ tool_messages = [
+ m.tool_call_id for m in messages if isinstance(m, ToolMessage)
+ ]
+ last_ai_message = next(
+ m for m in reversed(messages) if isinstance(m, AIMessage)
+ )
+ pending_tool_calls = [
+ c for c in last_ai_message.tool_calls if c["id"] not in tool_messages
+ ]
+
+ if pending_tool_calls:
+ return [
+ Send(
+ "tools",
+ ToolCallWithContext(
+ __type="tool_call_with_context",
+ tool_call=call,
+ state=state,
+ ),
+ )
+ for call in pending_tool_calls
+ ]
+ elif isinstance(messages[-1], ToolMessage):
+ return entrypoint
+ elif response_format is not None:
+ return "generate_structured_response"
+ else:
+ return END
+
+ workflow.add_conditional_edges(
+ "post_model_hook",
+ post_model_hook_router,
+ path_map=post_model_hook_paths,
+ )
+
+ workflow.add_conditional_edges(
+ "agent",
+ should_continue,
+ path_map=agent_paths,
+ )
+
+ def route_tool_responses(state: StateSchema) -> str:
+ for m in reversed(_get_state_value(state, "messages")):
+ if not isinstance(m, ToolMessage):
+ break
+ if m.name in should_return_direct:
+ return END
+
+ # handle a case of parallel tool calls where
+ # the tool w/ `return_direct` was executed in a different `Send`
+ if isinstance(m, AIMessage) and m.tool_calls:
+ if any(call["name"] in should_return_direct for call in m.tool_calls):
+ return END
+
+ return entrypoint
+
+ if should_return_direct:
+ workflow.add_conditional_edges(
+ "tools", route_tool_responses, path_map=[entrypoint, END]
+ )
+ else:
+ workflow.add_edge("tools", entrypoint)
+
+ # Finally, we compile it!
+ # This compiles it into a LangChain Runnable,
+ # meaning you can use it as you would any other runnable
+ return workflow.compile(
+ checkpointer=checkpointer,
+ store=store,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ debug=debug,
+ name=name,
+ )
+
+
+# Keep for backwards compatibility
+create_tool_calling_executor = create_react_agent
+
+__all__ = [
+ "create_react_agent",
+ "create_tool_calling_executor",
+ "AgentState",
+ "AgentStatePydantic",
+ "AgentStateWithStructuredResponse",
+ "AgentStateWithStructuredResponsePydantic",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/interrupt.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/interrupt.py
new file mode 100644
index 0000000000000000000000000000000000000000..d23c11c8565a6fc364c5eb7c31a78c9d532cb33f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/interrupt.py
@@ -0,0 +1,105 @@
+from typing import Literal
+
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+from typing_extensions import TypedDict, deprecated
+
+
+@deprecated(
+ "HumanInterruptConfig has been moved to `langchain.agents.interrupt`. Please update your import to `from langchain.agents.interrupt import HumanInterruptConfig`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class HumanInterruptConfig(TypedDict):
+ """Configuration that defines what actions are allowed for a human interrupt.
+
+ This controls the available interaction options when the graph is paused for human input.
+
+ Attributes:
+ allow_ignore: Whether the human can choose to ignore/skip the current step
+ allow_respond: Whether the human can provide a text response/feedback
+ allow_edit: Whether the human can edit the provided content/state
+ allow_accept: Whether the human can accept/approve the current state
+ """
+
+ allow_ignore: bool
+ allow_respond: bool
+ allow_edit: bool
+ allow_accept: bool
+
+
+@deprecated(
+ "ActionRequest has been moved to `langchain.agents.interrupt`. Please update your import to `from langchain.agents.interrupt import ActionRequest`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class ActionRequest(TypedDict):
+ """Represents a request for human action within the graph execution.
+
+ Contains the action type and any associated arguments needed for the action.
+
+ Attributes:
+ action: The type or name of action being requested (e.g., `"Approve XYZ action"`)
+ args: Key-value pairs of arguments needed for the action
+ """
+
+ action: str
+ args: dict
+
+
+@deprecated(
+ "HumanInterrupt has been moved to `langchain.agents.interrupt`. Please update your import to `from langchain.agents.interrupt import HumanInterrupt`.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class HumanInterrupt(TypedDict):
+ """Represents an interrupt triggered by the graph that requires human intervention.
+
+ This is passed to the `interrupt` function when execution is paused for human input.
+
+ Attributes:
+ action_request: The specific action being requested from the human
+ config: Configuration defining what actions are allowed
+ description: Optional detailed description of what input is needed
+
+ Example:
+ ```python
+ # Extract a tool call from the state and create an interrupt request
+ request = HumanInterrupt(
+ action_request=ActionRequest(
+ action="run_command", # The action being requested
+ args={"command": "ls", "args": ["-l"]} # Arguments for the action
+ ),
+ config=HumanInterruptConfig(
+ allow_ignore=True, # Allow skipping this step
+ allow_respond=True, # Allow text feedback
+ allow_edit=False, # Don't allow editing
+ allow_accept=True # Allow direct acceptance
+ ),
+ description="Please review the command before execution"
+ )
+ # Send the interrupt request and get the response
+ response = interrupt([request])[0]
+ ```
+ """
+
+ action_request: ActionRequest
+ config: HumanInterruptConfig
+ description: str | None
+
+
+class HumanResponse(TypedDict):
+ """The response provided by a human to an interrupt, which is returned when graph execution resumes.
+
+ Attributes:
+ type: The type of response:
+
+ - `'accept'`: Approves the current state without changes
+ - `'ignore'`: Skips/ignores the current step
+ - `'response'`: Provides text feedback or instructions
+ - `'edit'`: Modifies the current state/content
+ args: The response payload:
+
+ - `None`: For ignore/accept actions
+ - `str`: For text responses
+ - `ActionRequest`: For edit actions with updated content
+ """
+
+ type: Literal["accept", "ignore", "response", "edit"]
+ args: None | str | ActionRequest
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/py.typed b/python/user_packages/Python313/site-packages/langgraph/prebuilt/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_node.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_node.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5aa4d86d25e9df99d4627b4fb4adfc403011deb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_node.py
@@ -0,0 +1,2030 @@
+"""Tool execution node for LangGraph workflows.
+
+This module provides prebuilt functionality for executing tools in LangGraph.
+
+Tools are functions that models can call to interact with external systems,
+APIs, databases, or perform computations.
+
+The module implements design patterns for:
+
+- Parallel execution of multiple tool calls for efficiency
+- Robust error handling with customizable error messages
+- State injection for tools that need access to graph state
+- Store injection for tools that need persistent storage
+- Command-based state updates for advanced control flow
+
+Key Components:
+
+- [`ToolNode`][langgraph.prebuilt.ToolNode]: Main class for executing tools in LangGraph workflows
+- [`InjectedState`][langgraph.prebuilt.InjectedState]: Annotation for injecting graph state into tools
+- [`InjectedStore`][langgraph.prebuilt.InjectedStore]: Annotation for injecting persistent store into tools
+- [`ToolRuntime`][langgraph.prebuilt.ToolRuntime]: Runtime information for tools, bundling together `state`, `context`,
+ `config`, `stream_writer`, `tool_call_id`, and `store`
+- [`tools_condition`][langgraph.prebuilt.tools_condition]: Utility function for conditional routing based on tool calls
+
+Typical Usage:
+ ```python
+ from langchain_core.tools import tool
+ from langchain.tools import ToolNode
+
+
+ @tool
+ def my_tool(x: int) -> str:
+ return f"Result: {x}"
+
+
+ tool_node = ToolNode([my_tool])
+ ```
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+from collections.abc import Awaitable, Callable
+from copy import copy, deepcopy
+from dataclasses import dataclass, field, replace
+from types import UnionType
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Generic,
+ Literal,
+ TypedDict,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ RemoveMessage,
+ ToolCall,
+ ToolMessage,
+ convert_to_messages,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ get_config_list,
+ get_executor_for_config,
+)
+from langchain_core.tools import BaseTool, InjectedToolArg
+from langchain_core.tools import tool as create_tool
+from langchain_core.tools.base import (
+ TOOL_MESSAGE_BLOCK_TYPES,
+ ToolException,
+ _DirectlyInjectedToolArg,
+ _is_injected_arg_type,
+ get_all_basemodel_annotations,
+)
+from langgraph._internal._constants import CONF, CONFIG_KEY_READ
+from langgraph._internal._runnable import RunnableCallable
+from langgraph.errors import GraphBubbleUp
+from langgraph.graph.message import REMOVE_ALL_MESSAGES
+from langgraph.pregel._tools import _tool_call_writer
+from langgraph.runtime import ExecutionInfo, ServerInfo # noqa: TC002
+from langgraph.store.base import BaseStore # noqa: TC002
+from langgraph.types import Command, Send, StreamWriter
+from pydantic import BaseModel, ValidationError
+from typing_extensions import TypeVar, Unpack
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langgraph.runtime import Runtime
+ from pydantic_core import ErrorDetails
+
+# right now we use a dict as the default, can change this to AgentState, but depends
+# on if this lives in LangChain or LangGraph... ideally would have some typed
+# messages key
+StateT = TypeVar("StateT", default=dict)
+ContextT = TypeVar("ContextT", default=None)
+
+INVALID_TOOL_NAME_ERROR_TEMPLATE = (
+ "Error: {requested_tool} is not a valid tool, try one of [{available_tools}]."
+)
+TOOL_CALL_ERROR_TEMPLATE = "Error: {error}\n Please fix your mistakes."
+TOOL_EXECUTION_ERROR_TEMPLATE = (
+ "Error executing tool '{tool_name}' with kwargs {tool_kwargs} with error:\n"
+ " {error}\n"
+ " Please fix the error and try again."
+)
+TOOL_INVOCATION_ERROR_TEMPLATE = (
+ "Error invoking tool '{tool_name}' with kwargs {tool_kwargs} with error:\n"
+ " {error}\n"
+ " Please fix the error and try again."
+)
+
+
+class _ToolCallRequestOverrides(TypedDict, total=False):
+ """Possible overrides for ToolCallRequest.override() method."""
+
+ tool_call: ToolCall
+ tool: BaseTool
+ state: Any
+
+
+@dataclass
+class ToolCallRequest:
+ """Tool execution request passed to tool call interceptors.
+
+ Attributes:
+ tool_call: Tool call dict with name, args, and id from model output.
+ tool: BaseTool instance to be invoked, or None if tool is not
+ registered with the `ToolNode`. When tool is `None`, interceptors can
+ handle the request without validation. If the interceptor calls `execute()`,
+ validation will occur and raise an error for unregistered tools.
+ state: Agent state (`dict`, `list`, or `BaseModel`).
+ runtime: LangGraph runtime context (optional, `None` if outside graph).
+ """
+
+ tool_call: ToolCall
+ tool: BaseTool | None
+ state: Any
+ runtime: ToolRuntime
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ """Raise deprecation warning when setting attributes directly.
+
+ Direct attribute assignment is deprecated. Use the `override()` method instead.
+ """
+ import warnings
+
+ # Allow setting attributes during initialization
+ if not hasattr(self, "__dataclass_fields__") or not hasattr(self, name):
+ object.__setattr__(self, name, value)
+ else:
+ warnings.warn(
+ f"Setting attribute '{name}' on ToolCallRequest is deprecated. "
+ "Use the override() method instead to create a new instance with modified values.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ object.__setattr__(self, name, value)
+
+ def override(
+ self, **overrides: Unpack[_ToolCallRequestOverrides]
+ ) -> ToolCallRequest:
+ """Replace the request with a new request with the given overrides.
+
+ Returns a new `ToolCallRequest` instance with the specified attributes replaced.
+ This follows an immutable pattern, leaving the original request unchanged.
+
+ Args:
+ **overrides: Keyword arguments for attributes to override.
+
+ Supported keys:
+
+ - tool_call: Tool call dict with `name`, `args`, and `id`
+ - state: Agent state (`dict`, `list`, or `BaseModel`)
+
+ Returns:
+ New ToolCallRequest instance with specified overrides applied.
+
+ Examples:
+ ```python
+ # Modify tool call arguments without mutating original
+ modified_call = {**request.tool_call, "args": {"value": 10}}
+ new_request = request.override(tool_call=modified_call)
+
+ # Override multiple attributes
+ new_request = request.override(tool_call=modified_call, state=new_state)
+ ```
+ """
+ return replace(self, **overrides)
+
+
+ToolCallWrapper = Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], ToolMessage | Command]],
+ ToolMessage | Command,
+]
+"""Wrapper for tool call execution with multi-call support.
+
+Wrapper receives:
+ request: ToolCallRequest with tool_call, tool, state, and runtime.
+ execute: Callable to execute the tool (CAN BE CALLED MULTIPLE TIMES).
+
+Returns:
+ ToolMessage or Command (the final result).
+
+The execute callable can be invoked multiple times for retry logic,
+with potentially modified requests each time. Each call to execute
+is independent and stateless.
+
+!!! note
+ When implementing middleware for `create_agent`, use
+ `AgentMiddleware.wrap_tool_call` which provides properly typed
+ state parameter for better type safety.
+
+Examples:
+ Passthrough (execute once):
+
+ def handler(request, execute):
+ return execute(request)
+
+ Modify request before execution:
+
+ ```python
+ def handler(request, execute):
+ modified_call = {**request.tool_call, "args": {**request.tool_call["args"], "value": request.tool_call["args"]["value"] * 2}}
+ modified_request = request.override(tool_call=modified_call)
+ return execute(modified_request)
+ ```
+
+ Retry on error (execute multiple times):
+
+ ```python
+ def handler(request, execute):
+ for attempt in range(3):
+ try:
+ result = execute(request)
+ if is_valid(result):
+ return result
+ except Exception:
+ if attempt == 2:
+ raise
+ return result
+ ```
+
+ Conditional retry based on response:
+
+ ```python
+ def handler(request, execute):
+ for attempt in range(3):
+ result = execute(request)
+ if isinstance(result, ToolMessage) and result.status != "error":
+ return result
+ if attempt < 2:
+ continue
+ return result
+ ```
+
+ Cache/short-circuit without calling execute:
+
+ ```python
+ def handler(request, execute):
+ if cached := get_cache(request):
+ return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
+ result = execute(request)
+ save_cache(request, result)
+ return result
+ ```
+"""
+
+AsyncToolCallWrapper = Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+]
+"""Async wrapper for tool call execution with multi-call support."""
+
+
+class ToolCallWithContext(TypedDict):
+ """ToolCall with additional context for graph state.
+
+ This is an internal data structure meant to help the `ToolNode` accept
+ tool calls with additional context (e.g. state) when dispatched using the
+ Send API.
+
+ The Send API is used in create_agent to distribute tool calls in parallel
+ and support human-in-the-loop workflows where graph execution may be paused
+ for an indefinite time.
+ """
+
+ tool_call: ToolCall
+ __type: Literal["tool_call_with_context"]
+ """Type to parameterize the payload.
+
+ Using "__" as a prefix to be defensive against potential name collisions with
+ regular user state.
+ """
+ state: Any
+ """The state is provided as additional context."""
+
+
+def msg_content_output(output: Any) -> str | list[dict]:
+ """Convert tool output to `ToolMessage` content format.
+
+ Handles `str`, `list[dict]` (content blocks), and arbitrary objects by attempting
+ JSON serialization with fallback to str().
+
+ Args:
+ output: Tool execution output of any type.
+
+ Returns:
+ String or list of content blocks suitable for `ToolMessage.content`.
+ """
+ if isinstance(output, str) or (
+ isinstance(output, list)
+ and all(
+ isinstance(x, dict) and x.get("type") in TOOL_MESSAGE_BLOCK_TYPES
+ for x in output
+ )
+ ):
+ return output
+ # Technically a list of strings is also valid message content, but it's
+ # not currently well tested that all chat models support this.
+ # And for backwards compatibility we want to make sure we don't break
+ # any existing ToolNode usage.
+ try:
+ return json.dumps(output, ensure_ascii=False)
+ except Exception: # noqa: BLE001
+ return str(output)
+
+
+class ToolInvocationError(ToolException):
+ """An error occurred while invoking a tool due to invalid arguments.
+
+ This exception is only raised when invoking a tool using the `ToolNode`!
+ """
+
+ def __init__(
+ self,
+ tool_name: str,
+ source: ValidationError,
+ tool_kwargs: dict[str, Any],
+ filtered_errors: list[ErrorDetails] | None = None,
+ ) -> None:
+ """Initialize the ToolInvocationError.
+
+ Args:
+ tool_name: The name of the tool that failed.
+ source: The exception that occurred.
+ tool_kwargs: The keyword arguments that were passed to the tool.
+ filtered_errors: Optional list of filtered validation errors excluding
+ injected arguments.
+ """
+ # Format error display based on filtered errors if provided
+ if filtered_errors is not None:
+ # Manually format the filtered errors without URLs or fancy formatting
+ error_str_parts = []
+ for error in filtered_errors:
+ loc_str = ".".join(str(loc) for loc in error.get("loc", ()))
+ msg = error.get("msg", "Unknown error")
+ error_str_parts.append(f"{loc_str}: {msg}")
+ error_display_str = "\n".join(error_str_parts)
+ else:
+ error_display_str = str(source)
+
+ self.message = TOOL_INVOCATION_ERROR_TEMPLATE.format(
+ tool_name=tool_name, tool_kwargs=tool_kwargs, error=error_display_str
+ )
+ self.tool_name = tool_name
+ self.tool_kwargs = tool_kwargs
+ self.source = source
+ self.filtered_errors = filtered_errors
+ super().__init__(self.message)
+
+
+def _default_handle_tool_errors(e: Exception) -> str:
+ """Default error handler for tool errors.
+
+ If the tool is a tool invocation error, return its message.
+ Otherwise, raise the error.
+ """
+ if isinstance(e, ToolInvocationError):
+ return e.message
+ raise e
+
+
+def _handle_tool_error(
+ e: Exception,
+ *,
+ flag: bool
+ | str
+ | Callable[..., str]
+ | type[Exception]
+ | tuple[type[Exception], ...],
+) -> str:
+ """Generate error message content based on exception handling configuration.
+
+ This function centralizes error message generation logic, supporting different
+ error handling strategies configured via the `ToolNode`'s `handle_tool_errors`
+ parameter.
+
+ Args:
+ e: The exception that occurred during tool execution.
+ flag: Configuration for how to handle the error. Can be:
+ - bool: If `True`, use default error template
+ - str: Use this string as the error message
+ - Callable: Call this function with the exception to get error message
+ - tuple: Not used in this context (handled by caller)
+
+ Returns:
+ A string containing the error message to include in the `ToolMessage`.
+
+ Raises:
+ ValueError: If flag is not one of the supported types.
+
+ !!! note
+ The tuple case is handled by the caller through exception type checking,
+ not by this function directly.
+ """
+ if isinstance(flag, (bool, tuple)) or (
+ isinstance(flag, type) and issubclass(flag, Exception)
+ ):
+ content = TOOL_CALL_ERROR_TEMPLATE.format(error=repr(e))
+ elif isinstance(flag, str):
+ content = flag
+ elif callable(flag):
+ content = flag(e) # type: ignore [assignment, call-arg]
+ else:
+ msg = (
+ f"Got unexpected type of `handle_tool_error`. Expected bool, str "
+ f"or callable. Received: {flag}"
+ )
+ raise ValueError(msg)
+ return content
+
+
+def _infer_handled_types(handler: Callable[..., str]) -> tuple[type[Exception], ...]:
+ """Infer exception types handled by a custom error handler function.
+
+ This function analyzes the type annotations of a custom error handler to determine
+ which exception types it's designed to handle. This enables type-safe error handling
+ where only specific exceptions are caught and processed by the handler.
+
+ Args:
+ handler: A callable that takes an exception and returns an error message string.
+ The first parameter (after self/cls if present) should be type-annotated
+ with the exception type(s) to handle.
+
+ Returns:
+ A tuple of exception types that the handler can process. Returns (Exception,)
+ if no specific type information is available for backward compatibility.
+
+ Raises:
+ ValueError: If the handler's annotation contains non-Exception types or
+ if Union types contain non-Exception types.
+
+ !!! note
+ This function supports both single exception types and Union types for
+ handlers that need to handle multiple exception types differently.
+ """
+ sig = inspect.signature(handler)
+ params = list(sig.parameters.values())
+ if params:
+ # If it's a method, the first argument is typically 'self' or 'cls'
+ if params[0].name in ["self", "cls"] and len(params) == 2:
+ first_param = params[1]
+ else:
+ first_param = params[0]
+
+ type_hints = get_type_hints(handler)
+ if first_param.name in type_hints:
+ origin = get_origin(first_param.annotation)
+ if origin in [Union, UnionType]:
+ args = get_args(first_param.annotation)
+ if all(issubclass(arg, Exception) for arg in args):
+ return tuple(args)
+ msg = (
+ "All types in the error handler error annotation must be "
+ "Exception types. For example, "
+ "`def custom_handler(e: Union[ValueError, TypeError])`. "
+ f"Got '{first_param.annotation}' instead."
+ )
+ raise ValueError(msg)
+
+ exception_type = type_hints[first_param.name]
+ if Exception in exception_type.__mro__:
+ return (exception_type,)
+ msg = (
+ f"Arbitrary types are not supported in the error handler "
+ f"signature. Please annotate the error with either a "
+ f"specific Exception type or a union of Exception types. "
+ "For example, `def custom_handler(e: ValueError)` or "
+ "`def custom_handler(e: Union[ValueError, TypeError])`. "
+ f"Got '{exception_type}' instead."
+ )
+ raise ValueError(msg)
+
+ # If no type information is available, return (Exception,)
+ # for backwards compatibility.
+ return (Exception,)
+
+
+def _filter_validation_errors(
+ validation_error: ValidationError,
+ injected_args: _InjectedArgs | None,
+) -> list[ErrorDetails]:
+ """Filter validation errors to only include LLM-controlled arguments.
+
+ When a tool invocation fails validation, only errors for arguments that the LLM
+ controls should be included in error messages. This ensures the LLM receives
+ focused, actionable feedback about parameters it can actually fix. System-injected
+ arguments (state, store, runtime) are filtered out since the LLM has no control
+ over them.
+
+ This function also removes injected argument values from the `input` field in error
+ details, ensuring that only LLM-provided arguments appear in error messages.
+
+ Args:
+ validation_error: The Pydantic ValidationError raised during tool invocation.
+ injected_args: The _InjectedArgs structure containing all injected arguments,
+ or None if there are no injected arguments.
+
+ Returns:
+ List of ErrorDetails containing only errors for LLM-controlled arguments,
+ with system-injected argument values removed from the input field.
+ """
+ # Collect all injected argument names
+ injected_arg_names: set[str] = set()
+ if injected_args:
+ if injected_args.state:
+ injected_arg_names.update(injected_args.state.keys())
+ if injected_args.store:
+ injected_arg_names.add(injected_args.store)
+ if injected_args.runtime:
+ injected_arg_names.add(injected_args.runtime)
+
+ filtered_errors: list[ErrorDetails] = []
+ for error in validation_error.errors():
+ # Check if error location contains any injected argument
+ # error['loc'] is a tuple like ('field_name',) or ('field_name', 'nested_field')
+ if error["loc"] and error["loc"][0] not in injected_arg_names:
+ # Create a copy of the error dict to avoid mutating the original
+ error_copy: dict[str, Any] = {**error}
+
+ # Remove injected arguments from input_value if it's a dict
+ if isinstance(error_copy.get("input"), dict):
+ input_dict = error_copy["input"]
+ input_copy = {
+ k: v for k, v in input_dict.items() if k not in injected_arg_names
+ }
+ error_copy["input"] = input_copy
+
+ # Cast is safe because ErrorDetails is a TypedDict compatible with this structure
+ filtered_errors.append(error_copy) # type: ignore[arg-type]
+
+ return filtered_errors
+
+
+@dataclass
+class _InjectedArgs:
+ """Internal structure for tracking injected arguments for a tool.
+
+ This data structure is built once during ToolNode initialization by analyzing
+ the tool's signature and args schema, then reused during execution for efficient
+ injection without repeated reflection.
+
+ The structure maps from tool parameter names to their injection sources, enabling
+ the ToolNode to know exactly which arguments need to be injected and where to
+ get their values from.
+
+ Attributes:
+ state: Mapping from tool parameter names to state field names for injection.
+ Keys are tool parameter names, values are either:
+ - str: Name of the state field to extract and inject
+ - None: Inject the entire state object
+ Empty dict if no state injection is needed.
+ store: Name of the tool parameter where the store should be injected,
+ or None if no store injection is needed.
+ runtime: Name of the tool parameter where the runtime should be injected,
+ or None if no runtime injection is needed.
+
+ Example:
+ For a tool with signature:
+ ```python
+ def my_tool(
+ x: int,
+ messages: Annotated[list, InjectedState("messages")],
+ full_state: Annotated[dict, InjectedState()],
+ store: Annotated[BaseStore, InjectedStore()],
+ runtime: ToolRuntime,
+ ) -> str:
+ ...
+ ```
+
+ The resulting `_InjectedArgs` would be:
+ ```python
+ _InjectedArgs(
+ state={
+ "messages": "messages", # Extract state["messages"]
+ "full_state": None, # Inject entire state
+ },
+ store="store", # Inject into "store" parameter
+ runtime="runtime", # Inject into "runtime" parameter
+ )
+ ```
+ """
+
+ state: dict[str, str | None]
+ store: str | None
+ runtime: str | None
+ all_injected_keys: set[str]
+ _optional_state_args: set[str]
+
+
+class ToolNode(RunnableCallable):
+ """A node for executing tools in LangGraph workflows.
+
+ Handles tool execution patterns including function calls, state injection,
+ persistent storage, and control flow. Manages parallel execution,
+ error handling.
+
+ Use `ToolNode` when building custom workflows that require fine-grained control over
+ tool execution—for example, custom routing logic, specialized error handling, or
+ non-standard agent architectures.
+
+ For standard ReAct-style agents, use [`create_agent`][langchain.agents.create_agent]
+ instead. It uses `ToolNode` internally with sensible defaults for the agent loop,
+ conditional routing, and error handling.
+
+ Input Formats:
+ 1. **Graph state** with `messages` key that has a list of messages:
+ - Common representation for agentic workflows
+ - Supports custom messages key via `messages_key` parameter
+
+ 2. **Message List**: `[AIMessage(..., tool_calls=[...])]`
+ - List of messages with tool calls in the last AIMessage
+
+ 3. **Direct Tool Calls**: `[{"name": "tool", "args": {...}, "id": "1", "type": "tool_call"}]`
+ - Bypasses message parsing for direct tool execution
+ - For programmatic tool invocation and testing
+
+ Output Formats:
+ Output format depends on input type and tool behavior:
+
+ **For Regular tools**:
+
+ - Dict input → `{"messages": [ToolMessage(...)]}`
+ - List input → `[ToolMessage(...)]`
+
+ **For Command tools**:
+
+ - Returns `[Command(...)]` or mixed list with regular tool outputs
+ - `Command` can update state, trigger navigation, or send messages
+
+ Args:
+ tools: A sequence of tools that can be invoked by this node.
+
+ Supports:
+
+ - **BaseTool instances**: Tools with schemas and metadata
+ - **Plain functions**: Automatically converted to tools with inferred schemas
+
+ name: The name identifier for this node in the graph. Used for debugging
+ and visualization.
+ tags: Optional metadata tags to associate with the node for filtering
+ and organization.
+ handle_tool_errors: Configuration for error handling during tool execution.
+ Supports multiple strategies:
+
+ - `True`: Catch all errors and return a `ToolMessage` with the default
+ error template containing the exception details.
+ - `str`: Catch all errors and return a `ToolMessage` with this custom
+ error message string.
+ - `type[Exception]`: Only catch exceptions with the specified type and
+ return the default error message for it.
+ - `tuple[type[Exception], ...]`: Only catch exceptions with the specified
+ types and return default error messages for them.
+ - `Callable[..., str]`: Catch exceptions matching the callable's signature
+ and return the string result of calling it with the exception.
+ - `False`: Disable error handling entirely, allowing exceptions to
+ propagate.
+
+ Defaults to a callable that:
+
+ - Catches tool invocation errors (due to invalid arguments provided by the
+ model) and returns a descriptive error message
+ - Ignores tool execution errors (they will be re-raised)
+
+ messages_key: The key in the state dictionary that contains the message list.
+ This same key will be used for the output `ToolMessage` objects.
+
+ Allows custom state schemas with different message field names.
+
+ Examples:
+ Basic usage:
+
+ ```python
+ from langchain.tools import ToolNode
+ from langchain_core.tools import tool
+
+ @tool
+ def calculator(a: int, b: int) -> int:
+ \"\"\"Add two numbers.\"\"\"
+ return a + b
+
+ tool_node = ToolNode([calculator])
+ ```
+
+ State injection:
+
+ ```python
+ from typing_extensions import Annotated
+ from langchain.tools import InjectedState
+
+ @tool
+ def context_tool(query: str, state: Annotated[dict, InjectedState]) -> str:
+ \"\"\"Some tool that uses state.\"\"\"
+ return f"Query: {query}, Messages: {len(state['messages'])}"
+
+ tool_node = ToolNode([context_tool])
+ ```
+
+ Error handling:
+
+ ```python
+ def handle_errors(e: ValueError) -> str:
+ return "Invalid input provided"
+
+
+ tool_node = ToolNode([my_tool], handle_tool_errors=handle_errors)
+ ```
+ """ # noqa: E501
+
+ name: str = "tools"
+
+ def __init__(
+ self,
+ tools: Sequence[BaseTool | Callable],
+ *,
+ name: str = "tools",
+ tags: list[str] | None = None,
+ handle_tool_errors: bool
+ | str
+ | Callable[..., str]
+ | type[Exception]
+ | tuple[type[Exception], ...] = _default_handle_tool_errors,
+ messages_key: str = "messages",
+ wrap_tool_call: ToolCallWrapper | None = None,
+ awrap_tool_call: AsyncToolCallWrapper | None = None,
+ ) -> None:
+ """Initialize `ToolNode` with tools and configuration.
+
+ Args:
+ tools: Sequence of tools to make available for execution.
+ name: Node name for graph identification.
+ tags: Optional metadata tags.
+ handle_tool_errors: Error handling configuration.
+ messages_key: State key containing messages.
+ wrap_tool_call: Sync wrapper function to intercept tool execution. Receives
+ ToolCallRequest and execute callable, returns ToolMessage or Command.
+ Enables retries, caching, request modification, and control flow.
+ awrap_tool_call: Async wrapper function to intercept tool execution.
+ If not provided, falls back to wrap_tool_call for async execution.
+ """
+ super().__init__(self._func, self._afunc, name=name, tags=tags, trace=False)
+ self._tools_by_name: dict[str, BaseTool] = {}
+ self._injected_args: dict[str, _InjectedArgs] = {}
+ self._handle_tool_errors = handle_tool_errors
+ self._messages_key = messages_key
+ self._wrap_tool_call = wrap_tool_call
+ self._awrap_tool_call = awrap_tool_call
+ for tool in tools:
+ if not isinstance(tool, BaseTool):
+ tool_ = create_tool(cast("type[BaseTool]", tool))
+ else:
+ tool_ = tool
+ self._tools_by_name[tool_.name] = tool_
+ # Build injected args mapping once during initialization in a single pass
+ self._injected_args[tool_.name] = _get_all_injected_args(tool_)
+
+ @property
+ def tools_by_name(self) -> dict[str, BaseTool]:
+ """Mapping from tool name to BaseTool instance."""
+ return self._tools_by_name
+
+ def _func(
+ self,
+ input: list[AnyMessage] | dict[str, Any] | BaseModel,
+ config: RunnableConfig,
+ runtime: Runtime,
+ ) -> Any:
+ tool_calls, input_type = self._parse_input(input)
+ config_list = get_config_list(config, len(tool_calls))
+
+ # Construct ToolRuntime instances at the top level for each tool call
+ tool_runtimes = []
+ for call, cfg in zip(tool_calls, config_list, strict=False):
+ state = self._extract_state(input, cfg)
+ tool_runtime = ToolRuntime(
+ state=state,
+ tool_call_id=call["id"],
+ config=cfg,
+ context=runtime.context,
+ store=runtime.store,
+ stream_writer=runtime.stream_writer,
+ tools=list(self.tools_by_name.values()),
+ execution_info=runtime.execution_info,
+ server_info=runtime.server_info,
+ )
+ tool_runtimes.append(tool_runtime)
+
+ # Pass original tool calls without injection
+ input_types = [input_type] * len(tool_calls)
+ with get_executor_for_config(config) as executor:
+ outputs = list(
+ executor.map(self._run_one, tool_calls, input_types, tool_runtimes)
+ )
+
+ return self._combine_tool_outputs(outputs, input_type)
+
+ async def _afunc(
+ self,
+ input: list[AnyMessage] | dict[str, Any] | BaseModel,
+ config: RunnableConfig,
+ runtime: Runtime,
+ ) -> Any:
+ tool_calls, input_type = self._parse_input(input)
+ config_list = get_config_list(config, len(tool_calls))
+
+ # Construct ToolRuntime instances at the top level for each tool call
+ tool_runtimes = []
+ for call, cfg in zip(tool_calls, config_list, strict=False):
+ state = self._extract_state(input, cfg)
+ tool_runtime = ToolRuntime(
+ state=state,
+ tool_call_id=call["id"],
+ config=cfg,
+ context=runtime.context,
+ store=runtime.store,
+ stream_writer=runtime.stream_writer,
+ tools=list(self.tools_by_name.values()),
+ execution_info=runtime.execution_info,
+ server_info=runtime.server_info,
+ )
+ tool_runtimes.append(tool_runtime)
+
+ # Pass original tool calls without injection
+ coros = []
+ for call, tool_runtime in zip(tool_calls, tool_runtimes, strict=False):
+ coros.append(self._arun_one(call, input_type, tool_runtime)) # type: ignore[arg-type]
+ outputs = await asyncio.gather(*coros)
+
+ return self._combine_tool_outputs(outputs, input_type)
+
+ def _combine_tool_outputs(
+ self,
+ outputs: list[ToolMessage | Command | list[ToolMessage | Command]],
+ input_type: Literal["list", "dict", "tool_calls"],
+ ) -> list[Command | list[ToolMessage] | dict[str, list[ToolMessage]]]:
+ # Flatten list entries from tools that returned multiple items
+ flat_outputs: list[ToolMessage | Command]
+ if any(isinstance(output, list) for output in outputs):
+ flat_outputs = []
+ for output in outputs:
+ if isinstance(output, list):
+ flat_outputs.extend(output)
+ else:
+ flat_outputs.append(output)
+ else:
+ flat_outputs = cast("list[ToolMessage | Command]", outputs)
+
+ # preserve existing behavior for non-command tool outputs for backwards
+ # compatibility
+ if not any(isinstance(output, Command) for output in flat_outputs):
+ # TypedDict, pydantic, dataclass, etc. should all be able to load from dict
+ return (
+ flat_outputs
+ if input_type == "list"
+ else {self._messages_key: flat_outputs}
+ )
+
+ # LangGraph will automatically handle list of Command and non-command node
+ # updates
+ combined_outputs: list[
+ Command | list[ToolMessage] | dict[str, list[ToolMessage]]
+ ] = []
+
+ # combine all parent commands with goto into a single parent command
+ parent_command: Command | None = None
+ for output in flat_outputs:
+ if isinstance(output, Command):
+ if (
+ output.graph is Command.PARENT
+ and isinstance(output.goto, list)
+ and all(isinstance(send, Send) for send in output.goto)
+ ):
+ if parent_command:
+ parent_command = replace(
+ parent_command,
+ goto=cast("list[Send]", parent_command.goto) + output.goto,
+ )
+ else:
+ parent_command = Command(graph=Command.PARENT, goto=output.goto)
+ else:
+ combined_outputs.append(output)
+ else:
+ combined_outputs.append(
+ [output] if input_type == "list" else {self._messages_key: [output]}
+ )
+
+ if parent_command:
+ combined_outputs.append(parent_command)
+ return combined_outputs
+
+ def _execute_tool_sync(
+ self,
+ request: ToolCallRequest,
+ input_type: Literal["list", "dict", "tool_calls"],
+ config: RunnableConfig,
+ ) -> ToolMessage | Command | list[Command | ToolMessage]:
+ """Execute tool call with configured error handling.
+
+ Args:
+ request: Tool execution request.
+ input_type: Input format.
+ config: Runnable configuration.
+
+ Returns:
+ ToolMessage, Command, or list of Command/ToolMessage.
+
+ Raises:
+ Exception: If tool fails and handle_tool_errors is False.
+ """
+ call = request.tool_call
+ tool = request.tool
+
+ # Validate tool exists when we actually need to execute it
+ if tool is None:
+ if invalid_tool_message := self._validate_tool_call(call):
+ return invalid_tool_message
+ # This should never happen if validation works correctly
+ msg = f"Tool {call['name']} is not registered with ToolNode"
+ raise TypeError(msg)
+
+ # Inject state, store, and runtime right before invocation
+ injected_call = self._inject_tool_args(call, request.runtime, tool)
+ call_args = {**injected_call, "type": "tool_call"}
+
+ try:
+ try:
+ response = tool.invoke(call_args, config)
+ except ValidationError as exc:
+ # Filter out errors for injected arguments
+ injected = self._injected_args.get(call["name"])
+ filtered_errors = _filter_validation_errors(exc, injected)
+ # Use original call["args"] without injected values for error reporting
+ raise ToolInvocationError(
+ call["name"], exc, call["args"], filtered_errors
+ ) from exc
+
+ # Inside try so validation errors route through _handle_tool_errors
+ return self._normalize_tool_response(
+ response, request.tool_call, input_type
+ )
+
+ # GraphInterrupt is a special exception that will always be raised.
+ # It can be triggered in the following scenarios,
+ # Where GraphInterrupt(GraphBubbleUp) is raised from an `interrupt` invocation
+ # most commonly:
+ # (1) a GraphInterrupt is raised inside a tool
+ # (2) a GraphInterrupt is raised inside a graph node for a graph called as a tool
+ # (3) a GraphInterrupt is raised when a subgraph is interrupted inside a graph
+ # called as a tool
+ # (2 and 3 can happen in a "supervisor w/ tools" multi-agent architecture)
+ except GraphBubbleUp:
+ raise
+ except Exception as e:
+ # Determine which exception types are handled
+ handled_types: tuple[type[Exception], ...]
+ if isinstance(self._handle_tool_errors, type) and issubclass(
+ self._handle_tool_errors, Exception
+ ):
+ handled_types = (self._handle_tool_errors,)
+ elif isinstance(self._handle_tool_errors, tuple):
+ handled_types = self._handle_tool_errors
+ elif callable(self._handle_tool_errors) and not isinstance(
+ self._handle_tool_errors, type
+ ):
+ handled_types = _infer_handled_types(self._handle_tool_errors)
+ else:
+ # default behavior is catching all exceptions
+ handled_types = (Exception,)
+
+ # Check if this error should be handled
+ if not self._handle_tool_errors or not isinstance(e, handled_types):
+ raise
+
+ # Error is handled - create error ToolMessage
+ content = _handle_tool_error(e, flag=self._handle_tool_errors)
+ return ToolMessage(
+ content=content,
+ name=call["name"],
+ tool_call_id=call["id"],
+ status="error",
+ )
+
+ def _run_one(
+ self,
+ call: ToolCall,
+ input_type: Literal["list", "dict", "tool_calls"],
+ tool_runtime: ToolRuntime,
+ ) -> ToolMessage | Command | list[Command | ToolMessage]:
+ """Execute single tool call with wrap_tool_call wrapper if configured.
+
+ Args:
+ call: Tool call dict.
+ input_type: Input format.
+ tool_runtime: Tool runtime.
+
+ Returns:
+ ToolMessage or Command.
+ """
+ # Validation is deferred to _execute_tool_sync to allow interceptors
+ # to short-circuit requests for unregistered tools
+ tool = self.tools_by_name.get(call["name"])
+
+ # Create the tool request with state and runtime
+ tool_request = ToolCallRequest(
+ tool_call=call,
+ tool=tool,
+ state=tool_runtime.state,
+ runtime=tool_runtime,
+ )
+
+ config = tool_runtime.config
+
+ if self._wrap_tool_call is None:
+ # No wrapper - execute directly
+ return self._execute_tool_sync(tool_request, input_type, config)
+
+ # Define execute callable that can be called multiple times
+ def execute(req: ToolCallRequest) -> ToolMessage | Command:
+ """Execute tool with given request. Can be called multiple times."""
+ return self._execute_tool_sync(req, input_type, config)
+
+ # Call wrapper with request and execute callable
+ try:
+ return self._wrap_tool_call(tool_request, execute)
+ except Exception as e:
+ # Wrapper threw an exception
+ if not self._handle_tool_errors:
+ raise
+ # Convert to error message
+ content = _handle_tool_error(e, flag=self._handle_tool_errors)
+ return ToolMessage(
+ content=content,
+ name=tool_request.tool_call["name"],
+ tool_call_id=tool_request.tool_call["id"],
+ status="error",
+ )
+
+ async def _execute_tool_async(
+ self,
+ request: ToolCallRequest,
+ input_type: Literal["list", "dict", "tool_calls"],
+ config: RunnableConfig,
+ ) -> ToolMessage | Command | list[Command | ToolMessage]:
+ """Execute tool call asynchronously with configured error handling.
+
+ Args:
+ request: Tool execution request.
+ input_type: Input format.
+ config: Runnable configuration.
+
+ Returns:
+ ToolMessage, Command, or list of Command/ToolMessage.
+
+ Raises:
+ Exception: If tool fails and handle_tool_errors is False.
+ """
+ call = request.tool_call
+ tool = request.tool
+
+ # Validate tool exists when we actually need to execute it
+ if tool is None:
+ if invalid_tool_message := self._validate_tool_call(call):
+ return invalid_tool_message
+ # This should never happen if validation works correctly
+ msg = f"Tool {call['name']} is not registered with ToolNode"
+ raise TypeError(msg)
+
+ # Inject state, store, and runtime right before invocation
+ injected_call = self._inject_tool_args(call, request.runtime, tool)
+ call_args = {**injected_call, "type": "tool_call"}
+
+ try:
+ try:
+ response = await tool.ainvoke(call_args, config)
+ except ValidationError as exc:
+ # Filter out errors for injected arguments
+ injected = self._injected_args.get(call["name"])
+ filtered_errors = _filter_validation_errors(exc, injected)
+ # Use original call["args"] without injected values for error reporting
+ raise ToolInvocationError(
+ call["name"], exc, call["args"], filtered_errors
+ ) from exc
+
+ # Inside try so validation errors route through _handle_tool_errors
+ return self._normalize_tool_response(
+ response, request.tool_call, input_type
+ )
+
+ # GraphInterrupt is a special exception that will always be raised.
+ # It can be triggered in the following scenarios,
+ # Where GraphInterrupt(GraphBubbleUp) is raised from an `interrupt` invocation
+ # most commonly:
+ # (1) a GraphInterrupt is raised inside a tool
+ # (2) a GraphInterrupt is raised inside a graph node for a graph called as a tool
+ # (3) a GraphInterrupt is raised when a subgraph is interrupted inside a graph
+ # called as a tool
+ # (2 and 3 can happen in a "supervisor w/ tools" multi-agent architecture)
+ except GraphBubbleUp:
+ raise
+ except Exception as e:
+ # Determine which exception types are handled
+ handled_types: tuple[type[Exception], ...]
+ if isinstance(self._handle_tool_errors, type) and issubclass(
+ self._handle_tool_errors, Exception
+ ):
+ handled_types = (self._handle_tool_errors,)
+ elif isinstance(self._handle_tool_errors, tuple):
+ handled_types = self._handle_tool_errors
+ elif callable(self._handle_tool_errors) and not isinstance(
+ self._handle_tool_errors, type
+ ):
+ handled_types = _infer_handled_types(self._handle_tool_errors)
+ else:
+ # default behavior is catching all exceptions
+ handled_types = (Exception,)
+
+ # Check if this error should be handled
+ if not self._handle_tool_errors or not isinstance(e, handled_types):
+ raise
+
+ # Error is handled - create error ToolMessage
+ content = _handle_tool_error(e, flag=self._handle_tool_errors)
+ return ToolMessage(
+ content=content,
+ name=call["name"],
+ tool_call_id=call["id"],
+ status="error",
+ )
+
+ async def _arun_one(
+ self,
+ call: ToolCall,
+ input_type: Literal["list", "dict", "tool_calls"],
+ tool_runtime: ToolRuntime,
+ ) -> ToolMessage | Command | list[Command | ToolMessage]:
+ """Execute single tool call asynchronously with awrap_tool_call wrapper if configured.
+
+ Args:
+ call: Tool call dict.
+ input_type: Input format.
+ tool_runtime: Tool runtime.
+
+ Returns:
+ ToolMessage or Command.
+ """
+ # Validation is deferred to _execute_tool_async to allow interceptors
+ # to short-circuit requests for unregistered tools
+ tool = self.tools_by_name.get(call["name"])
+
+ # Create the tool request with state and runtime
+ tool_request = ToolCallRequest(
+ tool_call=call,
+ tool=tool,
+ state=tool_runtime.state,
+ runtime=tool_runtime,
+ )
+
+ config = tool_runtime.config
+
+ if self._awrap_tool_call is None and self._wrap_tool_call is None:
+ # No wrapper - execute directly
+ return await self._execute_tool_async(tool_request, input_type, config)
+
+ # Define async execute callable that can be called multiple times
+ async def execute(req: ToolCallRequest) -> ToolMessage | Command:
+ """Execute tool with given request. Can be called multiple times."""
+ return await self._execute_tool_async(req, input_type, config)
+
+ def _sync_execute(req: ToolCallRequest) -> ToolMessage | Command:
+ """Sync execute fallback for sync wrapper."""
+ return self._execute_tool_sync(req, input_type, config)
+
+ # Call wrapper with request and execute callable
+ try:
+ if self._awrap_tool_call is not None:
+ return await self._awrap_tool_call(tool_request, execute)
+ # None check was performed above already
+ self._wrap_tool_call = cast("ToolCallWrapper", self._wrap_tool_call)
+ return self._wrap_tool_call(tool_request, _sync_execute)
+ except Exception as e:
+ # Wrapper threw an exception
+ if not self._handle_tool_errors:
+ raise
+ # Convert to error message
+ content = _handle_tool_error(e, flag=self._handle_tool_errors)
+ return ToolMessage(
+ content=content,
+ name=tool_request.tool_call["name"],
+ tool_call_id=tool_request.tool_call["id"],
+ status="error",
+ )
+
+ def _parse_input(
+ self,
+ input: list[AnyMessage] | dict[str, Any] | BaseModel,
+ ) -> tuple[list[ToolCall], Literal["list", "dict", "tool_calls"]]:
+ input_type: Literal["list", "dict", "tool_calls"]
+ if isinstance(input, list):
+ if isinstance(input[-1], dict) and input[-1].get("type") == "tool_call":
+ input_type = "tool_calls"
+ tool_calls = cast("list[ToolCall]", input)
+ return tool_calls, input_type
+ input_type = "list"
+ messages = input
+ elif (
+ isinstance(input, dict) and input.get("__type") == "tool_call_with_context"
+ ):
+ # Handle ToolCallWithContext from Send API
+ # mypy will not be able to type narrow correctly since the signature
+ # for input contains dict[str, Any]. We'd need to narrow dict[str, Any]
+ # before we can apply correct typing.
+ input_with_ctx = cast("ToolCallWithContext", input)
+ input_type = "tool_calls"
+ return [input_with_ctx["tool_call"]], input_type
+ elif isinstance(input, dict) and (
+ messages := input.get(self._messages_key, [])
+ ):
+ input_type = "dict"
+ elif messages := getattr(input, self._messages_key, []):
+ # Assume dataclass-like state that can coerce from dict
+ input_type = "dict"
+ else:
+ msg = "No message found in input"
+ raise ValueError(msg)
+
+ try:
+ latest_ai_message = next(
+ m for m in reversed(messages) if isinstance(m, AIMessage)
+ )
+ except StopIteration:
+ msg = "No AIMessage found in input"
+ raise ValueError(msg)
+
+ tool_calls = list(latest_ai_message.tool_calls)
+ return tool_calls, input_type
+
+ def _validate_tool_call(self, call: ToolCall) -> ToolMessage | None:
+ requested_tool = call["name"]
+ if requested_tool not in self.tools_by_name:
+ all_tool_names = list(self.tools_by_name.keys())
+ content = INVALID_TOOL_NAME_ERROR_TEMPLATE.format(
+ requested_tool=requested_tool,
+ available_tools=", ".join(all_tool_names),
+ )
+ return ToolMessage(
+ content, name=requested_tool, tool_call_id=call["id"], status="error"
+ )
+ return None
+
+ def _extract_state(
+ self,
+ input: list[AnyMessage] | dict[str, Any] | BaseModel,
+ config: RunnableConfig,
+ ) -> list[AnyMessage] | dict[str, Any] | BaseModel:
+ """Extract state from input.
+
+ Three input shapes:
+
+ - `ToolCallWithContext` dict — legacy Send payload carrying an inlined
+ state snapshot; return `input["state"]`.
+ - list of `ToolCall` dicts — new Send payload with no inlined state;
+ hydrate state from channels via `CONFIG_KEY_READ`.
+ - regular graph state (dict/list/BaseModel) — return `input` as-is.
+ """
+ if isinstance(input, dict) and input.get("__type") == "tool_call_with_context":
+ return input["state"]
+ if (
+ isinstance(input, list)
+ and input
+ and isinstance(input[-1], dict)
+ and input[-1].get("type") == "tool_call"
+ ):
+ read = config.get(CONF, {}).get(CONFIG_KEY_READ)
+ if read is None:
+ return {}
+ # Pregel installs CONFIG_KEY_READ as
+ # `functools.partial(local_read, scratchpad, channels, managed, task)`.
+ # Match the previous inlined-state contract by reading channels only;
+ # managed values have their own injection path (`ToolRuntime.context`).
+ channels = read.args[1]
+ return cast("dict[str, Any]", read(list(channels), True))
+ return input
+
+ def _inject_tool_args(
+ self,
+ tool_call: ToolCall,
+ tool_runtime: ToolRuntime,
+ tool: BaseTool | None = None,
+ ) -> ToolCall:
+ """Inject graph state, store, and runtime into tool call arguments.
+
+ This is an internal method that enables tools to access graph context that
+ should not be controlled by the model. Tools can declare dependencies on graph
+ state, persistent storage, or runtime context using InjectedState, InjectedStore,
+ and ToolRuntime annotations. This method automatically identifies these
+ dependencies and injects the appropriate values.
+
+ The injection process preserves the original tool call structure while adding
+ the necessary context arguments. This allows tools to be both model-callable
+ and context-aware without exposing internal state management to the model.
+
+ Args:
+ tool_call: The tool call dictionary to augment with injected arguments.
+ Must contain 'name', 'args', 'id', and 'type' fields.
+ tool_runtime: The ToolRuntime instance containing all runtime context
+ (state, config, store, context, stream_writer) to inject into tools.
+ tool: Optional tool instance. When provided, allows injection for
+ dynamically registered tools that are not in self.tools_by_name
+ (e.g., tools added via middleware's wrap_tool_call).
+
+ Returns:
+ A new ToolCall dictionary with the same structure as the input but with
+ additional arguments injected based on the tool's annotation requirements.
+
+ Raises:
+ ValueError: If a tool requires store injection but no store is provided,
+ or if state injection requirements cannot be satisfied.
+
+ !!! note
+ This method is called automatically during tool execution. It should not
+ be called from outside the `ToolNode`.
+ """
+ injected = self._injected_args.get(tool_call["name"])
+ if not injected and tool is not None:
+ # For dynamically registered tools (e.g., added via middleware's
+ # wrap_tool_call), compute injected args on-the-fly since they
+ # were not present during ToolNode initialization.
+ injected = _get_all_injected_args(tool)
+ if not injected:
+ return tool_call
+
+ tool_call_copy: ToolCall = copy(tool_call)
+ injected_args: dict[str, Any] = {}
+
+ # Inject state
+ if injected.state:
+ state = tool_runtime.state
+ # Handle list state by converting to dict
+ if isinstance(state, list):
+ required_fields = list(injected.state.values())
+ if (
+ len(required_fields) == 1
+ and required_fields[0] == self._messages_key
+ ) or required_fields[0] is None:
+ state = {self._messages_key: state}
+ else:
+ err_msg = (
+ f"Invalid input to ToolNode. Tool {tool_call['name']} requires "
+ f"graph state dict as input."
+ )
+ if any(state_field for state_field in injected.state.values()):
+ required_fields_str = ", ".join(f for f in required_fields if f)
+ err_msg += (
+ f" State should contain fields {required_fields_str}."
+ )
+ raise ValueError(err_msg)
+
+ # Extract state values
+ if isinstance(state, dict):
+ for tool_arg, state_field in injected.state.items():
+ if not state_field:
+ injected_args[tool_arg] = state
+ elif state_field in state:
+ injected_args[tool_arg] = state[state_field]
+ elif tool_arg not in injected._optional_state_args:
+ raise KeyError(state_field)
+ else:
+ for tool_arg, state_field in injected.state.items():
+ if not state_field:
+ injected_args[tool_arg] = state
+ elif hasattr(state, state_field):
+ injected_args[tool_arg] = getattr(state, state_field)
+ elif tool_arg not in injected._optional_state_args:
+ raise AttributeError(state_field)
+
+ # Inject store
+ if injected.store:
+ if tool_runtime.store is None:
+ msg = (
+ "Cannot inject store into tools with InjectedStore annotations - "
+ "please compile your graph with a store."
+ )
+ raise ValueError(msg)
+ injected_args[injected.store] = tool_runtime.store
+
+ # Inject runtime
+ if injected.runtime:
+ injected_args[injected.runtime] = tool_runtime
+
+ # Strip any caller-supplied values for injected args, then add
+ # back only trusted values. This prevents an LLM from forging
+ # hidden InjectedToolArg fields via ToolCall.args.
+ stripped_args = {
+ k: v
+ for k, v in tool_call_copy["args"].items()
+ if k not in injected.all_injected_keys
+ }
+ tool_call_copy["args"] = {**stripped_args, **injected_args}
+ return tool_call_copy
+
+ def _normalize_tool_response(
+ self,
+ response: Any,
+ tool_call: ToolCall,
+ input_type: Literal["list", "dict", "tool_calls"],
+ ) -> ToolMessage | Command | list[Command | ToolMessage]:
+ """Validate and normalize a tool's raw return value."""
+ if isinstance(response, Command):
+ return self._validate_tool_command(response, tool_call, input_type)
+ if isinstance(response, ToolMessage):
+ response.content = cast("str | list", msg_content_output(response.content))
+ return response
+ if isinstance(response, list):
+ if all(isinstance(r, (Command, ToolMessage)) for r in response):
+ return self._validate_tool_command_list(response, tool_call, input_type)
+ msg = (
+ f"Tool {tool_call['name']} returned a list with invalid element "
+ "types: expected all Command or ToolMessage"
+ )
+ raise TypeError(msg)
+ msg = f"Tool {tool_call['name']} returned unexpected type: {type(response)}"
+ raise TypeError(msg)
+
+ def _validate_tool_command_list(
+ self,
+ response: list[Command | ToolMessage],
+ tool_call: ToolCall,
+ input_type: Literal["list", "dict", "tool_calls"],
+ ) -> list[Command | ToolMessage]:
+ """Validate a list of Command/ToolMessage returned by a single tool call.
+
+ Requires exactly one terminating ToolMessage (matching the outer tool_call_id)
+ across the list — either as a top-level element or nested in a
+ Command.update["messages"].
+ """
+ expected_id = tool_call["id"]
+
+ terminator_count = 0
+ for item in response:
+ if isinstance(item, ToolMessage):
+ if item.tool_call_id == expected_id:
+ terminator_count += 1
+ elif isinstance(item, Command) and isinstance(item.update, dict):
+ for msg in item.update.get(self._messages_key, []):
+ if isinstance(msg, ToolMessage) and msg.tool_call_id == expected_id:
+ terminator_count += 1
+
+ if terminator_count != 1:
+ msg = (
+ f"Tool {tool_call['name']} returned a list with "
+ f"{terminator_count} messages bound to tool_call_id "
+ f"{expected_id!r}; expected exactly one terminating ToolMessage."
+ )
+ raise ValueError(msg)
+
+ # Per-Command normalization still runs, but the list-level count above
+ # already guarantees exactly one terminator, so individual Commands may
+ # lack one.
+ validated: list[Command | ToolMessage] = []
+ for item in response:
+ if isinstance(item, Command):
+ validated.append(
+ self._validate_tool_command(
+ item, tool_call, input_type, require_terminator=False
+ )
+ )
+ else:
+ item.content = cast("str | list", msg_content_output(item.content))
+ validated.append(item)
+ return validated
+
+ def _validate_tool_command(
+ self,
+ command: Command,
+ call: ToolCall,
+ input_type: Literal["list", "dict", "tool_calls"],
+ *,
+ require_terminator: bool = True,
+ ) -> Command:
+ if isinstance(command.update, dict):
+ # input type is dict when ToolNode is invoked with a dict input
+ # (e.g. {"messages": [AIMessage(..., tool_calls=[...])]})
+ if input_type not in ("dict", "tool_calls"):
+ msg = (
+ "Tools can provide a dict in Command.update only when using dict "
+ f"with '{self._messages_key}' key as ToolNode input, "
+ f"got: {command.update} for tool '{call['name']}'"
+ )
+ raise ValueError(msg)
+
+ updated_command = deepcopy(command)
+ state_update = cast("dict[str, Any]", updated_command.update) or {}
+ messages_update = state_update.get(self._messages_key, [])
+ elif isinstance(command.update, list):
+ # Input type is list when ToolNode is invoked with a list input
+ # (e.g. [AIMessage(..., tool_calls=[...])])
+ if input_type != "list":
+ msg = (
+ "Tools can provide a list of messages in Command.update "
+ "only when using list of messages as ToolNode input, "
+ f"got: {command.update} for tool '{call['name']}'"
+ )
+ raise ValueError(msg)
+
+ updated_command = deepcopy(command)
+ messages_update = updated_command.update
+ else:
+ return command
+
+ # convert to message objects if updates are in a dict format
+ messages_update = convert_to_messages(messages_update)
+
+ # no validation needed if all messages are being removed
+ if messages_update == [RemoveMessage(id=REMOVE_ALL_MESSAGES)]:
+ return updated_command
+
+ has_matching_tool_message = False
+ for message in messages_update:
+ if not isinstance(message, ToolMessage):
+ continue
+
+ if message.tool_call_id == call["id"]:
+ message.name = call["name"]
+ has_matching_tool_message = True
+
+ # validate that we always have a ToolMessage matching the tool call in
+ # Command.update if command is sent to the CURRENT graph
+ if (
+ require_terminator
+ and updated_command.graph is None
+ and not has_matching_tool_message
+ ):
+ example_update = (
+ '`Command(update={"messages": '
+ '[ToolMessage("Success", tool_call_id=tool_call_id), ...]}, ...)`'
+ if input_type == "dict"
+ else "`Command(update="
+ '[ToolMessage("Success", tool_call_id=tool_call_id), ...], ...)`'
+ )
+ msg = (
+ "Expected to have a matching ToolMessage in Command.update "
+ f"for tool '{call['name']}', got: {messages_update}. "
+ "Every tool call (LLM requesting to call a tool) "
+ "in the message history MUST have a corresponding ToolMessage. "
+ f"You can fix it by modifying the tool to return {example_update}."
+ )
+ raise ValueError(msg)
+ return updated_command
+
+
+def tools_condition(
+ state: list[AnyMessage] | dict[str, Any] | BaseModel,
+ messages_key: str = "messages",
+) -> Literal["tools", "__end__"]:
+ """Conditional routing function for tool-calling workflows.
+
+ This utility function implements the standard conditional logic for ReAct-style
+ agents: if the last `AIMessage` contains tool calls, route to the tool execution
+ node; otherwise, end the workflow. This pattern is fundamental to most tool-calling
+ agent architectures.
+
+ The function handles multiple state formats commonly used in LangGraph applications,
+ making it flexible for different graph designs while maintaining consistent behavior.
+
+ Args:
+ state: The current graph state to examine for tool calls. Supported formats:
+ - Dictionary containing a messages key (for `StateGraph`)
+ - `BaseModel` instance with a messages attribute
+ messages_key: The key or attribute name containing the message list in the state.
+ This allows customization for graphs using different state schemas.
+
+ Returns:
+ Either `'tools'` if tool calls are present in the last `AIMessage`, or `'__end__'`
+ to terminate the workflow. These are the standard routing destinations for
+ tool-calling conditional edges.
+
+ Raises:
+ ValueError: If no messages can be found in the provided state format.
+
+ Example:
+ Basic usage in a ReAct agent:
+
+ ```python
+ from langgraph.graph import StateGraph
+ from langchain.tools import ToolNode
+ from langchain.tools.tool_node import tools_condition
+ from typing_extensions import TypedDict
+
+
+ class State(TypedDict):
+ messages: list
+
+
+ graph = StateGraph(State)
+ graph.add_node("llm", call_model)
+ graph.add_node("tools", ToolNode([my_tool]))
+ graph.add_conditional_edges(
+ "llm",
+ tools_condition, # Routes to "tools" or "__end__"
+ {"tools": "tools", "__end__": "__end__"},
+ )
+ ```
+
+ Custom messages key:
+
+ ```python
+ def custom_condition(state):
+ return tools_condition(state, messages_key="chat_history")
+ ```
+
+ !!! note
+ This function is designed to work seamlessly with `ToolNode` and standard
+ LangGraph patterns. It expects the last message to be an `AIMessage` when
+ tool calls are present, which is the standard output format for tool-calling
+ language models.
+ """
+ if isinstance(state, list):
+ ai_message = state[-1]
+ elif (isinstance(state, dict) and (messages := state.get(messages_key, []))) or (
+ messages := getattr(state, messages_key, [])
+ ):
+ ai_message = messages[-1]
+ else:
+ msg = f"No messages found in input state to tool_edge: {state}"
+ raise ValueError(msg)
+ if hasattr(ai_message, "tool_calls") and len(ai_message.tool_calls) > 0:
+ return "tools"
+ return "__end__"
+
+
+@dataclass
+class ToolRuntime(_DirectlyInjectedToolArg, Generic[ContextT, StateT]):
+ """Runtime context automatically injected into tools.
+
+ !!! note
+
+ This is distinct from `Runtime` (from `langgraph.runtime`), which is injected
+ into graph nodes and middleware. `ToolRuntime` includes additional tool-specific
+ attributes like `config`, `state`, and `tool_call_id` that `Runtime` does not
+ have.
+
+ When a tool function has a parameter named `runtime` with type hint
+ `ToolRuntime`, the tool execution system will automatically inject an instance
+ containing:
+
+ - `state`: The current graph state
+ - `tool_call_id`: The ID of the current tool call
+ - `config`: `RunnableConfig` for the current execution
+ - `context`: Runtime context (shared with `Runtime`)
+ - `store`: `BaseStore` instance for persistent storage (shared with `Runtime`)
+ - `stream_writer`: `StreamWriter` for streaming output (shared with `Runtime`)
+ - `tools`: List of all available `BaseTool` instances
+
+ No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`
+ as a parameter.
+
+ Example:
+ ```python
+ from langchain_core.tools import tool
+ from langchain.tools import ToolRuntime
+
+ @tool
+ def my_tool(x: int, runtime: ToolRuntime) -> str:
+ \"\"\"Tool that accesses runtime context.\"\"\"
+ # Access state
+ messages = tool_runtime.state["messages"]
+
+ # Access tool_call_id
+ print(f"Tool call ID: {tool_runtime.tool_call_id}")
+
+ # Access config
+ print(f"Run ID: {tool_runtime.config.get('run_id')}")
+
+ # Access runtime context
+ user_id = tool_runtime.context.get("user_id")
+
+ # Access store
+ tool_runtime.store.put(("metrics",), "count", 1)
+
+ # Stream output
+ tool_runtime.stream_writer.write("Processing...")
+
+ return f"Processed {x}"
+ ```
+
+ !!! note
+ This is a marker class used for type checking and detection.
+ The actual runtime object will be constructed during tool execution.
+ """
+
+ state: StateT
+ context: ContextT
+ config: RunnableConfig
+ stream_writer: StreamWriter
+ tool_call_id: str | None
+ store: BaseStore | None
+ tools: list[BaseTool] = field(default_factory=list)
+ execution_info: ExecutionInfo | None = None
+ server_info: ServerInfo | None = None
+
+ def emit_output_delta(self, delta: Any) -> None:
+ """Stream a partial output chunk on the `tools` stream channel.
+
+ Reads the per-tool-call writer that `StreamToolCallHandler`
+ installs on a ContextVar at `on_tool_start` and forwards `delta`
+ through it. Silent no-op when the graph was not run with
+ `"tools"` in `stream_mode` (no writer is set), so tool authors
+ can leave `emit_output_delta` calls in place without gating
+ them on stream mode.
+
+ Args:
+ delta: Partial output chunk. Any JSON-serializable value;
+ surfaced as-is on the `tools` channel's
+ `tool-output-delta` payload under `"delta"`.
+ """
+ writer = _tool_call_writer.get()
+ if writer is None:
+ return
+ writer(delta)
+
+
+class InjectedState(InjectedToolArg):
+ """Annotation for injecting graph state into tool arguments.
+
+ This annotation enables tools to access graph state without exposing state
+ management details to the language model. Tools annotated with `InjectedState`
+ receive state data automatically during execution while remaining invisible
+ to the model's tool-calling interface.
+
+ Args:
+ field: Optional key to extract from the state dictionary. If `None`, the entire
+ state is injected. If specified, only that field's value is injected.
+ This allows tools to request specific state components rather than
+ processing the full state structure.
+
+ Example:
+ ```python
+ from typing import List
+ from typing_extensions import Annotated, TypedDict
+
+ from langchain_core.messages import BaseMessage, AIMessage
+ from langchain.tools import InjectedState, ToolNode, tool
+
+
+ class AgentState(TypedDict):
+ messages: List[BaseMessage]
+ foo: str
+
+
+ @tool
+ def state_tool(x: int, state: Annotated[dict, InjectedState]) -> str:
+ '''Do something with state.'''
+ if len(state["messages"]) > 2:
+ return state["foo"] + str(x)
+ else:
+ return "not enough messages"
+
+
+ @tool
+ def foo_tool(x: int, foo: Annotated[str, InjectedState("foo")]) -> str:
+ '''Do something else with state.'''
+ return foo + str(x + 1)
+
+
+ node = ToolNode([state_tool, foo_tool])
+
+ tool_call1 = {"name": "state_tool", "args": {"x": 1}, "id": "1", "type": "tool_call"}
+ tool_call2 = {"name": "foo_tool", "args": {"x": 1}, "id": "2", "type": "tool_call"}
+ state = {
+ "messages": [AIMessage("", tool_calls=[tool_call1, tool_call2])],
+ "foo": "bar",
+ }
+ node.invoke(state)
+ ```
+
+ ```python
+ [
+ ToolMessage(content="not enough messages", name="state_tool", tool_call_id="1"),
+ ToolMessage(content="bar2", name="foo_tool", tool_call_id="2"),
+ ]
+ ```
+
+ !!! note
+ - `InjectedState` arguments are automatically excluded from tool schemas
+ presented to language models
+ - `ToolNode` handles the injection process during execution
+ - Tools can mix regular arguments (controlled by the model) with injected
+ arguments (controlled by the system)
+ - State injection occurs after the model generates tool calls but before
+ tool execution
+ """
+
+ def __init__(self, field: str | None = None) -> None:
+ """Initialize the `InjectedState` annotation."""
+ self.field = field
+
+
+class InjectedStore(InjectedToolArg):
+ """Annotation for injecting persistent store into tool arguments.
+
+ This annotation enables tools to access LangGraph's persistent storage system
+ without exposing storage details to the language model. Tools annotated with
+ `InjectedStore` receive the store instance automatically during execution while
+ remaining invisible to the model's tool-calling interface.
+
+ The store provides persistent, cross-session data storage that tools can use
+ for maintaining context, user preferences, or any other data that needs to
+ persist beyond individual workflow executions.
+
+ !!! warning
+ `InjectedStore` annotation requires `langchain-core >= 0.3.8`
+
+ Example:
+ ```python
+ from typing_extensions import Annotated
+ from langgraph.store.memory import InMemoryStore
+ from langchain.tools import InjectedStore, ToolNode, tool
+
+ @tool
+ def save_preference(
+ key: str,
+ value: str,
+ store: Annotated[Any, InjectedStore()]
+ ) -> str:
+ \"\"\"Save user preference to persistent storage.\"\"\"
+ store.put(("preferences",), key, value)
+ return f"Saved {key} = {value}"
+
+ @tool
+ def get_preference(
+ key: str,
+ store: Annotated[Any, InjectedStore()]
+ ) -> str:
+ \"\"\"Retrieve user preference from persistent storage.\"\"\"
+ result = store.get(("preferences",), key)
+ return result.value if result else "Not found"
+ ```
+
+ Usage with `ToolNode` and graph compilation:
+
+ ```python
+ from langgraph.graph import StateGraph
+ from langgraph.store.memory import InMemoryStore
+
+ store = InMemoryStore()
+ tool_node = ToolNode([save_preference, get_preference])
+
+ graph = StateGraph(State)
+ graph.add_node("tools", tool_node)
+ compiled_graph = graph.compile(store=store) # Store is injected automatically
+ ```
+
+ Cross-session persistence:
+
+ ```python
+ # First session
+ result1 = graph.invoke({"messages": [HumanMessage("Save my favorite color as blue")]})
+
+ # Later session - data persists
+ result2 = graph.invoke({"messages": [HumanMessage("What's my favorite color?")]})
+ ```
+
+ !!! note
+ - `InjectedStore` arguments are automatically excluded from tool schemas
+ presented to language models
+ - The store instance is automatically injected by `ToolNode` during execution
+ - Tools can access namespaced storage using the store's get/put methods
+ - Store injection requires the graph to be compiled with a store instance
+ - Multiple tools can share the same store instance for data consistency
+ """
+
+
+def _is_injection(
+ type_arg: Any,
+ injection_type: type[InjectedState | InjectedStore | ToolRuntime],
+) -> bool:
+ """Check if a type argument represents an injection annotation.
+
+ This utility function determines whether a type annotation indicates that
+ an argument should be injected with state or store data. It handles both
+ direct annotations and nested annotations within Union or Annotated types.
+
+ Args:
+ type_arg: The type argument to check for injection annotations.
+ injection_type: The injection type to look for (InjectedState or InjectedStore).
+
+ Returns:
+ True if the type argument contains the specified injection annotation.
+ """
+ if isinstance(type_arg, injection_type) or (
+ isinstance(type_arg, type) and issubclass(type_arg, injection_type)
+ ):
+ return True
+ origin_ = get_origin(type_arg)
+ if origin_ is Union or origin_ is Annotated:
+ return any(_is_injection(ta, injection_type) for ta in get_args(type_arg))
+
+ if origin_ is not None and (
+ origin_ is injection_type
+ or (isinstance(origin_, type) and issubclass(origin_, injection_type))
+ ):
+ return True
+ return False
+
+
+def _get_injection_from_type(
+ type_: Any, injection_type: type[InjectedState | InjectedStore | ToolRuntime]
+) -> Any | None:
+ """Extract injection instance from a type annotation.
+
+ Args:
+ type_: The type annotation to check.
+ injection_type: The injection type to look for.
+
+ Returns:
+ The injection instance if found, True if injection marker found without instance, None otherwise.
+ """
+ type_args = get_args(type_)
+ matches = [arg for arg in type_args if _is_injection(arg, injection_type)]
+
+ if len(matches) > 1:
+ msg = (
+ f"A tool argument should not be annotated with {injection_type.__name__} "
+ f"more than once. Found: {matches}"
+ )
+ raise ValueError(msg)
+
+ if len(matches) == 1:
+ return matches[0]
+ elif _is_injection(type_, injection_type):
+ return True
+
+ return None
+
+
+def _get_all_injected_args(tool: BaseTool) -> _InjectedArgs:
+ """Extract all injected arguments from tool in a single pass.
+
+ This function analyzes both the tool's input schema and function signature
+ to identify all arguments that should be injected (state, store, runtime).
+
+ Args:
+ tool: The tool to analyze for injection requirements.
+
+ Returns:
+ _InjectedArgs structure containing all detected injections.
+ """
+ # Get annotations from both schema and function signature
+ full_schema = tool.get_input_schema()
+ schema_annotations = get_all_basemodel_annotations(full_schema)
+
+ func = getattr(tool, "func", None) or getattr(tool, "coroutine", None)
+ func_annotations = get_type_hints(func, include_extras=True) if func else {}
+
+ # Combine both annotation sources, preferring schema annotations
+ # In the future, we might want to add more restrictions here...
+ all_annotations = {**func_annotations, **schema_annotations}
+
+ # Track injected args
+ state_args: dict[str, str | None] = {}
+ store_arg: str | None = None
+ runtime_arg: str | None = None
+ all_injected_keys: set[str] = set()
+ _optional_state_args: set[str] = set()
+
+ for name, type_ in all_annotations.items():
+ # Track all InjectedToolArg-annotated params (including custom subclasses)
+ if _is_injected_arg_type(type_):
+ all_injected_keys.add(name)
+
+ # Check for runtime (special case: parameter named "runtime")
+ if name == "runtime":
+ runtime_arg = name
+
+ # Check for InjectedState
+ if state_inj := _get_injection_from_type(type_, InjectedState):
+ if isinstance(state_inj, InjectedState) and state_inj.field:
+ state_args[name] = state_inj.field
+ field_info = full_schema.model_fields.get(name)
+ if field_info and not field_info.is_required():
+ _optional_state_args.add(name)
+ else:
+ state_args[name] = None
+
+ # Check for InjectedStore
+ if _get_injection_from_type(type_, InjectedStore):
+ store_arg = name
+
+ # Check for ToolRuntime
+ if _get_injection_from_type(type_, ToolRuntime):
+ runtime_arg = name
+
+ return _InjectedArgs(
+ state=state_args,
+ store=store_arg,
+ runtime=runtime_arg,
+ all_injected_keys=all_injected_keys,
+ _optional_state_args=_optional_state_args,
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_validator.py b/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec9b3c29035007a3e283f133e7de365957d9dc12
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/prebuilt/tool_validator.py
@@ -0,0 +1,221 @@
+"""This module provides a ValidationNode class that can be used to validate tool calls
+in a langchain graph. It applies a pydantic schema to tool_calls in the models' outputs,
+and returns a ToolMessage with the validated content. If the schema is not valid, it
+returns a ToolMessage with the error message. The ValidationNode can be used in a
+StateGraph with a "messages" key. If multiple tool calls are requested, they will be run in parallel.
+"""
+
+from collections.abc import Callable, Sequence
+from typing import (
+ Any,
+ cast,
+)
+
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ ToolCall,
+ ToolMessage,
+)
+from langchain_core.runnables import (
+ RunnableConfig,
+)
+from langchain_core.runnables.config import get_executor_for_config
+from langchain_core.tools import BaseTool, create_schema_from_function
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from langgraph._internal._runnable import RunnableCallable
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+from pydantic import BaseModel, ValidationError
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import ValidationError as ValidationErrorV1
+from typing_extensions import deprecated
+
+
+def _default_format_error(
+ error: BaseException,
+ call: ToolCall,
+ schema: type[BaseModel] | type[BaseModelV1],
+) -> str:
+ """Default error formatting function."""
+ return f"{repr(error)}\n\nRespond after fixing all validation errors."
+
+
+@deprecated(
+ "ValidationNode is deprecated. Please use `create_agent` from `langchain.agents` with custom tool error handling.",
+ category=LangGraphDeprecatedSinceV10,
+)
+class ValidationNode(RunnableCallable):
+ """A node that validates all tools requests from the last `AIMessage`.
+
+ It can be used either in `StateGraph` with a `'messages'` key.
+
+ !!! note
+
+ This node does not actually **run** the tools, it only validates the tool calls,
+ which is useful for extraction and other use cases where you need to generate
+ structured output that conforms to a complex schema without losing the original
+ messages and tool IDs (for use in multi-turn conversations).
+
+ Returns:
+ (Union[Dict[str, List[ToolMessage]], Sequence[ToolMessage]]): A list of
+ `ToolMessage` objects with the validated content or error messages.
+
+ Example:
+ ```python title="Example usage for re-prompting the model to generate a valid response:"
+ from typing import Literal, Annotated
+ from typing_extensions import TypedDict
+
+ from langchain_anthropic import ChatAnthropic
+ from pydantic import BaseModel, field_validator
+
+ from langgraph.graph import END, START, StateGraph
+ from langgraph.prebuilt import ValidationNode
+ from langgraph.graph.message import add_messages
+
+ class SelectNumber(BaseModel):
+ a: int
+
+ @field_validator("a")
+ def a_must_be_meaningful(cls, v):
+ if v != 37:
+ raise ValueError("Only 37 is allowed")
+ return v
+
+ builder = StateGraph(Annotated[list, add_messages])
+ llm = ChatAnthropic(model="claude-3-5-haiku-latest").bind_tools([SelectNumber])
+ builder.add_node("model", llm)
+ builder.add_node("validation", ValidationNode([SelectNumber]))
+ builder.add_edge(START, "model")
+
+ def should_validate(state: list) -> Literal["validation", "__end__"]:
+ if state[-1].tool_calls:
+ return "validation"
+ return END
+
+ builder.add_conditional_edges("model", should_validate)
+
+ def should_reprompt(state: list) -> Literal["model", "__end__"]:
+ for msg in state[::-1]:
+ # None of the tool calls were errors
+ if msg.type == "ai":
+ return END
+ if msg.additional_kwargs.get("is_error"):
+ return "model"
+ return END
+
+ builder.add_conditional_edges("validation", should_reprompt)
+
+ graph = builder.compile()
+ res = graph.invoke(("user", "Select a number, any number"))
+ # Show the retry logic
+ for msg in res:
+ msg.pretty_print()
+ ```
+ """
+
+ def __init__(
+ self,
+ schemas: Sequence[BaseTool | type[BaseModel] | Callable],
+ *,
+ format_error: Callable[[BaseException, ToolCall, type[BaseModel]], str]
+ | None = None,
+ name: str = "validation",
+ tags: list[str] | None = None,
+ ) -> None:
+ """Initialize the ValidationNode.
+
+ Args:
+ schemas: A list of schemas to validate the tool calls with. These can be
+ any of the following:
+ - A pydantic BaseModel class
+ - A BaseTool instance (the args_schema will be used)
+ - A function (a schema will be created from the function signature)
+ format_error: A function that takes an exception, a ToolCall, and a schema
+ and returns a formatted error string. By default, it returns the
+ exception repr and a message to respond after fixing validation errors.
+ name: The name of the node.
+ tags: A list of tags to add to the node.
+ """
+ super().__init__(self._func, None, name=name, tags=tags, trace=False)
+ self._format_error = format_error or _default_format_error
+ self.schemas_by_name: dict[str, type[BaseModel]] = {}
+ for schema in schemas:
+ if isinstance(schema, BaseTool):
+ if schema.args_schema is None:
+ raise ValueError(
+ f"Tool {schema.name} does not have an args_schema defined."
+ )
+ elif not isinstance(
+ schema.args_schema, type
+ ) or not is_basemodel_subclass(schema.args_schema):
+ raise ValueError(
+ "Validation node only works with tools that have a pydantic BaseModel args_schema. "
+ f"Got {schema.name} with args_schema: {schema.args_schema}."
+ )
+ self.schemas_by_name[schema.name] = schema.args_schema
+ elif isinstance(schema, type) and issubclass(
+ schema, (BaseModel, BaseModelV1)
+ ):
+ self.schemas_by_name[schema.__name__] = cast(type[BaseModel], schema)
+ elif callable(schema):
+ base_model = create_schema_from_function("Validation", schema)
+ self.schemas_by_name[schema.__name__] = base_model
+ else:
+ raise ValueError(
+ f"Unsupported input to ValidationNode. Expected BaseModel, tool or function. Got: {type(schema)}."
+ )
+
+ def _get_message(
+ self, input: list[AnyMessage] | dict[str, Any]
+ ) -> tuple[str, AIMessage]:
+ """Extract the last AIMessage from the input."""
+ if isinstance(input, list):
+ output_type = "list"
+ messages: list = input
+ elif messages := input.get("messages", []):
+ output_type = "dict"
+ else:
+ raise ValueError("No message found in input")
+ message: AnyMessage = messages[-1]
+ if not isinstance(message, AIMessage):
+ raise ValueError("Last message is not an AIMessage")
+ return output_type, message
+
+ def _func(
+ self, input: list[AnyMessage] | dict[str, Any], config: RunnableConfig
+ ) -> Any:
+ """Validate and run tool calls synchronously."""
+ output_type, message = self._get_message(input)
+
+ def run_one(call: ToolCall) -> ToolMessage:
+ schema = self.schemas_by_name[call["name"]]
+ try:
+ if issubclass(schema, BaseModel):
+ output = schema.model_validate(call["args"])
+ content = output.model_dump_json()
+ elif issubclass(schema, BaseModelV1):
+ output = schema.validate(call["args"])
+ content = output.json()
+ else:
+ raise ValueError(
+ f"Unsupported schema type: {type(schema)}. Expected BaseModel or BaseModelV1."
+ )
+ return ToolMessage(
+ content=content,
+ name=call["name"],
+ tool_call_id=cast(str, call["id"]),
+ )
+ except (ValidationError, ValidationErrorV1) as e:
+ return ToolMessage(
+ content=self._format_error(e, call, schema),
+ name=call["name"],
+ tool_call_id=cast(str, call["id"]),
+ additional_kwargs={"is_error": True},
+ )
+
+ with get_executor_for_config(config) as executor:
+ outputs = [*executor.map(run_one, message.tool_calls)]
+ if output_type == "list":
+ return outputs
+ else:
+ return {"messages": outputs}
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__init__.py b/python/user_packages/Python313/site-packages/langgraph/pregel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..90eb44b85492bf210333122b3f93bf26cefdd475
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/__init__.py
@@ -0,0 +1,3 @@
+from langgraph.pregel.main import NodeBuilder, Pregel
+
+__all__ = ("Pregel", "NodeBuilder")
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ddb3d6d4505fff3c050e7de2156daed514b9ffb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_algo.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_algo.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a2ef62b50826ef1e5aa578ea4bd7cbc13619601
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_algo.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_call.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_call.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cde758c957b9c7f43b36970d8595fc0dc847aa79
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_call.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d3916966fba45a85ec1a3aa11257f81119cb2cd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_config.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_config.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46c3d22bd863d023d423ed30e55a94afb71d2958
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_config.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_draw.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_draw.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e83b7c3a0c0a6f1a817aed5b9982dec545faf5e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_draw.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_executor.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_executor.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc0ce8ca33531fbe260a697b585521299833a242
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_executor.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_io.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_io.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d57aaba60163b3f6bff10a671313bb6f0aa32398
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_io.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_log.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_log.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e630c850e8af009a9a2c0603c466c6c616955cf9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_log.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed92f44d9b3d9032511c46faa6376414aa2aff0f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_messages.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_messages.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a273b6291828ab3166bd6a17c8187bac9c270a7a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_messages.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_read.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_read.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d1f6cecef537c215a2a6f00cc2290edbd649a69
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_read.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_retry.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f88ea2b32cdf4fbc0e6062062f04f243ca83b004
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_retry.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_runner.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_runner.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ea7c40e1a385272b1ff5e35c3e6f3f6302b4363
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_runner.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_tools.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_tools.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fceb241dde2bb047e52ba7521c3b9f9441b0006
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_tools.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_utils.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70a17d6e969e08b461297210edc472c37cfd6406
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_utils.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_validate.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_validate.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ab7b4646ce2b6d3c8c293623d50e090c5b6803d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_validate.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_write.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_write.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..514b4394071b478687c3ff794b648b1aa33ff765
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/_write.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/debug.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/debug.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9889553f7eec386559ea8c6be006469acb3f5eb9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/debug.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/protocol.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/protocol.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6816afd6a20ae8f7260c70cedbf787b9beb4ac40
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/protocol.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/remote.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/remote.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b3390071b557df75afa4a2a3e16fd67b414b125
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/remote.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fb71a4f628e6f8bce7a74f0f49c173a33ca6f50
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/pregel/__pycache__/types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_algo.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_algo.py
new file mode 100644
index 0000000000000000000000000000000000000000..103f6cce01757d6db94ad113a50528909d78c6f7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_algo.py
@@ -0,0 +1,1460 @@
+from __future__ import annotations
+
+import binascii
+import itertools
+import sys
+import threading
+from collections import defaultdict, deque
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from copy import copy
+from functools import partial
+from hashlib import sha1
+from typing import (
+ Any,
+ Literal,
+ NamedTuple,
+ Protocol,
+ cast,
+ overload,
+)
+
+from langchain_core.callbacks import Callbacks
+from langchain_core.callbacks.manager import AsyncParentRunManager, ParentRunManager
+from langchain_core.runnables.config import RunnableConfig
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ ChannelVersions,
+ Checkpoint,
+ PendingWrite,
+ V,
+)
+from langgraph.store.base import BaseStore
+from xxhash import xxh3_128_hexdigest
+
+from langgraph._internal._config import merge_configs, patch_config
+from langgraph._internal._constants import (
+ CACHE_NS_WRITES,
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_CHECKPOINTER,
+ CONFIG_KEY_NODE_ERROR,
+ CONFIG_KEY_READ,
+ CONFIG_KEY_RESUME_MAP,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SCRATCHPAD,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INTERRUPT,
+ NO_WRITES,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PREVIOUS,
+ PULL,
+ PUSH,
+ RESERVED,
+ RESUME,
+ RETURN,
+ TASKS,
+)
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.topic import Topic
+from langgraph.channels.untracked_value import UntrackedValue
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import NodeError
+from langgraph.managed.base import ManagedValueMapping
+from langgraph.pregel._call import get_runnable_for_task, identifier
+from langgraph.pregel._io import read_channels
+from langgraph.pregel._log import logger
+from langgraph.pregel._read import INPUT_CACHE_KEY_TYPE, PregelNode
+from langgraph.runtime import DEFAULT_RUNTIME, ExecutionInfo, Runtime
+from langgraph.types import (
+ All,
+ CacheKey,
+ CachePolicy,
+ PregelExecutableTask,
+ PregelTask,
+ RetryPolicy,
+ Send,
+ TimeoutPolicy,
+)
+
+GetNextVersion = Callable[[V | None, None], V]
+SUPPORTS_EXC_NOTES = sys.version_info >= (3, 11)
+
+
+class WritesProtocol(Protocol):
+ """Protocol for objects containing writes to be applied to checkpoint.
+ Implemented by PregelTaskWrites and PregelExecutableTask."""
+
+ @property
+ def path(self) -> tuple[str | int | tuple, ...]: ...
+
+ @property
+ def name(self) -> str: ...
+
+ @property
+ def writes(self) -> Sequence[tuple[str, Any]]: ...
+
+ @property
+ def triggers(self) -> Sequence[str]: ...
+
+
+class PregelTaskWrites(NamedTuple):
+ """Simplest implementation of WritesProtocol, for usage with writes that
+ don't originate from a runnable task, eg. graph input, update_state, etc."""
+
+ path: tuple[str | int | tuple, ...]
+ name: str
+ writes: Sequence[tuple[str, Any]]
+ triggers: Sequence[str]
+
+
+class Call:
+ __slots__ = (
+ "func",
+ "input",
+ "retry_policy",
+ "cache_policy",
+ "callbacks",
+ "timeout",
+ )
+
+ func: Callable
+ input: tuple[tuple[Any, ...], dict[str, Any]]
+ retry_policy: Sequence[RetryPolicy] | None
+ cache_policy: CachePolicy | None
+ callbacks: Callbacks
+ timeout: TimeoutPolicy | None
+
+ def __init__(
+ self,
+ func: Callable,
+ input: tuple[tuple[Any, ...], dict[str, Any]],
+ *,
+ retry_policy: Sequence[RetryPolicy] | None,
+ cache_policy: CachePolicy | None,
+ callbacks: Callbacks,
+ timeout: TimeoutPolicy | None = None,
+ ) -> None:
+ self.func = func
+ self.input = input
+ self.retry_policy = retry_policy
+ self.cache_policy = cache_policy
+ self.callbacks = callbacks
+ self.timeout = timeout
+
+
+def should_interrupt(
+ checkpoint: Checkpoint,
+ interrupt_nodes: All | Sequence[str],
+ tasks: Iterable[PregelExecutableTask],
+) -> list[PregelExecutableTask]:
+ """Check if the graph should be interrupted based on current state."""
+ version_type = type(next(iter(checkpoint["channel_versions"].values()), None))
+ null_version = version_type() # type: ignore[misc]
+ seen = checkpoint["versions_seen"].get(INTERRUPT, {})
+ # interrupt if any channel has been updated since last interrupt
+ any_updates_since_prev_interrupt = any(
+ version > seen.get(chan, null_version) # type: ignore[operator]
+ for chan, version in checkpoint["channel_versions"].items()
+ )
+ # and any triggered node is in interrupt_nodes list
+ return (
+ [
+ task
+ for task in tasks
+ if (
+ (
+ not task.config
+ or TAG_HIDDEN not in task.config.get("tags", EMPTY_SEQ)
+ )
+ if interrupt_nodes == "*"
+ else task.name in interrupt_nodes
+ )
+ ]
+ if any_updates_since_prev_interrupt
+ else []
+ )
+
+
+def local_read(
+ scratchpad: PregelScratchpad,
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ task: WritesProtocol,
+ select: list[str] | str,
+ fresh: bool = False,
+) -> dict[str, Any] | Any:
+ """Function injected under CONFIG_KEY_READ in task config, to read current state.
+ Used by conditional edges to read a copy of the state with reflecting the writes
+ from that node only."""
+ updated: dict[str, list[Any]] = defaultdict(list)
+ if isinstance(select, str):
+ managed_keys = []
+ for c, v in task.writes:
+ if c == select:
+ updated[c].append(v)
+ else:
+ managed_keys = [k for k in select if k in managed]
+ select = [k for k in select if k not in managed]
+ for c, v in task.writes:
+ if c in select:
+ updated[c].append(v)
+ if fresh:
+ # apply writes
+ local_channels: dict[str, BaseChannel] = {}
+ for k in channels:
+ cc = channels[k].copy()
+ cc.update(updated[k])
+ local_channels[k] = cc
+ # read fresh values
+ values = read_channels(local_channels, select)
+ else:
+ values = read_channels(channels, select)
+ if managed_keys:
+ values.update({k: managed[k].get(scratchpad) for k in managed_keys})
+ return values
+
+
+def increment(current: int | None, channel: None) -> int:
+ """Default channel versioning function, increments the current int version."""
+ return current + 1 if current is not None else 1
+
+
+def apply_writes(
+ checkpoint: Checkpoint,
+ channels: Mapping[str, BaseChannel],
+ tasks: Iterable[WritesProtocol],
+ get_next_version: GetNextVersion | None,
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+) -> set[str]:
+ """Apply writes from a set of tasks (usually the tasks from a Pregel step)
+ to the checkpoint and channels, and return managed values writes to be applied
+ externally.
+
+ Args:
+ checkpoint: The checkpoint to update.
+ channels: The channels to update.
+ tasks: The tasks to apply writes from.
+ get_next_version: Optional function to determine the next version of a channel.
+ trigger_to_nodes: Mapping of channel names to the set of nodes that can be triggered by updates to that channel.
+
+ Returns:
+ Set of channels that were updated in this step.
+ """
+ # sort tasks on path, to ensure deterministic order for update application
+ # any path parts after the 3rd are ignored for sorting
+ # (we use them for eg. task ids which aren't good for sorting)
+ tasks = sorted(tasks, key=lambda t: task_path_str(t.path[:3]))
+ # if no task has triggers this is applying writes from the null task only
+ # so we don't do anything other than update the channels written to
+ bump_step = any(t.triggers for t in tasks)
+
+ # update seen versions
+ for task in tasks:
+ checkpoint["versions_seen"].setdefault(task.name, {}).update(
+ {
+ chan: checkpoint["channel_versions"][chan]
+ for chan in task.triggers
+ if chan in checkpoint["channel_versions"]
+ }
+ )
+
+ # Find the highest version of all channels
+ if get_next_version is None:
+ next_version = None
+ else:
+ next_version = get_next_version(
+ (
+ max(checkpoint["channel_versions"].values())
+ if checkpoint["channel_versions"]
+ else None
+ ),
+ None,
+ )
+
+ # Consume all channels that were read
+ for chan in {
+ chan
+ for task in tasks
+ for chan in task.triggers
+ if chan not in RESERVED and chan in channels
+ }:
+ if channels[chan].consume() and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+
+ # Group writes by channel
+ pending_writes_by_channel: dict[str, list[Any]] = defaultdict(list)
+ for task in tasks:
+ for chan, val in task.writes:
+ if chan in (
+ NO_WRITES,
+ PUSH,
+ RESUME,
+ INTERRUPT,
+ RETURN,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ ):
+ pass
+ elif chan in channels:
+ pending_writes_by_channel[chan].append(val)
+ else:
+ logger.warning(
+ f"Task {task.name} with path {task.path} wrote to unknown channel {chan}, ignoring it."
+ )
+
+ # Apply writes to channels
+ updated_channels: set[str] = set()
+ for chan, vals in pending_writes_by_channel.items():
+ if chan in channels:
+ if channels[chan].update(vals) and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # Channels that weren't updated in this step are notified of a new step
+ if bump_step:
+ for chan in channels:
+ if channels[chan].is_available() and chan not in updated_channels:
+ if channels[chan].update(EMPTY_SEQ) and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # If this is (tentatively) the last superstep, notify all channels of finish
+ if bump_step and updated_channels.isdisjoint(trigger_to_nodes):
+ for chan in channels:
+ if channels[chan].finish() and next_version is not None:
+ checkpoint["channel_versions"][chan] = next_version
+ # unavailable channels can't trigger tasks, so don't add them
+ if channels[chan].is_available():
+ updated_channels.add(chan)
+
+ # Return managed values writes to be applied externally
+ return updated_channels
+
+
+@overload
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: Literal[False],
+ store: Literal[None] = None,
+ checkpointer: Literal[None] = None,
+ manager: Literal[None] = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: Literal[None] = None,
+) -> dict[str, PregelTask]: ...
+
+
+@overload
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: Literal[True],
+ store: BaseStore | None,
+ checkpointer: BaseCheckpointSaver | None,
+ manager: None | ParentRunManager | AsyncParentRunManager,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+) -> dict[str, PregelExecutableTask]: ...
+
+
+def prepare_next_tasks(
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ *,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ updated_channels: set[str] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+) -> dict[str, PregelTask] | dict[str, PregelExecutableTask]:
+ """Prepare the set of tasks that will make up the next Pregel step.
+
+ Args:
+ checkpoint: The current checkpoint.
+ pending_writes: The list of pending writes.
+ processes: The mapping of process names to PregelNode instances.
+ channels: The mapping of channel names to BaseChannel instances.
+ managed: The mapping of managed value names to functions.
+ config: The `Runnable` configuration.
+ step: The current step.
+ for_execution: Whether the tasks are being prepared for execution.
+ store: An instance of BaseStore to make it available for usage within tasks.
+ checkpointer: `Checkpointer` instance used for saving checkpoints.
+ manager: The parent run manager to use for the tasks.
+ trigger_to_nodes: Optional: Mapping of channel names to the set of nodes
+ that are can be triggered by that channel.
+ updated_channels: Optional. Set of channel names that have been updated during
+ the previous step. Using in conjunction with trigger_to_nodes to speed
+ up the process of determining which nodes should be triggered in the next
+ step.
+
+ Returns:
+ A dictionary of tasks to be executed. The keys are the task ids and the values
+ are the tasks themselves. This is the union of all PUSH tasks (Sends)
+ and PULL tasks (nodes triggered by edges).
+ """
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] = {}
+ checkpoint_id_bytes = binascii.unhexlify(checkpoint["id"].replace("-", ""))
+ null_version = checkpoint_null_version(checkpoint)
+ tasks: list[PregelTask | PregelExecutableTask] = []
+ # Consume pending tasks
+ tasks_channel = cast(Topic[Send] | None, channels.get(TASKS))
+ if tasks_channel and tasks_channel.is_available():
+ for idx, _ in enumerate(tasks_channel.get()):
+ if task := prepare_single_task(
+ (PUSH, idx),
+ None,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=pending_writes,
+ processes=processes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ input_cache=input_cache,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ ):
+ tasks.append(task)
+
+ # This section is an optimization that allows which nodes will be active
+ # during the next step.
+ # When there's information about:
+ # 1. Which channels were updated in the previous step
+ # 2. Which nodes are triggered by which channels
+ # Then we can determine which nodes should be triggered in the next step
+ # without having to cycle through all nodes.
+ if updated_channels and trigger_to_nodes:
+ triggered_nodes: set[str] = set()
+ # Get all nodes that have triggers associated with an updated channel
+ for channel in updated_channels:
+ if node_ids := trigger_to_nodes.get(channel):
+ triggered_nodes.update(node_ids)
+ # Sort the nodes to ensure deterministic order
+ candidate_nodes: Iterable[str] = sorted(triggered_nodes)
+ elif not checkpoint["channel_versions"]:
+ candidate_nodes = ()
+ else:
+ candidate_nodes = processes.keys()
+
+ # Check if any processes should be run in next step
+ # If so, prepare the values to be passed to them
+ for name in candidate_nodes:
+ if task := prepare_single_task(
+ (PULL, name),
+ None,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=pending_writes,
+ processes=processes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ input_cache=input_cache,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ ):
+ tasks.append(task)
+ return {t.id: t for t in tasks}
+
+
+PUSH_TRIGGER = (PUSH,)
+
+
+class _TaskIDFn(Protocol):
+ def __call__(self, namespace: bytes, *parts: str | bytes) -> str:
+ pass
+
+
+def prepare_single_task(
+ task_path: tuple[Any, ...],
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ checkpoint_null_version: V | None,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] | None = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+) -> None | PregelTask | PregelExecutableTask:
+ """Prepares a single task for the next Pregel step, given a task path, which
+ uniquely identifies a PUSH or PULL task within the graph."""
+ configurable = config.get(CONF, {})
+ parent_ns = configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_id_func = _xxhash_str if checkpoint["v"] > 1 else _uuid5_str
+
+ if task_path[0] == PUSH and isinstance(task_path[-1], Call):
+ return prepare_push_task_functional(
+ cast(tuple[str, tuple, int, str, Call], task_path),
+ task_id_checksum,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ pending_writes=pending_writes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ parent_ns=parent_ns,
+ task_id_func=task_id_func,
+ )
+
+ elif task_path[0] == PUSH:
+ return prepare_push_task_send(
+ cast(tuple[str, tuple], task_path),
+ task_id_checksum,
+ checkpoint=checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ pending_writes=pending_writes,
+ channels=channels,
+ managed=managed,
+ config=config,
+ step=step,
+ processes=processes,
+ stop=stop,
+ for_execution=for_execution,
+ store=store,
+ checkpointer=checkpointer,
+ manager=manager,
+ cache_policy=cache_policy,
+ retry_policy=retry_policy,
+ parent_ns=parent_ns,
+ task_id_func=task_id_func,
+ )
+
+ elif task_path[0] == PULL:
+ # (PULL, node name)
+ name = cast(str, task_path[1])
+ if name not in processes:
+ return
+ proc = processes[name]
+ if checkpoint_null_version is None:
+ return
+ # If any of the channels read by this process were updated
+ if _triggers(
+ channels,
+ checkpoint["channel_versions"],
+ checkpoint["versions_seen"].get(name),
+ checkpoint_null_version,
+ proc,
+ ):
+ triggers = tuple(sorted(proc.triggers))
+ # create task id
+ checkpoint_ns = f"{parent_ns}{NS_SEP}{name}" if parent_ns else name
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ name,
+ PULL,
+ *triggers,
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}{NS_END}{task_id}"
+ # create scratchpad
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ # create task input
+ try:
+ val = _proc_input(
+ proc,
+ managed,
+ channels,
+ for_execution=for_execution,
+ input_cache=input_cache,
+ scratchpad=scratchpad,
+ )
+ if val is MISSING:
+ return
+ except Exception as exc:
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(
+ f"Before task with name '{name}' and path '{task_path[:3]}'"
+ )
+ raise
+
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": name,
+ "langgraph_triggers": triggers,
+ "langgraph_path": task_path[:3],
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ if node := proc.node:
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = proc.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(val)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ name,
+ ),
+ xxh3_128_hexdigest(
+ (
+ args_key.encode()
+ if isinstance(args_key, str)
+ else args_key
+ ),
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ runtime = cast(
+ Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ )
+ runtime = runtime.override(
+ previous=checkpoint["channel_values"].get(PREVIOUS, None),
+ store=store,
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ additional_config = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ name,
+ val,
+ node,
+ writes,
+ patch_config(
+ merge_configs(
+ config, cast(RunnableConfig, additional_config)
+ ),
+ run_name=name,
+ callbacks=(
+ manager.get_child(f"graph:step:{step}")
+ if manager
+ else None
+ ),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ task_path[:3],
+ name,
+ writes,
+ triggers,
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer
+ or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ proc.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ task_path[:3],
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ timeout=proc.timeout,
+ )
+ else:
+ return PregelTask(task_id, name, task_path[:3])
+
+
+def _coerce_pending_error(value: Any) -> BaseException:
+ if isinstance(value, BaseException):
+ return value
+ return Exception(str(value))
+
+
+def _read_errors_from_pending_writes(
+ pending_writes: list[PendingWrite],
+) -> list[BaseException]:
+ errors: list[BaseException] = []
+ for _, channel, value in pending_writes:
+ if channel == ERROR:
+ errors.append(_coerce_pending_error(value))
+ return errors
+
+
+def _read_error_for_task_id_from_pending_writes(
+ pending_writes: list[PendingWrite], task_id: str
+) -> BaseException | None:
+ for pending_task_id, channel, value in reversed(pending_writes):
+ if pending_task_id == task_id and channel == ERROR:
+ return _coerce_pending_error(value)
+ return None
+
+
+def _read_error_source_node_from_pending_writes(
+ pending_writes: list[PendingWrite], task_id: str
+) -> str | None:
+ for pending_task_id, channel, value in reversed(pending_writes):
+ if pending_task_id == task_id and channel == ERROR_SOURCE_NODE:
+ if isinstance(value, str):
+ return value
+ return str(value)
+ return None
+
+
+def prepare_push_task_functional(
+ task_path: tuple[str, tuple, int, str, Call],
+ # (PUSH, parent task path, idx of PUSH write, id of parent task, Call)
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ pending_writes: list[PendingWrite],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ parent_ns: str,
+ # namespace: bytes, *parts: str | bytes
+ task_id_func: _TaskIDFn,
+) -> PregelTask | PregelExecutableTask:
+ """Prepare a push task with an attached caller. Used for the functional API."""
+ configurable = config.get(CONF, {})
+
+ call = task_path[-1]
+ proc_ = get_runnable_for_task(call.func)
+ name = proc_.name
+ if name is None:
+ raise ValueError("`call` functions must have a `__name__` attribute")
+ # create task id
+ triggers: Sequence[str] = PUSH_TRIGGER
+ checkpoint_ns = f"{parent_ns}{NS_SEP}{name}" if parent_ns else name
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ name,
+ PUSH,
+ task_path_str(task_path[1]),
+ str(task_path[2]),
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ # we append True to the task path to indicate that a call is being
+ # made, so we should not return interrupts from this task (responsibility lies with the parent)
+ in_progress_task_path = (*task_path[:3], True)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": name,
+ "langgraph_triggers": triggers,
+ "langgraph_path": in_progress_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = call.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(*call.input[0], **call.input[1])
+ cache_key: CacheKey | None = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(call.func) or "__dynamic__"),
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key,
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ scratchpad = _scratchpad(
+ configurable.get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ configurable.get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store,
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ return PregelExecutableTask(
+ name,
+ call.input,
+ proc_,
+ writes,
+ patch_config(
+ merge_configs(config, {"metadata": metadata}),
+ run_name=name,
+ callbacks=call.callbacks
+ or (manager.get_child(f"graph:step:{step}") if manager else None),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(in_progress_task_path, name, writes, triggers),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ call.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ in_progress_task_path,
+ timeout=call.timeout,
+ )
+ else:
+ return PregelTask(task_id, name, in_progress_task_path)
+
+
+def prepare_push_task_send(
+ task_path: tuple[str, tuple],
+ # (PUSH, parent task path)
+ task_id_checksum: str | None,
+ *,
+ checkpoint: Checkpoint,
+ checkpoint_id_bytes: bytes,
+ pending_writes: list[PendingWrite],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ for_execution: bool,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ parent_ns: str,
+ task_id_func: _TaskIDFn,
+ processes: Mapping[str, PregelNode],
+) -> PregelTask | PregelExecutableTask | None:
+ if len(task_path) == 2:
+ # SEND tasks, executed in superstep n+1
+ # (PUSH, idx of pending send)
+ idx = cast(int, task_path[1])
+ if not channels[TASKS].is_available():
+ return
+ sends: Sequence[Send] = channels[TASKS].get()
+ if idx < 0 or idx >= len(sends):
+ return
+ packet = sends[idx]
+ if not isinstance(packet, Send):
+ logger.warning(
+ f"Ignoring invalid packet type {type(packet)} in pending sends"
+ )
+ return
+
+ if packet.node not in processes:
+ logger.warning(f"Ignoring unknown node name {packet.node} in pending sends")
+ return
+ # find process
+ proc = processes[packet.node]
+ proc_node = proc.node
+ if proc_node is None:
+ return
+ # create task id
+ triggers = PUSH_TRIGGER
+ checkpoint_ns = (
+ f"{parent_ns}{NS_SEP}{packet.node}" if parent_ns else packet.node
+ )
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ packet.node,
+ PUSH,
+ str(idx),
+ )
+ else:
+ logger.warning(f"Ignoring invalid PUSH task path {task_path}")
+ return
+ configurable = config.get(CONF, {})
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ # we append False to the task path to indicate that a call is not being made
+ # so we should return interrupts from this task
+ translated_task_path = (*task_path[:3], False)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": packet.node,
+ "langgraph_triggers": triggers,
+ "langgraph_path": translated_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if task_id_checksum is not None:
+ assert task_id == task_id_checksum, f"{task_id} != {task_id_checksum}"
+ if for_execution:
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+ cache_policy = proc.cache_policy or cache_policy
+ if cache_policy:
+ args_key = cache_policy.key_func(packet.arg)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ packet.node,
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key,
+ ),
+ cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store,
+ previous=checkpoint["channel_values"].get(PREVIOUS, None),
+ execution_info=ExecutionInfo(
+ checkpoint_id=checkpoint["id"],
+ checkpoint_ns=task_checkpoint_ns,
+ task_id=task_id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+ additional_config: RunnableConfig = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ packet.node,
+ packet.arg,
+ proc_node,
+ writes,
+ patch_config(
+ merge_configs(config, additional_config),
+ run_name=packet.node,
+ callbacks=(
+ manager.get_child(f"graph:step:{step}") if manager else None
+ ),
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ translated_task_path, packet.node, writes, triggers
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ },
+ ),
+ triggers,
+ proc.retry_policy or retry_policy,
+ cache_key,
+ task_id,
+ translated_task_path,
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ timeout=packet.timeout if packet.timeout is not None else proc.timeout,
+ )
+ else:
+ return PregelTask(task_id, packet.node, translated_task_path)
+
+
+def prepare_node_error_handler_task(
+ failed_task: PregelExecutableTask,
+ *,
+ handler_node_name: str,
+ failed_error: BaseException,
+ checkpoint: Checkpoint,
+ pending_writes: list[PendingWrite],
+ processes: Mapping[str, PregelNode],
+ channels: Mapping[str, BaseChannel],
+ managed: ManagedValueMapping,
+ config: RunnableConfig,
+ step: int,
+ stop: int,
+ store: BaseStore | None = None,
+ checkpointer: BaseCheckpointSaver | None = None,
+ manager: None | ParentRunManager | AsyncParentRunManager = None,
+ cache_policy: CachePolicy | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+) -> PregelExecutableTask | None:
+ """Prepare an immediate node-level error handler task for a failed task."""
+ if handler_node_name not in processes:
+ return None
+ proc = processes[handler_node_name]
+ proc_node = proc.node
+ if proc_node is None:
+ return None
+
+ checkpoint_id_bytes = binascii.unhexlify(checkpoint["id"].replace("-", ""))
+ task_id_func = _xxhash_str if checkpoint["v"] > 1 else _uuid5_str
+ configurable = config.get(CONF, {})
+ parent_ns = configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ checkpoint_ns = (
+ f"{parent_ns}{NS_SEP}{handler_node_name}" if parent_ns else handler_node_name
+ )
+ task_id = task_id_func(
+ checkpoint_id_bytes,
+ checkpoint_ns,
+ str(step),
+ handler_node_name,
+ PUSH,
+ "node_error_handler",
+ failed_task.id,
+ )
+ task_checkpoint_ns = f"{checkpoint_ns}:{task_id}"
+ translated_task_path = (*failed_task.path[:3], "node_error_handler", False)
+ metadata = {
+ "langgraph_step": step,
+ "langgraph_node": handler_node_name,
+ "langgraph_triggers": PUSH_TRIGGER,
+ "langgraph_path": translated_task_path,
+ "langgraph_checkpoint_ns": task_checkpoint_ns,
+ }
+ if proc.metadata:
+ metadata.update(proc.metadata)
+ writes: deque[tuple[str, Any]] = deque()
+
+ effective_retry_policy = proc.retry_policy or retry_policy
+ effective_cache_policy = proc.cache_policy or cache_policy
+ if effective_cache_policy:
+ args_key = effective_cache_policy.key_func(failed_task.input)
+ cache_key = CacheKey(
+ (
+ CACHE_NS_WRITES,
+ (identifier(proc) or "__dynamic__"),
+ handler_node_name,
+ ),
+ xxh3_128_hexdigest(
+ args_key.encode() if isinstance(args_key, str) else args_key
+ ),
+ effective_cache_policy.ttl,
+ )
+ else:
+ cache_key = None
+
+ scratchpad = _scratchpad(
+ config[CONF].get(CONFIG_KEY_SCRATCHPAD),
+ pending_writes,
+ task_id,
+ xxh3_128_hexdigest(task_checkpoint_ns.encode()),
+ config[CONF].get(CONFIG_KEY_RESUME_MAP),
+ step,
+ stop,
+ )
+ runtime = cast(Runtime, configurable.get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME))
+ runtime = runtime.override(
+ store=store, previous=checkpoint["channel_values"].get(PREVIOUS, None)
+ )
+ additional_config: RunnableConfig = {
+ "metadata": metadata,
+ "tags": proc.tags,
+ }
+ return PregelExecutableTask(
+ handler_node_name,
+ failed_task.input,
+ proc_node,
+ writes,
+ patch_config(
+ merge_configs(config, additional_config),
+ run_name=handler_node_name,
+ callbacks=manager.get_child(f"graph:step:{step}") if manager else None,
+ configurable={
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ scratchpad,
+ channels,
+ managed,
+ PregelTaskWrites(
+ translated_task_path,
+ handler_node_name,
+ writes,
+ PUSH_TRIGGER,
+ ),
+ ),
+ CONFIG_KEY_CHECKPOINTER: (
+ checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
+ ),
+ CONFIG_KEY_CHECKPOINT_MAP: {
+ **configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {}),
+ parent_ns: checkpoint["id"],
+ },
+ CONFIG_KEY_CHECKPOINT_ID: None,
+ CONFIG_KEY_CHECKPOINT_NS: task_checkpoint_ns,
+ CONFIG_KEY_SCRATCHPAD: scratchpad,
+ CONFIG_KEY_RUNTIME: runtime,
+ CONFIG_KEY_NODE_ERROR: NodeError(
+ node=failed_task.name, error=failed_error
+ ),
+ },
+ ),
+ PUSH_TRIGGER,
+ effective_retry_policy,
+ cache_key,
+ task_id,
+ translated_task_path,
+ writers=proc.flat_writers,
+ subgraphs=proc.subgraphs,
+ )
+
+
+def checkpoint_null_version(
+ checkpoint: Checkpoint,
+) -> V | None:
+ """Get the null version for the checkpoint, if available."""
+ for version in checkpoint["channel_versions"].values():
+ return type(version)()
+ return None
+
+
+def _triggers(
+ channels: Mapping[str, BaseChannel],
+ versions: ChannelVersions,
+ seen: ChannelVersions | None,
+ null_version: V,
+ proc: PregelNode,
+) -> bool:
+ if seen is None:
+ for chan in proc.triggers:
+ if channels[chan].is_available():
+ return True
+ else:
+ for chan in proc.triggers:
+ if channels[chan].is_available() and versions.get( # type: ignore[operator]
+ chan, null_version
+ ) > seen.get(chan, null_version):
+ return True
+ return False
+
+
+def _scratchpad(
+ parent_scratchpad: PregelScratchpad | None,
+ pending_writes: list[PendingWrite],
+ task_id: str,
+ namespace_hash: str,
+ resume_map: dict[str, Any] | None,
+ step: int,
+ stop: int,
+) -> PregelScratchpad:
+ if len(pending_writes) > 0:
+ # find global resume value
+ for w in pending_writes:
+ if w[0] == NULL_TASK_ID and w[1] == RESUME:
+ null_resume_write = w
+ break
+ else:
+ # None cannot be used as a resume value, because it would be difficult to
+ # distinguish from missing when used over http
+ null_resume_write = None
+
+ # find task-specific resume value
+ for w in pending_writes:
+ if w[0] == task_id and w[1] == RESUME:
+ task_resume_write = w[2]
+ if not isinstance(task_resume_write, list):
+ task_resume_write = [task_resume_write]
+ break
+ else:
+ task_resume_write = []
+ del w
+
+ # find namespace and task-specific resume value
+ if resume_map and namespace_hash in resume_map:
+ mapped_resume_write = resume_map[namespace_hash]
+ task_resume_write.append(mapped_resume_write)
+
+ else:
+ null_resume_write = None
+ task_resume_write = []
+
+ def get_null_resume(consume: bool = False) -> Any:
+ if null_resume_write is None:
+ if parent_scratchpad is not None:
+ return parent_scratchpad.get_null_resume(consume)
+ return None
+ if consume:
+ try:
+ pending_writes.remove(null_resume_write)
+ return null_resume_write[2]
+ except ValueError:
+ return None
+ return null_resume_write[2]
+
+ # using itertools.count as an atomic counter (+= 1 is not thread-safe)
+ return PregelScratchpad(
+ step=step,
+ stop=stop,
+ # call
+ call_counter=LazyAtomicCounter(),
+ # interrupt
+ interrupt_counter=LazyAtomicCounter(),
+ resume=task_resume_write,
+ get_null_resume=get_null_resume,
+ # subgraph
+ subgraph_counter=LazyAtomicCounter(),
+ )
+
+
+def _proc_input(
+ proc: PregelNode,
+ managed: ManagedValueMapping,
+ channels: Mapping[str, BaseChannel],
+ *,
+ for_execution: bool,
+ scratchpad: PregelScratchpad,
+ input_cache: dict[INPUT_CACHE_KEY_TYPE, Any] | None,
+) -> Any:
+ """Prepare input for a PULL task, based on the process's channels and triggers."""
+ # if in cache return shallow copy
+ if input_cache is not None and proc.input_cache_key in input_cache:
+ return copy(input_cache[proc.input_cache_key])
+ # If all trigger channels subscribed by this process are not empty
+ # then invoke the process with the values of all non-empty channels
+ if isinstance(proc.channels, list):
+ val: dict[str, Any] = {}
+ for chan in proc.channels:
+ if chan in channels:
+ if channels[chan].is_available():
+ val[chan] = channels[chan].get()
+ else:
+ val[chan] = managed[chan].get(scratchpad)
+ elif isinstance(proc.channels, str):
+ if proc.channels in channels:
+ if channels[proc.channels].is_available():
+ val = channels[proc.channels].get()
+ else:
+ return MISSING
+ else:
+ return MISSING
+ else:
+ raise RuntimeError(
+ f"Invalid channels type, expected list or dict, got {proc.channels}"
+ )
+
+ # If the process has a mapper, apply it to the value
+ if for_execution and proc.mapper is not None:
+ val = proc.mapper(val)
+
+ # Cache the input value
+ if input_cache is not None:
+ input_cache[proc.input_cache_key] = val
+
+ return val
+
+
+def _uuid5_str(namespace: bytes, *parts: str | bytes) -> str:
+ """Generate a UUID from the SHA-1 hash of a namespace and str parts."""
+
+ sha = sha1(namespace, usedforsecurity=False)
+ sha.update(b"".join(p.encode() if isinstance(p, str) else p for p in parts))
+ hex = sha.hexdigest()
+ return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
+
+
+def _xxhash_str(namespace: bytes, *parts: str | bytes) -> str:
+ """Generate a UUID from the XXH3 hash of a namespace and str parts."""
+ hex = xxh3_128_hexdigest(
+ namespace + b"".join(p.encode() if isinstance(p, str) else p for p in parts)
+ )
+ return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
+
+
+def task_path_str(tup: str | int | tuple) -> str:
+ """Generate a string representation of the task path."""
+ return (
+ f"~{', '.join(task_path_str(x) for x in tup)}"
+ if isinstance(tup, (tuple, list))
+ else f"{tup:010d}"
+ if isinstance(tup, int)
+ else str(tup)
+ )
+
+
+LAZY_ATOMIC_COUNTER_LOCK = threading.Lock()
+
+
+class LazyAtomicCounter:
+ __slots__ = ("_counter",)
+
+ _counter: Callable[[], int] | None
+
+ def __init__(self) -> None:
+ self._counter = None
+
+ def __call__(self) -> int:
+ if self._counter is None:
+ with LAZY_ATOMIC_COUNTER_LOCK:
+ if self._counter is None:
+ self._counter = itertools.count(0).__next__
+ return self._counter()
+
+
+def sanitize_untracked_values_in_send(
+ packet: Send, channels: Mapping[str, BaseChannel]
+) -> Send:
+ """Pop any values belonging to UntrackedValue channels in Send.arg for safe checkpointing.
+
+ Send is often called with state to be passed to the dest node, which may contain
+ UntrackedValues at the top level. Send is not typed and arg may be a nested dict."""
+
+ if not isinstance(packet.arg, dict):
+ # Command
+ return packet
+
+ # top level keys should be the channel names
+ sanitized_arg = {
+ k: v
+ for k, v in packet.arg.items()
+ if not isinstance(channels.get(k), UntrackedValue)
+ }
+ return Send(node=packet.node, arg=sanitized_arg, timeout=packet.timeout)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_call.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_call.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c3fb385668850fc9d3a626823849fc576fe7a2a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_call.py
@@ -0,0 +1,298 @@
+"""Utility to convert a user provided function into a Runnable with a ChannelWrite."""
+
+from __future__ import annotations
+
+import concurrent.futures
+import functools
+import inspect
+import sys
+import types
+from collections.abc import Awaitable, Callable, Generator, Sequence
+from datetime import timedelta
+from typing import Any, Generic, TypeVar, cast
+
+from langchain_core.runnables import Runnable
+from typing_extensions import ParamSpec
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_CALL, RETURN
+from langgraph._internal._runnable import (
+ RunnableCallable,
+ RunnableSeq,
+ is_async_callable,
+ run_in_executor,
+)
+from langgraph._internal._timeout import (
+ coerce_timeout_policy,
+ sync_timeout_unsupported,
+)
+from langgraph.config import get_config
+from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
+from langgraph.types import CachePolicy, RetryPolicy, TimeoutPolicy
+
+##
+# Utilities borrowed from cloudpickle.
+# https://github.com/cloudpipe/cloudpickle/blob/6220b0ce83ffee5e47e06770a1ee38ca9e47c850/cloudpickle/cloudpickle.py#L265
+
+
+def _getattribute(obj: Any, name: str) -> Any:
+ parent = None
+ for subpath in name.split("."):
+ if subpath == "":
+ raise AttributeError(f"Can't get local attribute {name!r} on {obj!r}")
+ try:
+ parent = obj
+ obj = getattr(obj, subpath)
+ except AttributeError:
+ raise AttributeError(f"Can't get attribute {name!r} on {obj!r}") from None
+ return obj, parent
+
+
+def _whichmodule(obj: Any, name: str) -> str | None:
+ """Find the module an object belongs to.
+
+ This function differs from ``pickle.whichmodule`` in two ways:
+ - it does not mangle the cases where obj's module is __main__ and obj was
+ not found in any module.
+ - Errors arising during module introspection are ignored, as those errors
+ are considered unwanted side effects.
+ """
+ module_name = getattr(obj, "__module__", None)
+
+ if module_name is not None:
+ return module_name
+ # Protect the iteration by using a copy of sys.modules against dynamic
+ # modules that trigger imports of other modules upon calls to getattr or
+ # other threads importing at the same time.
+ for module_name, module in sys.modules.copy().items():
+ # Some modules such as coverage can inject non-module objects inside
+ # sys.modules
+ if (
+ module_name == "__main__"
+ or module_name == "__mp_main__"
+ or module is None
+ or not isinstance(module, types.ModuleType)
+ ):
+ continue
+ try:
+ if _getattribute(module, name)[0] is obj:
+ return module_name
+ except Exception:
+ pass
+ return None
+
+
+def identifier(obj: Any, name: str | None = None) -> str | None:
+ """Return the module and name of an object."""
+ from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+ from langgraph.pregel._read import PregelNode
+
+ if isinstance(obj, PregelNode):
+ obj = obj.bound
+ if isinstance(obj, RunnableSeq):
+ obj = obj.steps[0]
+ if isinstance(obj, RunnableCallable):
+ obj = obj.func
+ if name is None:
+ name = getattr(obj, "__qualname__", None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, "__name__", None)
+ if name is None:
+ return None
+
+ module_name = getattr(obj, "__module__", None)
+ if module_name is None:
+ # In this case, obj.__module__ is None. obj is thus treated as dynamic.
+ return None
+
+ return f"{module_name}.{name}"
+
+
+def _lookup_module_and_qualname(
+ obj: Any, name: str | None = None
+) -> tuple[types.ModuleType, str] | None:
+ if name is None:
+ name = getattr(obj, "__qualname__", None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, "__name__", None)
+ if name is None:
+ return None
+
+ module_name = _whichmodule(obj, name)
+
+ if module_name is None:
+ # In this case, obj.__module__ is None AND obj was not found in any
+ # imported module. obj is thus treated as dynamic.
+ return None
+
+ if module_name == "__main__":
+ return None
+
+ # Note: if module_name is in sys.modules, the corresponding module is
+ # assumed importable at unpickling time. See #357
+ module = sys.modules.get(module_name, None)
+ if module is None:
+ # The main reason why obj's module would not be imported is that this
+ # module has been dynamically created, using for example
+ # types.ModuleType. The other possibility is that module was removed
+ # from sys.modules after obj was created/imported. But this case is not
+ # supported, as the standard pickle does not support it either.
+ return None
+
+ try:
+ obj2, parent = _getattribute(module, name)
+ except AttributeError:
+ # obj was not found inside the module it points to
+ return None
+ if obj2 is not obj:
+ return None
+ return module, name
+
+
+def _explode_args_trace_inputs(
+ sig: inspect.Signature, input: tuple[tuple[Any, ...], dict[str, Any]]
+) -> dict[str, Any]:
+ args, kwargs = input
+ bound = sig.bind_partial(*args, **kwargs)
+ bound.apply_defaults()
+ arguments = dict(bound.arguments)
+ arguments.pop("self", None)
+ arguments.pop("cls", None)
+ for param_name, param in sig.parameters.items():
+ if param.kind == inspect.Parameter.VAR_KEYWORD:
+ # Update with the **kwargs, and remove the original entry
+ # This is to help flatten out keyword arguments
+ if param_name in arguments:
+ arguments.update(arguments.pop(param_name))
+ return arguments
+
+
+def get_runnable_for_entrypoint(func: Callable[..., Any]) -> Runnable:
+ key = (func, False)
+ if key in CACHE:
+ return CACHE[key]
+ else:
+ if is_async_callable(func):
+ run = RunnableCallable(
+ None, func, name=func.__name__, trace=False, recurse=False
+ )
+ else:
+ afunc = functools.update_wrapper(
+ functools.partial(run_in_executor, None, func), func
+ )
+ run = RunnableCallable(
+ func,
+ afunc,
+ name=func.__name__,
+ trace=False,
+ recurse=False,
+ )
+ if not _lookup_module_and_qualname(func):
+ return run
+ return CACHE.setdefault(key, run)
+
+
+def get_runnable_for_task(func: Callable[..., Any]) -> Runnable:
+ key = (func, True)
+ if key in CACHE:
+ return CACHE[key]
+ else:
+ if hasattr(func, "__name__"):
+ name = func.__name__
+ elif hasattr(func, "func"):
+ name = func.func.__name__
+ elif hasattr(func, "__class__"):
+ name = func.__class__.__name__
+ else:
+ name = str(func)
+
+ if is_async_callable(func):
+ run = RunnableCallable(
+ None,
+ func,
+ explode_args=True,
+ name=name,
+ trace=False,
+ recurse=False,
+ )
+ else:
+ run = RunnableCallable(
+ func,
+ functools.wraps(func)(functools.partial(run_in_executor, None, func)),
+ explode_args=True,
+ name=name,
+ trace=False,
+ recurse=False,
+ )
+ seq = RunnableSeq(
+ run,
+ ChannelWrite([ChannelWriteEntry(RETURN)]),
+ name=name,
+ trace_inputs=functools.partial(
+ _explode_args_trace_inputs, inspect.signature(func)
+ ),
+ )
+ if not _lookup_module_and_qualname(func):
+ return seq
+ return CACHE.setdefault(key, seq)
+
+
+CACHE: dict[tuple[Callable[..., Any], bool], Runnable] = {}
+
+
+P = ParamSpec("P")
+P1 = TypeVar("P1")
+T = TypeVar("T")
+
+
+class SyncAsyncFuture(Generic[T], concurrent.futures.Future[T]):
+ def __await__(self) -> Generator[T, None, T]:
+ yield cast(T, ...)
+
+
+def call(
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ *args: Any,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ **kwargs: Any,
+) -> SyncAsyncFuture[T]:
+ return _call_with_options(
+ func,
+ args,
+ kwargs,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ timeout=coerce_timeout_policy(timeout),
+ )
+
+
+def _call_with_options(
+ func: Callable[P, Awaitable[T]] | Callable[P, T],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+) -> SyncAsyncFuture[T]:
+ if timeout is not None and not is_async_callable(func):
+ name = getattr(func, "__name__", func.__class__.__name__)
+ raise sync_timeout_unsupported(name, kind="Task")
+ config = get_config()
+ impl = config[CONF][CONFIG_KEY_CALL]
+ fut = impl(
+ func,
+ (args, kwargs),
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=config["callbacks"],
+ timeout=timeout,
+ )
+ return fut
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_checkpoint.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..081bc69bf2ffa528299b52492ecc0258f952ee60
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_checkpoint.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from datetime import datetime, timezone
+from typing import Any, cast
+
+from langchain_core.runnables import RunnableConfig
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ Checkpoint,
+)
+from langgraph.checkpoint.base.id import uuid6
+from langgraph.checkpoint.serde.types import _DeltaSnapshot
+
+from langgraph._internal._config import DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.delta import DeltaChannel
+from langgraph.managed.base import ManagedValueMapping, ManagedValueSpec
+
+LATEST_VERSION = 4
+
+GetNextVersion = Callable[[Any, None], Any]
+
+
+def empty_checkpoint() -> Checkpoint:
+ return Checkpoint(
+ v=LATEST_VERSION,
+ id=str(uuid6(clock_seq=-2)),
+ ts=datetime.now(timezone.utc).isoformat(),
+ channel_values={},
+ channel_versions={},
+ versions_seen={},
+ )
+
+
+def delta_channels_to_snapshot(
+ channels: Mapping[str, BaseChannel],
+ counters_since_delta_snapshot: Mapping[str, tuple[int, int]],
+) -> set[str]:
+ """Return the set of DeltaChannel names that should snapshot now.
+
+ A channel snapshots when EITHER its accumulated update count reaches
+ `snapshot_frequency` OR the total supersteps since its last snapshot
+ reaches `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. This is a pure
+ predicate — no mutation.
+ """
+ result: set[str] = set()
+ for name, ch in channels.items():
+ if not isinstance(ch, DeltaChannel) or not ch.is_available():
+ continue
+ updates, supersteps = counters_since_delta_snapshot.get(name, (0, 0))
+ if (
+ updates >= ch.snapshot_frequency
+ or supersteps >= DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT
+ ):
+ result.add(name)
+ return result
+
+
+def create_checkpoint(
+ checkpoint: Checkpoint,
+ channels: Mapping[str, BaseChannel] | None,
+ step: int,
+ *,
+ id: str | None = None,
+ updated_channels: set[str] | None = None,
+ get_next_version: GetNextVersion | None = None,
+ channels_to_snapshot: set[str] | None = None,
+) -> Checkpoint:
+ """Build a new Checkpoint from the previous one and live channel state.
+
+ For each name in `channels_to_snapshot`, a `_DeltaSnapshot(value)` blob
+ is written into `channel_values[k]`. Other delta channels are omitted
+ from `channel_values` — the ancestor walk reconstructs their state
+ from `checkpoint_writes`. Callers compute the set via
+ `delta_channels_to_snapshot(channels, counters)`; defaults to empty
+ (no snapshots) when not provided.
+ """
+ ts = datetime.now(timezone.utc).isoformat()
+ channels_to_snapshot = channels_to_snapshot or set()
+ if channels is None:
+ values = checkpoint["channel_values"]
+ channel_versions = checkpoint["channel_versions"]
+ else:
+ values = {}
+ channel_versions = dict(checkpoint["channel_versions"])
+ for k in channels:
+ if k not in channel_versions:
+ continue
+ ch = channels[k]
+ if k in channels_to_snapshot:
+ # In exit mode, the snapshot decision is deferred to exit
+ # time (intermediate steps have do_checkpoint=False). The
+ # channel's count may have reached snapshot_frequency over
+ # several supersteps, but the LAST superstep may not have
+ # written to this channel. In that case apply_writes()
+ # (in _algo.py) didn't bump this channel's version, so
+ # saver.put() wouldn't include it in new_versions and
+ # the snapshot blob would be silently dropped. The manual
+ # bump below closes the gap. In sync/async durability this
+ # branch is effectively dead code (the step that pushes
+ # the count to freq always writes the channel).
+ if get_next_version is not None and (
+ updated_channels is None or k not in updated_channels
+ ):
+ channel_versions[k] = get_next_version(channel_versions[k], None)
+ values[k] = _DeltaSnapshot(ch.get())
+ else:
+ v = ch.checkpoint()
+ if v is not MISSING:
+ values[k] = v
+ return Checkpoint(
+ v=LATEST_VERSION,
+ ts=ts,
+ id=id or str(uuid6(clock_seq=step)),
+ channel_values=values,
+ channel_versions=channel_versions,
+ versions_seen=checkpoint["versions_seen"],
+ updated_channels=None if updated_channels is None else sorted(updated_channels),
+ )
+
+
+def _needs_replay(spec: BaseChannel, stored: object) -> bool:
+ """True if `spec` is a `DeltaChannel` and no value is stored at this
+ checkpoint, requiring an ancestor walk to reconstruct.
+
+ `_DeltaSnapshot` blobs and plain values (migration) resolve directly via
+ `from_checkpoint` — only absence (`MISSING`) triggers replay.
+ """
+ if not isinstance(spec, DeltaChannel):
+ return False
+ return stored is MISSING
+
+
+def channels_from_checkpoint(
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ checkpoint: Checkpoint,
+ *,
+ saver: BaseCheckpointSaver | None = None,
+ config: RunnableConfig | None = None,
+) -> tuple[Mapping[str, BaseChannel], ManagedValueMapping]:
+ """Hydrate channels from a checkpoint.
+
+ For most channels, `spec.from_checkpoint(checkpoint["channel_values"][k])`
+ is sufficient. `DeltaChannel` is the exception: when the channel is
+ absent from `channel_values`, an ancestor walk via
+ `saver.get_delta_channel_history` is required to find the nearest seed
+ (`_DeltaSnapshot` blob or pre-migration plain value) and accumulate
+ the writes between it and the target. All delta channels needing
+ replay are batched into a single saver call.
+ """
+ channel_specs: dict[str, BaseChannel] = {}
+ managed_specs: dict[str, ManagedValueSpec] = {}
+ for k, v in specs.items():
+ if isinstance(v, BaseChannel):
+ channel_specs[k] = v
+ else:
+ managed_specs[k] = v
+
+ delta_channels: list[str] = [
+ k
+ for k, spec in channel_specs.items()
+ if _needs_replay(spec, checkpoint["channel_values"].get(k, MISSING))
+ ]
+ histories: Mapping[str, Any] = {}
+ if delta_channels and saver is not None and config is not None:
+ histories = saver.get_delta_channel_history(
+ config=config, channels=delta_channels
+ )
+
+ channels: dict[str, BaseChannel] = {}
+ for k, spec in channel_specs.items():
+ ch: BaseChannel
+ if k in histories:
+ delta_spec = cast(DeltaChannel, spec)
+ history = histories[k]
+ replay_ch = delta_spec.from_checkpoint(history.get("seed", MISSING))
+ replay_ch.replay_writes(history["writes"])
+ ch = replay_ch
+ else:
+ ch = spec.from_checkpoint(checkpoint["channel_values"].get(k, MISSING))
+ channels[k] = ch
+ return channels, managed_specs
+
+
+async def achannels_from_checkpoint(
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ checkpoint: Checkpoint,
+ *,
+ saver: BaseCheckpointSaver | None = None,
+ config: RunnableConfig | None = None,
+) -> tuple[Mapping[str, BaseChannel], ManagedValueMapping]:
+ """Async version of `channels_from_checkpoint`. See docstring there."""
+ channel_specs: dict[str, BaseChannel] = {}
+ managed_specs: dict[str, ManagedValueSpec] = {}
+ for k, v in specs.items():
+ if isinstance(v, BaseChannel):
+ channel_specs[k] = v
+ else:
+ managed_specs[k] = v
+
+ delta_channels: list[str] = [
+ k
+ for k, spec in channel_specs.items()
+ if _needs_replay(spec, checkpoint["channel_values"].get(k, MISSING))
+ ]
+ histories: Mapping[str, Any] = {}
+ if delta_channels and saver is not None and config is not None:
+ histories = await saver.aget_delta_channel_history(
+ config=config, channels=delta_channels
+ )
+
+ channels: dict[str, BaseChannel] = {}
+ for k, spec in channel_specs.items():
+ ch: BaseChannel
+ if k in histories:
+ delta_spec = cast(DeltaChannel, spec)
+ history = histories[k]
+ replay_ch = delta_spec.from_checkpoint(history.get("seed", MISSING))
+ replay_ch.replay_writes(history["writes"])
+ ch = replay_ch
+ else:
+ ch = spec.from_checkpoint(checkpoint["channel_values"].get(k, MISSING))
+ channels[k] = ch
+ return channels, managed_specs
+
+
+def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
+ return Checkpoint(
+ v=checkpoint["v"],
+ ts=checkpoint["ts"],
+ id=checkpoint["id"],
+ channel_values=checkpoint["channel_values"].copy(),
+ channel_versions=checkpoint["channel_versions"].copy(),
+ versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()},
+ updated_channels=checkpoint.get("updated_channels", None),
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_config.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_draw.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_draw.py
new file mode 100644
index 0000000000000000000000000000000000000000..922450df9a8bdaf122f4a4565ca0f7584b3a97fa
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_draw.py
@@ -0,0 +1,294 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Mapping, Sequence
+from typing import Any, NamedTuple, cast
+
+from langchain_core.runnables.config import RunnableConfig
+from langchain_core.runnables.graph import Graph, Node
+from langgraph.checkpoint.base import BaseCheckpointSaver
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, INPUT
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.last_value import LastValueAfterFinish
+from langgraph.constants import END, START
+from langgraph.managed.base import ManagedValueSpec
+from langgraph.pregel._algo import (
+ PregelTaskWrites,
+ apply_writes,
+ increment,
+ prepare_next_tasks,
+)
+from langgraph.pregel._checkpoint import channels_from_checkpoint, empty_checkpoint
+from langgraph.pregel._io import map_input
+from langgraph.pregel._read import PregelNode
+from langgraph.pregel._write import ChannelWrite
+from langgraph.types import All, Checkpointer
+
+
+class Edge(NamedTuple):
+ source: str
+ target: str
+ conditional: bool
+ data: str | None
+
+
+class TriggerEdge(NamedTuple):
+ source: str
+ conditional: bool
+ data: str | None
+
+
+def draw_graph(
+ config: RunnableConfig,
+ *,
+ nodes: dict[str, PregelNode],
+ specs: dict[str, BaseChannel | ManagedValueSpec],
+ input_channels: str | Sequence[str],
+ interrupt_after_nodes: All | Sequence[str],
+ interrupt_before_nodes: All | Sequence[str],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ checkpointer: Checkpointer,
+ subgraphs: dict[str, Graph],
+ limit: int = 250,
+) -> Graph:
+ """Get the graph for this Pregel instance.
+
+ Args:
+ config: The configuration to use for the graph.
+ subgraphs: The subgraphs to include in the graph.
+ checkpointer: The checkpointer to use for the graph.
+
+ Returns:
+ The graph for this Pregel instance.
+ """
+ # (src, dest, is_conditional, label)
+ edges: set[Edge] = set()
+
+ step = -1
+ checkpoint = empty_checkpoint()
+ get_next_version = (
+ checkpointer.get_next_version
+ if isinstance(checkpointer, BaseCheckpointSaver)
+ else increment
+ )
+ channels, managed = channels_from_checkpoint(
+ specs,
+ checkpoint,
+ )
+ static_seen: set[Any] = set()
+ sources: dict[str, set[TriggerEdge]] = {}
+ step_sources: dict[str, set[TriggerEdge]] = {}
+ static_declared_writes: dict[str, set[TriggerEdge]] = defaultdict(set)
+ # remove node mappers
+ nodes = {
+ k: v.copy(update={"mapper": None}) if v.mapper is not None else v
+ for k, v in nodes.items()
+ }
+ # apply input writes
+ input_writes = list(map_input(input_channels, {}))
+ updated_channels = apply_writes(
+ checkpoint,
+ channels,
+ [
+ PregelTaskWrites((), INPUT, input_writes, []),
+ ],
+ get_next_version,
+ trigger_to_nodes,
+ )
+ # prepare first tasks
+ tasks = prepare_next_tasks(
+ checkpoint,
+ [],
+ nodes,
+ channels,
+ managed,
+ config,
+ step,
+ -1,
+ for_execution=True,
+ store=None,
+ checkpointer=None,
+ manager=None,
+ trigger_to_nodes=trigger_to_nodes,
+ updated_channels=updated_channels,
+ )
+ start_tasks = tasks
+ # run the pregel loop
+ for step in range(step, limit):
+ if not tasks:
+ break
+ conditionals: dict[tuple[str, str, Any], str | None] = {}
+ # run task writers
+ for task in tasks.values():
+ for w in task.writers:
+ # apply regular writes
+ if isinstance(w, ChannelWrite):
+ empty_input = (
+ cast(BaseChannel, specs["__root__"]).ValueType()
+ if "__root__" in specs
+ else None
+ )
+ w.invoke(empty_input, task.config)
+ # apply conditional writes declared for static analysis, only once
+ if w not in static_seen:
+ static_seen.add(w)
+ # apply static writes
+ if writes := ChannelWrite.get_static_writes(w):
+ # END writes are not written, but become edges directly
+ for t in writes:
+ if t[0] == END:
+ edges.add(Edge(task.name, t[0], True, t[2]))
+ writes = [t for t in writes if t[0] != END]
+ conditionals.update(
+ {(task.name, t[0], t[1] or None): t[2] for t in writes}
+ )
+ # record static writes for edge creation
+ for t in writes:
+ static_declared_writes[task.name].add(
+ TriggerEdge(t[0], True, t[2])
+ )
+ task.config[CONF][CONFIG_KEY_SEND]([t[:2] for t in writes])
+ # collect sources
+ step_sources = {}
+ for task in tasks.values():
+ task_edges = {
+ TriggerEdge(
+ w[0],
+ (task.name, w[0], w[1] or None) in conditionals,
+ conditionals.get((task.name, w[0], w[1] or None)),
+ )
+ for w in task.writes
+ }
+ task_edges |= static_declared_writes.get(task.name, set())
+ step_sources[task.name] = task_edges
+ sources.update(step_sources)
+ # invert triggers
+ trigger_to_sources: dict[str, set[TriggerEdge]] = defaultdict(set)
+ for src, triggers in sources.items():
+ for trigger, cond, label in triggers:
+ trigger_to_sources[trigger].add(TriggerEdge(src, cond, label))
+ # apply writes
+ updated_channels = apply_writes(
+ checkpoint, channels, tasks.values(), get_next_version, trigger_to_nodes
+ )
+ # prepare next tasks
+ tasks = prepare_next_tasks(
+ checkpoint,
+ [],
+ nodes,
+ channels,
+ managed,
+ config,
+ step,
+ limit,
+ for_execution=True,
+ store=None,
+ checkpointer=None,
+ manager=None,
+ trigger_to_nodes=trigger_to_nodes,
+ updated_channels=updated_channels,
+ )
+ # collect deferred nodes
+ deferred_nodes: set[str] = set()
+ edges_to_deferred_nodes: set[Edge] = set()
+ for channel, item in channels.items():
+ if isinstance(item, LastValueAfterFinish):
+ deferred_node = channel.split(":", 2)[-1]
+ deferred_nodes.add(deferred_node)
+ # collect edges
+ for task in tasks.values():
+ added = False
+ for trigger in task.triggers:
+ for src, cond, label in sorted(trigger_to_sources[trigger]):
+ # record edge to be reviewed later
+ if task.name in deferred_nodes:
+ edges_to_deferred_nodes.add(Edge(src, task.name, cond, label))
+ edges.add(Edge(src, task.name, cond, label))
+ # if the edge is from this step, skip adding the implicit edges
+ if (trigger, cond, label) in step_sources.get(src, set()):
+ added = True
+ else:
+ sources[src].discard(TriggerEdge(trigger, cond, label))
+ # if no edges from this step, add implicit edges from all previous tasks
+ if not added:
+ for src in step_sources:
+ edges.add(Edge(src, task.name, True, None))
+
+ # assemble the graph
+ graph = Graph()
+ # add nodes
+ for name, node in nodes.items():
+ metadata = dict(node.metadata or {})
+ if name in deferred_nodes:
+ metadata["defer"] = True
+ if name in interrupt_before_nodes and name in interrupt_after_nodes:
+ metadata["__interrupt"] = "before,after"
+ elif name in interrupt_before_nodes:
+ metadata["__interrupt"] = "before"
+ elif name in interrupt_after_nodes:
+ metadata["__interrupt"] = "after"
+ graph.add_node(node.bound, name, metadata=metadata or None)
+ # add start node
+ if START not in nodes:
+ graph.add_node(None, START)
+ for task in start_tasks.values():
+ add_edge(graph, START, task.name)
+ # add discovered edges
+ for src, dest, is_conditional, label in sorted(edges):
+ add_edge(
+ graph,
+ src,
+ dest,
+ data=label if label != dest else None,
+ conditional=is_conditional,
+ )
+ # add end edges
+ termini = {d for _, d, _, _ in edges if d != END}.difference(
+ s for s, _, _, _ in edges
+ )
+ end_edge_exists = any(d == END for _, d, _, _ in edges)
+ if termini:
+ for src in sorted(termini):
+ add_edge(graph, src, END)
+ elif len(step_sources) == 1 and not end_edge_exists:
+ for src in sorted(step_sources):
+ add_edge(graph, src, END, conditional=True)
+ # replace subgraphs
+ for name, subgraph in subgraphs.items():
+ if (
+ len(subgraph.nodes) > 1
+ and name in graph.nodes
+ and subgraph.first_node()
+ and subgraph.last_node()
+ ):
+ subgraph.trim_first_node()
+ subgraph.trim_last_node()
+ # replace the node with the subgraph
+ graph.nodes.pop(name)
+ first, last = graph.extend(subgraph, prefix=name)
+ for idx, edge in enumerate(graph.edges):
+ if edge.source == name:
+ edge = edge.copy(source=cast(Node, last).id)
+ if edge.target == name:
+ edge = edge.copy(target=cast(Node, first).id)
+ graph.edges[idx] = edge
+
+ return graph
+
+
+def add_edge(
+ graph: Graph,
+ source: str,
+ target: str,
+ *,
+ data: Any | None = None,
+ conditional: bool = False,
+) -> None:
+ """Add an edge to the graph."""
+ for edge in graph.edges:
+ if edge.source == source and edge.target == target:
+ return
+ if target not in graph.nodes and target == END:
+ graph.add_node(None, END)
+ graph.add_edge(graph.nodes[source], graph.nodes[target], data, conditional)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_executor.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..10a43cf2b3cb8e20030bec5f5526b4546089bf8f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_executor.py
@@ -0,0 +1,223 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import time
+from collections.abc import Awaitable, Callable, Coroutine
+from contextlib import AbstractAsyncContextManager, AbstractContextManager, ExitStack
+from contextvars import copy_context
+from types import TracebackType
+from typing import (
+ Protocol,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables.config import get_executor_for_config
+from typing_extensions import ParamSpec
+
+from langgraph._internal._future import CONTEXT_NOT_SUPPORTED, run_coroutine_threadsafe
+from langgraph.errors import GraphBubbleUp
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+class Submit(Protocol[P, T]):
+ def __call__( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, T],
+ *args: P.args,
+ __name__: str | None = None,
+ __cancel_on_exit__: bool = False,
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False,
+ **kwargs: P.kwargs,
+ ) -> concurrent.futures.Future[T]: ...
+
+
+class BackgroundExecutor(AbstractContextManager):
+ """A context manager that runs sync tasks in the background.
+ Uses a thread pool executor to delegate tasks to separate threads.
+ On exit,
+ - cancels any (not yet started) tasks with `__cancel_on_exit__=True`
+ - waits for all tasks to finish
+ - re-raises the first exception from tasks with `__reraise_on_exit__=True`"""
+
+ def __init__(self, config: RunnableConfig) -> None:
+ self.stack = ExitStack()
+ self.executor = self.stack.enter_context(get_executor_for_config(config))
+ # mapping of Future to (__cancel_on_exit__, __reraise_on_exit__) flags
+ self.tasks: dict[concurrent.futures.Future, tuple[bool, bool]] = {}
+
+ def submit( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, T],
+ *args: P.args,
+ __name__: str | None = None, # currently not used in sync version
+ __cancel_on_exit__: bool = False, # for sync, can cancel only if not started
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False,
+ **kwargs: P.kwargs,
+ ) -> concurrent.futures.Future[T]:
+ ctx = copy_context()
+ if __next_tick__:
+ task = cast(
+ concurrent.futures.Future[T],
+ self.executor.submit(next_tick, ctx.run, fn, *args, **kwargs), # type: ignore[arg-type]
+ )
+ else:
+ task = self.executor.submit(ctx.run, fn, *args, **kwargs)
+ self.tasks[task] = (__cancel_on_exit__, __reraise_on_exit__)
+ # add a callback to remove the task from the tasks dict when it's done
+ task.add_done_callback(self.done)
+ return task
+
+ def done(self, task: concurrent.futures.Future) -> None:
+ """Remove the task from the tasks dict when it's done."""
+ try:
+ task.result()
+ except GraphBubbleUp:
+ # This exception is an interruption signal, not an error
+ # so we don't want to re-raise it on exit
+ self.tasks.pop(task)
+ except BaseException:
+ pass
+ else:
+ self.tasks.pop(task)
+
+ def __enter__(self) -> Submit:
+ return self.submit
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # copy the tasks as done() callback may modify the dict
+ tasks = self.tasks.copy()
+ # cancel all tasks that should be cancelled
+ for task, (cancel, _) in tasks.items():
+ if cancel:
+ task.cancel()
+ # wait for all tasks to finish
+ if pending := {t for t in tasks if not t.done()}:
+ concurrent.futures.wait(pending)
+ # shutdown the executor
+ self.stack.__exit__(exc_type, exc_value, traceback)
+ # if there's already an exception being raised, don't raise another one
+ if exc_type is None:
+ # re-raise the first exception that occurred in a task
+ for task, (_, reraise) in tasks.items():
+ if not reraise:
+ continue
+ try:
+ task.result()
+ except concurrent.futures.CancelledError:
+ pass
+
+
+class AsyncBackgroundExecutor(AbstractAsyncContextManager):
+ """A context manager that runs async tasks in the background.
+ Uses the current event loop to delegate tasks to asyncio tasks.
+ On exit,
+ - cancels any tasks with `__cancel_on_exit__=True`
+ - waits for all tasks to finish
+ - re-raises the first exception from tasks with `__reraise_on_exit__=True`
+ ignoring CancelledError"""
+
+ def __init__(self, config: RunnableConfig) -> None:
+ self.tasks: dict[asyncio.Future, tuple[bool, bool]] = {}
+ self.sentinel = object()
+ self.loop = asyncio.get_running_loop()
+ if max_concurrency := config.get("max_concurrency"):
+ self.semaphore: asyncio.Semaphore | None = asyncio.Semaphore(
+ max_concurrency
+ )
+ else:
+ self.semaphore = None
+
+ def submit( # type: ignore[valid-type]
+ self,
+ fn: Callable[P, Awaitable[T]],
+ *args: P.args,
+ __name__: str | None = None,
+ __cancel_on_exit__: bool = False,
+ __reraise_on_exit__: bool = True,
+ __next_tick__: bool = False, # noop in async (always True)
+ **kwargs: P.kwargs,
+ ) -> asyncio.Future[T]:
+ coro = cast(Coroutine[None, None, T], fn(*args, **kwargs))
+ if self.semaphore:
+ coro = gated(self.semaphore, coro)
+ if CONTEXT_NOT_SUPPORTED:
+ task = run_coroutine_threadsafe(
+ coro, self.loop, name=__name__, lazy=__next_tick__
+ )
+ else:
+ task = run_coroutine_threadsafe(
+ coro,
+ self.loop,
+ name=__name__,
+ context=copy_context(),
+ lazy=__next_tick__,
+ )
+ self.tasks[task] = (__cancel_on_exit__, __reraise_on_exit__)
+ task.add_done_callback(self.done)
+ return task
+
+ def done(self, task: asyncio.Future) -> None:
+ try:
+ if exc := task.exception():
+ # This exception is an interruption signal, not an error
+ # so we don't want to re-raise it on exit
+ if isinstance(exc, GraphBubbleUp):
+ self.tasks.pop(task)
+ else:
+ self.tasks.pop(task)
+ except asyncio.CancelledError:
+ self.tasks.pop(task)
+
+ async def __aenter__(self) -> Submit:
+ return self.submit
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ # copy the tasks as done() callback may modify the dict
+ tasks = self.tasks.copy()
+ # cancel all tasks that should be cancelled
+ for task, (cancel, _) in tasks.items():
+ if cancel:
+ task.cancel(self.sentinel)
+ # wait for all tasks to finish
+ if tasks:
+ await asyncio.wait(tasks)
+ # if there's already an exception being raised, don't raise another one
+ if exc_type is None:
+ # re-raise the first exception that occurred in a task
+ for task, (_, reraise) in tasks.items():
+ if not reraise:
+ continue
+ try:
+ if exc := task.exception():
+ raise exc
+ except asyncio.CancelledError:
+ pass
+
+
+async def gated(semaphore: asyncio.Semaphore, coro: Coroutine[None, None, T]) -> T:
+ """A coroutine that waits for a semaphore before running another coroutine."""
+ async with semaphore:
+ return await coro
+
+
+def next_tick(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
+ """A function that yields control to other threads before running another function."""
+ time.sleep(0)
+ return fn(*args, **kwargs)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_io.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c05dbda70ed04f1038268a201000d5141535832
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_io.py
@@ -0,0 +1,174 @@
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Literal
+
+from langgraph._internal._constants import (
+ ERROR,
+ INTERRUPT,
+ NULL_TASK_ID,
+ RESUME,
+ RETURN,
+ TASKS,
+)
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.channels.base import BaseChannel, EmptyChannelError
+from langgraph.constants import START, TAG_HIDDEN
+from langgraph.errors import InvalidUpdateError
+from langgraph.pregel._log import logger
+from langgraph.types import Command, PregelExecutableTask, Send
+
+
+def read_channel(
+ channels: Mapping[str, BaseChannel],
+ chan: str,
+ *,
+ catch: bool = True,
+) -> Any:
+ try:
+ return channels[chan].get()
+ except EmptyChannelError:
+ if catch:
+ return None
+ else:
+ raise
+
+
+def read_channels(
+ channels: Mapping[str, BaseChannel],
+ select: Sequence[str] | str,
+ *,
+ skip_empty: bool = True,
+) -> dict[str, Any] | Any:
+ if isinstance(select, str):
+ return read_channel(channels, select)
+ else:
+ values: dict[str, Any] = {}
+ for k in select:
+ try:
+ values[k] = read_channel(channels, k, catch=not skip_empty)
+ except EmptyChannelError:
+ pass
+ return values
+
+
+def map_command(cmd: Command) -> Iterator[tuple[str, str, Any]]:
+ """Map input chunk to a sequence of pending writes in the form (channel, value)."""
+ if cmd.graph == Command.PARENT:
+ raise InvalidUpdateError("There is no parent graph")
+ if cmd.goto:
+ if isinstance(cmd.goto, (tuple, list)):
+ sends = cmd.goto
+ else:
+ sends = [cmd.goto]
+ for send in sends:
+ if isinstance(send, Send):
+ yield (NULL_TASK_ID, TASKS, send)
+ elif isinstance(send, str):
+ yield (NULL_TASK_ID, f"branch:to:{send}", START)
+ else:
+ raise TypeError(
+ f"In Command.goto, expected Send/str, got {type(send).__name__}"
+ )
+ if cmd.resume is not None:
+ yield (NULL_TASK_ID, RESUME, cmd.resume)
+ if cmd.update:
+ for k, v in cmd._update_as_tuples():
+ yield (NULL_TASK_ID, k, v)
+
+
+def map_input(
+ input_channels: str | Sequence[str],
+ chunk: dict[str, Any] | Any | None,
+) -> Iterator[tuple[str, Any]]:
+ """Map input chunk to a sequence of pending writes in the form (channel, value)."""
+ if chunk is None:
+ return
+ elif isinstance(input_channels, str):
+ yield (input_channels, chunk)
+ else:
+ if not isinstance(chunk, dict):
+ raise TypeError(f"Expected chunk to be a dict, got {type(chunk).__name__}")
+ for k in chunk:
+ if k in input_channels:
+ yield (k, chunk[k])
+ else:
+ logger.warning(f"Input channel {k} not found in {input_channels}")
+
+
+def map_output_values(
+ output_channels: str | Sequence[str],
+ pending_writes: Literal[True] | Sequence[tuple[str, Any]],
+ channels: Mapping[str, BaseChannel],
+) -> Iterator[dict[str, Any] | Any]:
+ """Map pending writes (a sequence of tuples (channel, value)) to output chunk."""
+ if isinstance(output_channels, str):
+ if pending_writes is True or any(
+ chan == output_channels for chan, _ in pending_writes
+ ):
+ yield read_channel(channels, output_channels)
+ else:
+ if pending_writes is True or {
+ c for c, _ in pending_writes if c in output_channels
+ }:
+ yield read_channels(channels, output_channels)
+
+
+def map_output_updates(
+ output_channels: str | Sequence[str],
+ tasks: list[tuple[PregelExecutableTask, Sequence[tuple[str, Any]]]],
+ cached: bool = False,
+) -> Iterator[dict[str, Any | dict[str, Any]]]:
+ """Map pending writes (a sequence of tuples (channel, value)) to output chunk."""
+ output_tasks = [
+ (t, ww)
+ for t, ww in tasks
+ if (not t.config or TAG_HIDDEN not in t.config.get("tags", EMPTY_SEQ))
+ and ww[0][0] != ERROR
+ and ww[0][0] != INTERRUPT
+ ]
+ if not output_tasks:
+ return
+ updated: list[tuple[str, Any]] = []
+ for task, writes in output_tasks:
+ rtn = next((value for chan, value in writes if chan == RETURN), MISSING)
+ if rtn is not MISSING:
+ updated.append((task.name, rtn))
+ elif isinstance(output_channels, str):
+ updated.extend(
+ (task.name, value) for chan, value in writes if chan == output_channels
+ )
+ elif any(chan in output_channels for chan, _ in writes):
+ counts = Counter(chan for chan, _ in writes)
+ if any(counts[chan] > 1 for chan in output_channels):
+ updated.extend(
+ (
+ task.name,
+ {chan: value},
+ )
+ for chan, value in writes
+ if chan in output_channels
+ )
+ else:
+ updated.append(
+ (
+ task.name,
+ {
+ chan: value
+ for chan, value in writes
+ if chan in output_channels
+ },
+ )
+ )
+ grouped: dict[str, Any] = {t.name: [] for t, _ in output_tasks}
+ for node, value in updated:
+ grouped[node].append(value)
+ for node, value in grouped.items():
+ if len(value) == 0:
+ grouped[node] = None
+ if len(value) == 1:
+ grouped[node] = value[0]
+ if cached:
+ grouped["__metadata__"] = {"cached": cached}
+ yield grouped
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_log.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd127777b23fab1a3daa78b552a93b1a13ce38b1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_log.py
@@ -0,0 +1,3 @@
+import logging
+
+logger = logging.getLogger("langgraph")
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_loop.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b98fc91cef3d120a1742183ce0a9e0374352200
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_loop.py
@@ -0,0 +1,1954 @@
+from __future__ import annotations
+
+import asyncio
+import binascii
+import concurrent.futures
+from collections import defaultdict, deque
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from contextlib import (
+ AbstractAsyncContextManager,
+ AbstractContextManager,
+ AsyncExitStack,
+ ExitStack,
+)
+from datetime import datetime, timezone
+from inspect import signature
+from types import TracebackType
+from typing import (
+ Any,
+ Literal,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.callbacks import AsyncParentRunManager, ParentRunManager
+from langchain_core.runnables import RunnableConfig
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import (
+ WRITES_IDX_MAP,
+ BaseCheckpointSaver,
+ ChannelVersions,
+ Checkpoint,
+ CheckpointMetadata,
+ CheckpointTuple,
+ PendingWrite,
+)
+from langgraph.store.base import BaseStore
+from typing_extensions import ParamSpec, Self
+
+from langgraph._internal._config import patch_configurable
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_REPLAY_STATE,
+ CONFIG_KEY_RESUME_MAP,
+ CONFIG_KEY_RESUMING,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SCRATCHPAD,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INPUT,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PUSH,
+ RESUME,
+ TASKS,
+)
+from langgraph._internal._replay import ReplayState
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import EMPTY_SEQ, MISSING
+from langgraph.callbacks import (
+ GraphInterruptEvent,
+ GraphLifecycleEvent,
+ GraphResumeEvent,
+)
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.delta import DeltaChannel
+from langgraph.channels.untracked_value import UntrackedValue
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import (
+ EmptyInputError,
+ GraphInterrupt,
+)
+from langgraph.managed.base import (
+ ManagedValueMapping,
+ ManagedValueSpec,
+)
+from langgraph.pregel._algo import (
+ Call,
+ GetNextVersion,
+ PregelTaskWrites,
+ apply_writes,
+ checkpoint_null_version,
+ increment,
+ prepare_next_tasks,
+ prepare_node_error_handler_task,
+ prepare_single_task,
+ sanitize_untracked_values_in_send,
+ should_interrupt,
+ task_path_str,
+)
+from langgraph.pregel._checkpoint import (
+ achannels_from_checkpoint,
+ channels_from_checkpoint,
+ copy_checkpoint,
+ create_checkpoint,
+ delta_channels_to_snapshot,
+ empty_checkpoint,
+)
+from langgraph.pregel._executor import (
+ AsyncBackgroundExecutor,
+ BackgroundExecutor,
+ Submit,
+)
+from langgraph.pregel._io import (
+ map_command,
+ map_input,
+ map_output_updates,
+ map_output_values,
+ read_channels,
+)
+from langgraph.pregel._read import PregelNode
+from langgraph.pregel._utils import get_new_channel_versions, is_xxh3_128_hexdigest
+from langgraph.pregel.debug import (
+ map_debug_checkpoint,
+ map_debug_task_results,
+ map_debug_tasks,
+)
+from langgraph.pregel.protocol import StreamChunk, StreamProtocol
+from langgraph.runtime import RunControl, Runtime
+from langgraph.types import (
+ All,
+ CachePolicy,
+ Command,
+ Durability,
+ Interrupt,
+ PregelExecutableTask,
+ RetryPolicy,
+ Send,
+ StreamMode,
+)
+
+V = TypeVar("V")
+P = ParamSpec("P")
+
+
+WritesT = Sequence[tuple[str, Any]]
+
+
+def DuplexStream(*streams: StreamProtocol) -> StreamProtocol:
+ def __call__(value: StreamChunk) -> None:
+ for stream in streams:
+ if value[1] in stream.modes:
+ stream(value)
+
+ return StreamProtocol(__call__, {mode for s in streams for mode in s.modes})
+
+
+class PregelLoop:
+ config: RunnableConfig
+ store: BaseStore | None
+ stream: StreamProtocol | None
+ step: int
+ stop: int
+
+ input: Any | None
+ cache: BaseCache[WritesT] | None
+ checkpointer: BaseCheckpointSaver | None
+ nodes: Mapping[str, PregelNode]
+ specs: Mapping[str, BaseChannel | ManagedValueSpec]
+ input_keys: str | Sequence[str]
+ output_keys: str | Sequence[str]
+ stream_keys: str | Sequence[str]
+ is_replaying: bool
+ is_nested: bool
+ manager: None | AsyncParentRunManager | ParentRunManager
+ interrupt_after: All | Sequence[str]
+ interrupt_before: All | Sequence[str]
+ durability: Durability
+ retry_policy: Sequence[RetryPolicy]
+ cache_policy: CachePolicy | None
+
+ checkpointer_get_next_version: GetNextVersion
+ checkpointer_put_writes: Callable[[RunnableConfig, WritesT, str], Any] | None
+ checkpointer_put_writes_accepts_task_path: bool
+ _checkpointer_put_after_previous: (
+ Callable[
+ [
+ concurrent.futures.Future | None,
+ RunnableConfig,
+ Checkpoint,
+ str,
+ ChannelVersions,
+ ],
+ Any,
+ ]
+ | None
+ )
+ _migrate_checkpoint: Callable[[Checkpoint], None] | None
+ submit: Submit
+ channels: Mapping[str, BaseChannel]
+ # Futures from `checkpointer.put_writes` calls that produced delta-channel
+ # writes. `_checkpointer_put_after_previous` drains this list (swap to a
+ # local `futs` then reset to `[]` and wait/gather) before putting the
+ # next checkpoint, so a checkpoint never becomes durable before the
+ # writes that produced it. Initialised to `[]` in both sync and async
+ # `__enter__`; stays `None` only when no checkpointer.
+ _delta_write_futs: list[Any] | None = None
+
+ # Same pattern as `_delta_write_futs` but for error-handler writes.
+ # When `put_writes` persists an ERROR_SOURCE_NODE marker, the future is
+ # appended here. `schedule_error_handler` / `aschedule_error_handler`
+ # drain this list so the write is durable before the handler starts.
+ _error_handler_write_futs: list[Any] | None = None
+
+ # Exit-mode accumulator: every delta-channel write produced during this
+ # run (input writes from `_first` + per-superstep writes captured in
+ # `after_tick`). At exit, `_put_exit_delta_writes` filters out channels
+ # that will snapshot, then persists the rest under an anchor parent.
+ # `None` when not in exit mode (so the capture sites are no-ops).
+ # Each tuple is `(step, task_id, channel, value)` — `step` drives the
+ # synthetic step-prefixed task_id used to preserve chronological order
+ # under the saver's `ORDER BY task_id, idx` sorting.
+ _exit_delta_writes: list[tuple[int, str, str, Any]] | None = None
+
+ # The checkpoint_config that points at the parent loaded at `__enter__`
+ # (or the synthetic-empty checkpoint, on first run). We capture it
+ # eagerly because every `_put_checkpoint` advances `self.checkpoint_config`
+ # to the newly-saved checkpoint's id — by exit time the original parent
+ # config would otherwise be lost. `_put_exit_delta_writes` uses this:
+ # on resumed runs as the anchor for exit delta writes; on first runs
+ # to derive the lazy stub's config (its `checkpoint_id` is the
+ # synthetic-empty id we want the stub persisted under).
+ _initial_checkpoint_config: RunnableConfig
+
+ # True iff the saver actually returned a tuple at `__enter__`. False
+ # on the first-ever run for a thread (no parent persisted yet).
+ # `_put_exit_delta_writes` uses this to decide between anchoring on
+ # the existing parent (True) or creating a lazy stub (False).
+ _has_persisted_parent: bool = False
+
+ managed: ManagedValueMapping
+ checkpoint: Checkpoint
+ checkpoint_id_saved: str
+ checkpoint_ns: tuple[str, ...]
+ checkpoint_config: RunnableConfig
+ checkpoint_metadata: CheckpointMetadata
+ checkpoint_pending_writes: list[PendingWrite]
+ checkpoint_previous_versions: dict[str, str | float | int]
+ prev_checkpoint_config: RunnableConfig | None
+
+ status: Literal[
+ "input",
+ "pending",
+ "done",
+ "draining",
+ "interrupt_before",
+ "interrupt_after",
+ "out_of_steps",
+ ]
+ control: RunControl | None
+ tasks: dict[str, PregelExecutableTask]
+ output: None | dict[str, Any] | Any = None
+ updated_channels: set[str] | None = None
+ _graph_lifecycle_events: deque[GraphLifecycleEvent]
+ _has_graph_lifecycle_callbacks: bool
+
+ # public
+
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ input_keys: str | Sequence[str],
+ output_keys: str | Sequence[str],
+ stream_keys: str | Sequence[str],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ self.stream = stream
+ self.config = config
+ self.store = store
+ self.step = 0
+ self.stop = 0
+ self.input = input
+ self.checkpointer = checkpointer
+ self.cache = cache
+ self.nodes = nodes
+ self.specs = specs
+ self.input_keys = input_keys
+ self.output_keys = output_keys
+ self.stream_keys = stream_keys
+ self.interrupt_after = interrupt_after
+ self.interrupt_before = interrupt_before
+ self.manager = manager
+ self.is_nested = CONFIG_KEY_TASK_ID in self.config.get(CONF, {})
+ self.is_replaying = CONFIG_KEY_CHECKPOINT_ID in config[CONF]
+ self._migrate_checkpoint = migrate_checkpoint
+ self.trigger_to_nodes = trigger_to_nodes
+ self.retry_policy = retry_policy
+ self.cache_policy = cache_policy
+ self.durability = durability
+ self._has_graph_lifecycle_callbacks = has_graph_lifecycle_callbacks
+ self._graph_lifecycle_events = deque()
+ if self.stream is not None and CONFIG_KEY_STREAM in config[CONF]:
+ self.stream = DuplexStream(self.stream, config[CONF][CONFIG_KEY_STREAM])
+ scratchpad: PregelScratchpad | None = config[CONF].get(CONFIG_KEY_SCRATCHPAD)
+ if isinstance(scratchpad, PregelScratchpad):
+ # if count is > 0, append to checkpoint_ns
+ # if count is 0, leave as is
+ if cnt := scratchpad.subgraph_counter():
+ self.config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: NS_SEP.join(
+ (
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS],
+ str(cnt),
+ )
+ )
+ },
+ )
+ if not self.is_nested and config[CONF].get(CONFIG_KEY_CHECKPOINT_NS):
+ self.config = patch_configurable(
+ self.config,
+ {CONFIG_KEY_CHECKPOINT_NS: "", CONFIG_KEY_CHECKPOINT_ID: None},
+ )
+ if (
+ CONFIG_KEY_CHECKPOINT_MAP in self.config[CONF]
+ and self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS)
+ in self.config[CONF][CONFIG_KEY_CHECKPOINT_MAP]
+ ):
+ self.checkpoint_config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_CHECKPOINT_ID: self.config[CONF][
+ CONFIG_KEY_CHECKPOINT_MAP
+ ][self.config[CONF][CONFIG_KEY_CHECKPOINT_NS]]
+ },
+ )
+ else:
+ self.checkpoint_config = self.config
+ if thread_id := self.checkpoint_config[CONF].get(CONFIG_KEY_THREAD_ID):
+ if not isinstance(thread_id, str):
+ self.checkpoint_config = patch_configurable(
+ self.checkpoint_config,
+ {CONFIG_KEY_THREAD_ID: str(thread_id)},
+ )
+ self.checkpoint_ns = (
+ tuple(cast(str, self.config[CONF][CONFIG_KEY_CHECKPOINT_NS]).split(NS_SEP))
+ if self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS)
+ else ()
+ )
+ self.prev_checkpoint_config = None
+ runtime = self.config[CONF].get(CONFIG_KEY_RUNTIME)
+ self.control = runtime.control if isinstance(runtime, Runtime) else None
+
+ def _push_graph_lifecycle_event(
+ self,
+ kind: Literal["resume", "interrupt"],
+ *,
+ interrupts: tuple[Interrupt, ...] = (),
+ ) -> None:
+ # drain status never reaches lifecycle events: tick() returns False
+ # before pushing, and interrupts are raised through GraphInterrupt
+ if self.status == "draining":
+ raise RuntimeError("Draining status cannot emit lifecycle events")
+ status = self.status
+ if kind == "resume":
+ self._graph_lifecycle_events.append(
+ GraphResumeEvent(
+ run_id=None,
+ status=status,
+ checkpoint_id=self.checkpoint["id"],
+ checkpoint_ns=self.checkpoint_ns,
+ )
+ )
+ elif kind == "interrupt":
+ self._graph_lifecycle_events.append(
+ GraphInterruptEvent(
+ run_id=None,
+ status=status,
+ checkpoint_id=self.checkpoint["id"],
+ checkpoint_ns=self.checkpoint_ns,
+ interrupts=interrupts,
+ )
+ )
+ else:
+ msg = f"Unknown graph lifecycle event type: {kind}"
+ raise AssertionError(msg)
+
+ def _pop_lifecycle_event(self) -> GraphLifecycleEvent | None:
+ if not self._graph_lifecycle_events:
+ return None
+ return self._graph_lifecycle_events.popleft()
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ if not writes:
+ return
+ # deduplicate writes to special channels, last write wins
+ if all(w[0] in WRITES_IDX_MAP for w in writes):
+ writes = list({w[0]: w for w in writes}.values())
+ if task_id == NULL_TASK_ID:
+ # writes for the null task are accumulated
+ self.checkpoint_pending_writes = [
+ w
+ for w in self.checkpoint_pending_writes
+ if w[0] != task_id or w[1] not in WRITES_IDX_MAP
+ ]
+ writes_to_save: WritesT = [
+ w[1:] for w in self.checkpoint_pending_writes if w[0] == task_id
+ ] + list(writes)
+ else:
+ # remove existing writes for this task
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[0] != task_id
+ ]
+ writes_to_save = writes
+
+ # check if any writes are to an UntrackedValue channel
+ if any(
+ isinstance(channel, UntrackedValue) for channel in self.channels.values()
+ ):
+ # we do not persist untracked values in checkpoints
+ writes_to_save = [
+ # sanitize UntrackedValues that are nested within Send packets
+ (
+ (c, sanitize_untracked_values_in_send(v, self.channels))
+ if c == TASKS and isinstance(v, Send)
+ else (c, v)
+ )
+ for c, v in writes_to_save
+ # dont persist UntrackedValue channel writes
+ if not isinstance(self.specs.get(c), UntrackedValue)
+ ]
+
+ # save writes
+ self.checkpoint_pending_writes.extend((task_id, c, v) for c, v in writes)
+ if self.durability != "exit" and self.checkpointer_put_writes is not None:
+ config = patch_configurable(
+ self.checkpoint_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ )
+ if self.checkpointer_put_writes_accepts_task_path:
+ if hasattr(self, "tasks"):
+ task = self.tasks.get(task_id)
+ else:
+ task = None
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes_to_save,
+ task_id,
+ task_path_str(task.path) if task else "",
+ )
+ else:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes_to_save,
+ task_id,
+ )
+ if self._delta_write_futs is not None and any(
+ isinstance(self.specs.get(c), DeltaChannel) for c, _ in writes_to_save
+ ):
+ self._delta_write_futs.append(fut)
+ # ERROR_SOURCE_NODE is only appended by commit() when the task
+ # has an error handler (_should_route_to_error_handler), so this
+ # check naturally limits future collection to those tasks.
+ if self._error_handler_write_futs is not None and any(
+ c == ERROR_SOURCE_NODE for c, _ in writes
+ ):
+ self._error_handler_write_futs.append(fut)
+ # output writes
+ if hasattr(self, "tasks"):
+ self.output_writes(task_id, writes)
+
+ def _put_pending_writes(self) -> None:
+ if self.checkpointer_put_writes is None:
+ return
+ if not self.checkpoint_pending_writes:
+ return
+ # patch config
+ config = patch_configurable(
+ self.checkpoint_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ )
+ # group by task id
+ by_task = defaultdict(list)
+ for task_id, channel, value in self.checkpoint_pending_writes:
+ by_task[task_id].append((channel, value))
+ # submit writes to checkpointer
+ for task_id, writes in by_task.items():
+ if self.checkpointer_put_writes_accepts_task_path and hasattr(
+ self, "tasks"
+ ):
+ task = self.tasks.get(task_id)
+ self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes,
+ task_id,
+ task_path_str(task.path) if task else "",
+ )
+ else:
+ self.submit(
+ self.checkpointer_put_writes,
+ config,
+ writes,
+ task_id,
+ )
+
+ def accept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ """Accept a PUSH from a task, potentially returning a new task to start."""
+ checkpoint_id_bytes = binascii.unhexlify(self.checkpoint["id"].replace("-", ""))
+ null_version = checkpoint_null_version(self.checkpoint)
+ if pushed := cast(
+ PregelExecutableTask | None,
+ prepare_single_task(
+ (PUSH, task.path, write_idx, task.id, call),
+ None,
+ checkpoint=self.checkpoint,
+ checkpoint_id_bytes=checkpoint_id_bytes,
+ checkpoint_null_version=null_version,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=task.config,
+ step=self.step,
+ stop=self.stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ ),
+ ):
+ # produce debug output
+ self._emit("tasks", map_debug_tasks, [pushed])
+ # save the new task
+ self.tasks[pushed.id] = pushed
+ # match any pending writes to the new task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({pushed.id: pushed})
+ # return the new task, to be started if not run before
+ return pushed
+
+ def schedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ raise NotImplementedError
+
+ async def aschedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ raise NotImplementedError
+
+ def tick(self) -> bool:
+ """Execute a single iteration of the Pregel loop.
+
+ Returns:
+ True if more iterations are needed.
+ """
+
+ # check if iteration limit is reached
+ if self.step > self.stop:
+ self.status = "out_of_steps"
+ return False
+
+ # prepare next tasks
+ self.tasks = prepare_next_tasks(
+ self.checkpoint,
+ self.checkpoint_pending_writes,
+ self.nodes,
+ self.channels,
+ self.managed,
+ self.config,
+ self.step,
+ self.stop,
+ for_execution=True,
+ manager=self.manager,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ trigger_to_nodes=self.trigger_to_nodes,
+ updated_channels=self.updated_channels,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+
+ # produce debug output
+ if self._checkpointer_put_after_previous is not None:
+ self._emit(
+ "checkpoints",
+ map_debug_checkpoint,
+ {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ },
+ self.channels,
+ self.stream_keys,
+ self.checkpoint_metadata,
+ self.tasks.values(),
+ self.checkpoint_pending_writes,
+ self.prev_checkpoint_config,
+ self.output_keys,
+ )
+
+ # if no more tasks, we're done
+ if not self.tasks:
+ self.status = "done"
+ return False
+
+ if self.control is not None and self.control.drain_requested:
+ self.status = "draining"
+ return False
+
+ # if there are pending writes from a previous loop, apply them
+ if not self.is_replaying and self.checkpoint_pending_writes:
+ self._reapply_writes_to_succeeded_nodes(self.tasks)
+ self._resume_error_handlers_if_applicable()
+
+ # before execution, check if we should interrupt
+ if self.interrupt_before and should_interrupt(
+ self.checkpoint, self.interrupt_before, self.tasks.values()
+ ):
+ self.status = "interrupt_before"
+ raise GraphInterrupt()
+
+ # produce debug output
+ self._emit("tasks", map_debug_tasks, self.tasks.values())
+
+ # print output for any tasks we applied previous writes to
+ for task in self.tasks.values():
+ if task.writes:
+ self.output_writes(task.id, task.writes, cached=True)
+
+ return True
+
+ def after_tick(self) -> None:
+ # finish superstep
+ writes = [w for t in self.tasks.values() for w in t.writes]
+ # all tasks have finished
+ self.updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ self.tasks.values(),
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ # produce values output
+ if not self.updated_channels.isdisjoint(
+ (self.output_keys,)
+ if isinstance(self.output_keys, str)
+ else self.output_keys
+ ):
+ self._emit(
+ "values", map_output_values, self.output_keys, writes, self.channels
+ )
+ # capture delta-channel writes for exit-mode accumulator before clearing
+ if self._exit_delta_writes is not None:
+ for tid, ch, v in self.checkpoint_pending_writes:
+ if isinstance(self.specs.get(ch), DeltaChannel):
+ self._exit_delta_writes.append((self.step, tid, ch, v))
+ # clear pending writes
+ self.checkpoint_pending_writes.clear()
+ # only replay (re-execute) done tasks on the first tick
+ self.is_replaying = False
+ # save checkpoint
+ self._put_checkpoint({"source": "loop"})
+ # after execution, check if we should interrupt
+ if self.interrupt_after and should_interrupt(
+ self.checkpoint, self.interrupt_after, self.tasks.values()
+ ):
+ self.status = "interrupt_after"
+ raise GraphInterrupt()
+ # unset resuming flag
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+
+ def match_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ raise NotImplementedError
+
+ async def amatch_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ raise NotImplementedError
+
+ # private
+
+ def _reapply_writes_to_succeeded_nodes(
+ self, tasks: Mapping[str, PregelExecutableTask]
+ ) -> None:
+ """Restore successful channel writes from checkpoint to in-memory tasks.
+
+ Skips control signals (ERROR, ERROR_SOURCE_NODE, INTERRUPT, RESUME)
+ so that failed/interrupted tasks remain with empty writes and will be
+ re-executed (or routed to error handlers) by the runner.
+ """
+ for tid, k, v in self.checkpoint_pending_writes:
+ if k in (ERROR, ERROR_SOURCE_NODE, INTERRUPT, RESUME):
+ continue
+ if task := tasks.get(tid):
+ task.writes.append((k, v))
+
+ def _resume_error_handlers_if_applicable(self) -> None:
+ """On resume, schedule error handlers for tasks that failed in a prior run.
+
+ Called right after ``_reapply_writes_to_succeeded_nodes`` during ``tick()``.
+ At that point, ``_reapply_writes_to_succeeded_nodes`` has already skipped
+ ERROR / ERROR_SOURCE_NODE writes, so a previously-failed task still has
+ empty ``writes``. Without intervention the runner (which executes only
+ tasks where ``not t.writes``) would re-run the original node.
+
+ This method prevents that re-execution for nodes that have an error
+ handler:
+
+ 1. Scan ``checkpoint_pending_writes`` for ERROR_SOURCE_NODE markers
+ persisted by a prior ``commit()``. Each marker means "this task
+ already failed and was routed to an error handler".
+ 2. For each such task, write ``(ERROR, error)`` into ``task.writes``
+ so the task is no longer empty — the runner will skip it.
+ 3. Prepare a fresh error-handler task and add it to ``self.tasks``.
+ Because the handler task starts with empty ``writes``, the runner
+ will pick it up and execute it.
+ """
+ # Phase 1: collect task-ids that have ERROR_SOURCE_NODE + ERROR pairs.
+ failed: dict[str, BaseException] = {}
+ for tid, chan, val in self.checkpoint_pending_writes:
+ if chan == ERROR_SOURCE_NODE:
+ error = next(
+ (
+ v
+ for t, c, v in self.checkpoint_pending_writes
+ if t == tid and c == ERROR
+ ),
+ None,
+ )
+ if error is not None:
+ failed[tid] = error
+ # Phase 2: mark originals as done, schedule handler tasks.
+ for task_id, error in failed.items():
+ task = self.tasks.get(task_id)
+ if task is None:
+ continue
+ handler_node = self.nodes[task.name].error_handler_node
+ if not handler_node:
+ continue
+ # Non-empty writes → runner's `not t.writes` filter skips this task.
+ task.writes.append((ERROR, error))
+ # The handler task starts with empty writes → runner will execute it.
+ handler_task = prepare_node_error_handler_task(
+ task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is not None:
+ self.tasks[handler_task.id] = handler_task
+
+ def _pending_interrupts(self) -> set[str]:
+ """Return the set of interrupt ids that are pending without corresponding resume values."""
+ # mapping of task ids to interrupt ids
+ pending_interrupts: dict[str, str] = {}
+
+ # set of resume task ids
+ pending_resumes: set[str] = set()
+
+ for task_id, write_type, value in self.checkpoint_pending_writes:
+ if write_type == INTERRUPT:
+ # interrupts is always a list, but there should only be one element
+ pending_interrupts[task_id] = value[0].id
+ elif write_type == RESUME:
+ pending_resumes.add(task_id)
+
+ resumed_interrupt_ids = {
+ pending_interrupts[task_id]
+ for task_id in pending_resumes
+ if task_id in pending_interrupts
+ }
+
+ # Keep only interrupts whose interrupt_id is not resumed
+ hanging_interrupts: set[str] = {
+ interrupt_id
+ for interrupt_id in pending_interrupts.values()
+ if interrupt_id not in resumed_interrupt_ids
+ }
+
+ return hanging_interrupts
+
+ def _first(
+ self, *, input_keys: str | Sequence[str], updated_channels: set[str] | None
+ ) -> set[str] | None:
+ # Resuming from a previous checkpoint requires two things:
+ # 1. A prior checkpoint exists (channel_versions is non-empty)
+ # 2. The input signals continuation (not a fresh run with new input)
+ # For subgraphs, the parent explicitly sets CONFIG_KEY_RESUMING.
+ # For the outer graph, we infer from the input:
+ # - None input: resume after interrupt (invoke(None, config))
+ # - Command input: any Command operates on existing state
+ # - Same run_id: re-entry into an ongoing run (e.g. stream reconnect)
+ configurable = self.config.get(CONF, {})
+ input_is_command = isinstance(self.input, Command)
+ is_resuming = bool(self.checkpoint["channel_versions"]) and bool(
+ configurable.get(
+ CONFIG_KEY_RESUMING,
+ self.input is None
+ or input_is_command
+ or (
+ not self.is_nested
+ and self.config.get("metadata", {}).get("run_id")
+ == self.checkpoint_metadata.get("run_id", MISSING)
+ ),
+ )
+ )
+
+ # When replaying from a specific checkpoint, drop cached RESUME
+ # writes so that interrupt() calls re-fire instead of returning
+ # stale values. But if we're actively resuming, keep them —
+ # multi-interrupt scenarios need previously resolved values preserved.
+ is_time_traveling = self.is_replaying and (
+ # Time-travel to a subgraph checkpoint: the parent sets
+ # RESUMING=True (it can't distinguish time-travel from resume),
+ # so we check if this subgraph's own ns is in checkpoint_map.
+ # Normally the map only has ancestor entries (_algo.py); the
+ # subgraph's own entry only appears via get_state(subgraphs=True).
+ (
+ self.is_nested
+ and configurable.get(CONFIG_KEY_CHECKPOINT_NS, "")
+ in configurable.get(CONFIG_KEY_CHECKPOINT_MAP, {})
+ )
+ or not (
+ # Outer graph: resume arrives as Command(resume=...)
+ (input_is_command and cast(Command, self.input).resume is not None)
+ # Subgraphs: resume arrives via config flag from parent
+ # (subgraph input is a Send arg, not a Command)
+ or configurable.get(CONFIG_KEY_RESUMING, False)
+ )
+ )
+ if is_time_traveling:
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[1] != RESUME
+ ]
+
+ # map command to writes
+ if input_is_command:
+ if (resume := cast(Command, self.input).resume) is not None:
+ if not self.checkpointer:
+ raise RuntimeError(
+ "Cannot use Command(resume=...) without checkpointer"
+ )
+
+ if resume_is_map := (
+ isinstance(resume, dict)
+ and all(is_xxh3_128_hexdigest(k) for k in resume)
+ ):
+ self.config[CONF][CONFIG_KEY_RESUME_MAP] = resume
+ else:
+ if len(self._pending_interrupts()) > 1:
+ raise RuntimeError(
+ "When there are multiple pending interrupts, you must specify the interrupt id when resuming. "
+ "Docs: https://docs.langchain.com/oss/python/langgraph/add-human-in-the-loop#resume-multiple-interrupts-with-one-invocation."
+ )
+
+ writes: defaultdict[str, list[tuple[str, Any]]] = defaultdict(list)
+ # group writes by task ID
+ for tid, c, v in map_command(cmd=cast(Command, self.input)):
+ if not (c == RESUME and resume_is_map):
+ writes[tid].append((c, v))
+ if not writes and not resume_is_map:
+ raise EmptyInputError("Received empty Command input")
+ # save writes
+ for tid, ws in writes.items():
+ self.put_writes(tid, ws)
+ # apply NULL writes
+ if null_writes := [
+ w[1:] for w in self.checkpoint_pending_writes if w[0] == NULL_TASK_ID
+ ]:
+ null_updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ if updated_channels is not None:
+ updated_channels.update(null_updated_channels)
+ # proceed past previous checkpoint
+ if is_resuming:
+ self.checkpoint["versions_seen"].setdefault(INTERRUPT, {})
+ for k in self.channels:
+ if k in self.checkpoint["channel_versions"]:
+ version = self.checkpoint["channel_versions"][k]
+ self.checkpoint["versions_seen"][INTERRUPT][k] = version
+ # When time-traveling (replaying from a specific checkpoint),
+ # save a fork checkpoint so the replayed execution creates a
+ # new branch. Without this, if the execution hits an interrupt
+ # before after_tick() runs, no new checkpoint is created —
+ # the parent's latest checkpoint remains the old one and
+ # subsequent resumes load the wrong state.
+ # Skip for update_state forks (source=update/fork) since they
+ # already have their own fork checkpoint.
+ if is_time_traveling and self.checkpoint_metadata.get("source") not in (
+ "update",
+ "fork",
+ ):
+ # Clear old INTERRUPT writes from the loaded checkpoint.
+ # The fork will have a new checkpoint_id which changes
+ # task IDs — stale interrupt writes would accumulate and
+ # confuse the multiple-interrupt check in future resumes.
+ self.checkpoint_pending_writes = [
+ w for w in self.checkpoint_pending_writes if w[1] != INTERRUPT
+ ]
+ self._put_checkpoint({"source": "fork"})
+ # produce values output
+ self._emit(
+ "values", map_output_values, self.output_keys, True, self.channels
+ )
+ # map inputs to channel updates
+ elif input_writes := deque(map_input(input_keys, self.input)):
+ # discard any unfinished tasks from previous checkpoint
+ discard_tasks = prepare_next_tasks(
+ self.checkpoint,
+ self.checkpoint_pending_writes,
+ self.nodes,
+ self.channels,
+ self.managed,
+ self.config,
+ self.step,
+ self.stop,
+ for_execution=True,
+ store=None,
+ checkpointer=None,
+ manager=None,
+ updated_channels=updated_channels,
+ )
+ # apply input writes
+ updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ [
+ *discard_tasks.values(),
+ PregelTaskWrites((), INPUT, input_writes, []),
+ ],
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ # Input writes go through `apply_writes` directly (above) — they
+ # never enter `checkpoint_pending_writes`, so the after_tick
+ # capture site does not see them. In exit mode, capture them
+ # here so `_exit_delta_writes` includes the input's delta writes
+ # alongside per-superstep writes; otherwise the input would be
+ # lost on read (it's not in final_checkpoint.channel_values for
+ # sub-freq channels, and walks ignore target.pending_writes).
+ if self._exit_delta_writes is not None:
+ for c, v in input_writes:
+ if isinstance(self.specs.get(c), DeltaChannel):
+ self._exit_delta_writes.append((self.step, NULL_TASK_ID, c, v))
+ # Persist delta-channel input writes so sub-freq inputs are
+ # recoverable via ancestor walk (mirrors the Command input path).
+ if self.durability != "exit":
+ delta_input = [
+ (c, v)
+ for c, v in input_writes
+ if isinstance(self.specs.get(c), DeltaChannel)
+ ]
+ if delta_input:
+ self.put_writes(NULL_TASK_ID, delta_input)
+ # save input checkpoint
+ self.updated_channels = updated_channels
+ self._put_checkpoint({"source": "input"})
+ elif CONFIG_KEY_RESUMING not in configurable:
+ raise EmptyInputError(f"Received no input for {input_keys}")
+ # Propagate resuming and replaying flags to subgraphs.
+ if not self.is_nested:
+ # Pass the resolved before-bound checkpoint ID so subgraphs can
+ # find their corresponding checkpoint without re-fetching the
+ # parent. For forks (source=update/fork), use the fork's parent
+ # checkpoint ID since the fork was created after the subgraph's
+ # checkpoints from the original execution.
+ #
+ # Only gate on is_time_traveling (not is_replaying). When the
+ # client resumes with an explicit checkpoint_id that happens to
+ # point at the current head (e.g. LangGraph Studio sending
+ # `checkpoint: {checkpoint_id}` alongside Command(resume=...)),
+ # is_replaying is True but is_time_traveling is False. In that
+ # case subgraphs should load their latest checkpoint normally,
+ # not go through ReplayState's before-bound lookup which would
+ # miss subgraph checkpoints created during processing of the
+ # current parent step.
+ replay_state: ReplayState | None = None
+ if is_time_traveling:
+ replay_checkpoint_id = self.checkpoint["id"]
+ if (
+ self.checkpoint_metadata.get("source")
+ in (
+ "update",
+ "fork",
+ )
+ and self.prev_checkpoint_config
+ ):
+ replay_checkpoint_id = self.prev_checkpoint_config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_ID, replay_checkpoint_id
+ )
+ replay_state = ReplayState(replay_checkpoint_id)
+ self.config = patch_configurable(
+ self.config,
+ {
+ CONFIG_KEY_RESUMING: is_resuming,
+ CONFIG_KEY_REPLAY_STATE: replay_state,
+ },
+ )
+ # set flag
+ self.status = "pending"
+ if is_resuming:
+ self._push_graph_lifecycle_event("resume")
+ return updated_channels
+
+ def _put_checkpoint(self, metadata: CheckpointMetadata) -> None:
+ # `is` (object identity) — not `==`. Three of four call sites pass a
+ # fresh dict ({"source":"input"|"loop"|"fork"}); only
+ # `_suppress_interrupt`(will rename to _on_loop_exit soon)
+ # at exit reuses the existing `self.checkpoint_metadata` instance. So
+ # `metadata is self.checkpoint_metadata` is True only on the exit call,
+ # which is what we use to gate exit-only behaviour (skip count-bump,
+ # don't replace metadata). Could be replaced by an explicit
+ # `exiting: bool = False` parameter; left as-is to match the existing
+ # idiom in this file.
+ # TODO: replace with an explicit `exiting: bool = False` parameter.
+ exiting = metadata is self.checkpoint_metadata
+ if exiting and self.checkpoint["id"] == self.checkpoint_id_saved:
+ # checkpoint already saved
+ return
+ # Per-delta-channel counter bookkeeping.
+ #
+ # Each delta channel tracks a (updates, supersteps) tuple:
+ # - `updates` increments only when the channel is written this step.
+ # - `supersteps` increments every superstep regardless.
+ #
+ # `_put_checkpoint` is called once per superstep with a fresh
+ # metadata dict (source="input"|"loop"|"fork") — those are the
+ # intermediate calls that bump counters. In exit mode,
+ # `_suppress_interrupt`(will rename to _on_loop_exit soon)
+ # additionally calls `_put_checkpoint(self.checkpoint_metadata)` AT
+ # EXIT to commit the final checkpoint — this runs *after* the last
+ # intermediate call already counted the last superstep. So the
+ # exit call must NOT bump again or it would double-count the last
+ # superstep.
+ if not exiting:
+ prev_counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ new_counters: dict[str, tuple[int, int]] = {}
+ updated = self.updated_channels or set()
+ for ch_name, ch in self.channels.items():
+ if not isinstance(ch, DeltaChannel):
+ continue
+ u, s = prev_counters.get(ch_name, (0, 0))
+ s += 1
+ if ch_name in updated:
+ u += 1
+ new_counters[ch_name] = (u, s)
+ metadata["step"] = self.step
+ metadata["parents"] = self.config[CONF].get(CONFIG_KEY_CHECKPOINT_MAP, {})
+ self.checkpoint_metadata = metadata
+ else:
+ new_counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ # do checkpoint?
+ do_checkpoint = self._checkpointer_put_after_previous is not None and (
+ exiting or self.durability != "exit"
+ )
+ # create new checkpoint
+ channels_to_snapshot = (
+ delta_channels_to_snapshot(self.channels, new_counters)
+ if do_checkpoint
+ else set()
+ )
+ self.checkpoint = create_checkpoint(
+ self.checkpoint,
+ self.channels if do_checkpoint else None,
+ self.step,
+ id=self.checkpoint["id"] if exiting else None,
+ updated_channels=self.updated_channels,
+ get_next_version=self.checkpointer_get_next_version
+ if do_checkpoint
+ else None,
+ channels_to_snapshot=channels_to_snapshot,
+ )
+ for k in channels_to_snapshot:
+ new_counters[k] = (0, 0)
+ non_zero = {k: v for k, v in new_counters.items() if v != (0, 0)}
+ if non_zero:
+ self.checkpoint_metadata["counters_since_delta_snapshot"] = non_zero
+ elif "counters_since_delta_snapshot" in self.checkpoint_metadata:
+ del self.checkpoint_metadata["counters_since_delta_snapshot"]
+ # sanitize TASK channel in the checkpoint before saving (durability=="exit")
+ if TASKS in self.checkpoint["channel_values"] and any(
+ isinstance(channel, UntrackedValue) for channel in self.channels.values()
+ ):
+ sanitized_tasks = [
+ sanitize_untracked_values_in_send(value, self.channels)
+ if isinstance(value, Send)
+ else value
+ for value in self.checkpoint["channel_values"][TASKS]
+ ]
+ self.checkpoint["channel_values"][TASKS] = sanitized_tasks
+ # bail if no checkpointer
+
+ if do_checkpoint and self._checkpointer_put_after_previous is not None:
+ self.prev_checkpoint_config = (
+ self.checkpoint_config
+ if CONFIG_KEY_CHECKPOINT_ID in self.checkpoint_config[CONF]
+ and self.checkpoint_config[CONF][CONFIG_KEY_CHECKPOINT_ID]
+ else None
+ )
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ },
+ }
+
+ channel_versions = self.checkpoint["channel_versions"].copy()
+ new_versions = get_new_channel_versions(
+ self.checkpoint_previous_versions, channel_versions
+ )
+ self.checkpoint_previous_versions = channel_versions
+
+ # save it, without blocking
+ # if there's a previous checkpoint save in progress, wait for it
+ # ensuring checkpointers receive checkpoints in order
+ self._put_checkpoint_fut = self.submit(
+ self._checkpointer_put_after_previous,
+ getattr(self, "_put_checkpoint_fut", None),
+ self.checkpoint_config,
+ copy_checkpoint(self.checkpoint),
+ self.checkpoint_metadata,
+ new_versions,
+ )
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ CONF: {
+ **self.checkpoint_config[CONF],
+ CONFIG_KEY_CHECKPOINT_ID: self.checkpoint["id"],
+ },
+ }
+ if not exiting:
+ # increment step
+ self.step += 1
+
+ def _put_exit_delta_writes(self) -> None:
+ """Stage stub + accumulated delta writes so final_checkpoint's put
+ waits on them (visibility invariant: both must be durable before
+ final_checkpoint becomes visible to readers).
+
+ Stub is created lazily — only when no persisted parent exists AND at
+ least one delta channel has writes that won't be snapshotted.
+ """
+ if (
+ not self._exit_delta_writes
+ or self.checkpointer is None
+ or self._checkpointer_put_after_previous is None
+ or self.checkpointer_put_writes is None
+ ):
+ return
+
+ counters = dict(
+ self.checkpoint_metadata.get("counters_since_delta_snapshot") or {}
+ )
+ channels_to_snapshot = delta_channels_to_snapshot(self.channels, counters)
+
+ pending = [
+ (step, tid, ch, v)
+ for (step, tid, ch, v) in self._exit_delta_writes
+ if ch not in channels_to_snapshot
+ ]
+ if not pending:
+ return
+
+ if self._has_persisted_parent:
+ # _initial_checkpoint_config's checkpoint_id is the saved parent's
+ # id (saver returned a real tuple at __enter__).
+ anchor_config = self._initial_checkpoint_config
+ else:
+ stub_cp = empty_checkpoint()
+ stub_cp["id"] = self.checkpoint_id_saved
+ stub_cp["ts"] = datetime.now(timezone.utc).isoformat()
+ # Stub has no parent (checkpoint_id=None in config).
+ stub_put_config = patch_configurable(
+ self._initial_checkpoint_config,
+ {CONFIG_KEY_CHECKPOINT_ID: None},
+ )
+ # Anchor config for put_writes: checkpoint_id = stub's id.
+ anchor_config = patch_configurable(
+ self._initial_checkpoint_config,
+ {CONFIG_KEY_CHECKPOINT_ID: stub_cp["id"]},
+ )
+ self._put_checkpoint_fut = self.submit(
+ self._checkpointer_put_after_previous,
+ getattr(self, "_put_checkpoint_fut", None),
+ stub_put_config,
+ stub_cp,
+ {"step": -2},
+ {},
+ )
+ # Set checkpoint_config so final_checkpoint's _put_checkpoint
+ # sees the stub as its parent.
+ self.checkpoint_config = anchor_config
+
+ # Step-prefixed synthetic task_id preserves chronological superstep
+ # order under the saver's ORDER BY task_id, idx sorting.
+ grouped: dict[tuple[int, str], list[tuple[str, Any]]] = {}
+ for step, tid, ch, v in pending:
+ grouped.setdefault((step, tid), []).append((ch, v))
+ anchor_write_config = patch_configurable(
+ anchor_config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: self.config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ ),
+ CONFIG_KEY_CHECKPOINT_ID: anchor_config[CONF][CONFIG_KEY_CHECKPOINT_ID],
+ },
+ )
+ for (step, tid), entries in grouped.items():
+ synth_tid = f"{step:08d}-{tid}"
+ if self.checkpointer_put_writes_accepts_task_path:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ anchor_write_config,
+ entries,
+ synth_tid,
+ "",
+ )
+ else:
+ fut = self.submit(
+ self.checkpointer_put_writes,
+ anchor_write_config,
+ entries,
+ synth_tid,
+ )
+ if self._delta_write_futs is not None:
+ self._delta_write_futs.append(fut)
+
+ def _suppress_interrupt(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # persist current checkpoint and writes
+ if self.durability == "exit" and (
+ # if it's a top graph
+ not self.is_nested
+ # or a nested graph with error or interrupt
+ or exc_value is not None
+ # or a nested graph with checkpointer=True
+ or all(NS_END not in part for part in self.checkpoint_ns)
+ ):
+ self._put_exit_delta_writes()
+ self._put_checkpoint(self.checkpoint_metadata)
+ self._put_pending_writes()
+ # suppress interrupt
+ if isinstance(exc_value, GraphInterrupt) and not self.is_nested:
+ interrupt = exc_value
+ interrupts = tuple(interrupt.args[0]) if interrupt.args else ()
+ self._push_graph_lifecycle_event("interrupt", interrupts=interrupts)
+ # emit one last "values" event, with pending writes applied
+ if (
+ hasattr(self, "tasks")
+ and self.checkpoint_pending_writes
+ and any(task.writes for task in self.tasks.values())
+ ):
+ updated_channels = apply_writes(
+ self.checkpoint,
+ self.channels,
+ self.tasks.values(),
+ self.checkpointer_get_next_version,
+ self.trigger_to_nodes,
+ )
+ if not updated_channels.isdisjoint(
+ (self.output_keys,)
+ if isinstance(self.output_keys, str)
+ else self.output_keys
+ ):
+ self._emit(
+ "values",
+ map_output_values,
+ self.output_keys,
+ [w for t in self.tasks.values() for w in t.writes],
+ self.channels,
+ )
+ # emit INTERRUPT if exception is empty (otherwise emitted by put_writes)
+ if not interrupt.args or not interrupt.args[0]:
+ interrupt_payload = interrupt.args[0] if interrupt.args else ()
+ self._emit(
+ "updates",
+ lambda: iter([{INTERRUPT: interrupt_payload}]),
+ )
+ # save final output
+ self.output = read_channels(self.channels, self.output_keys)
+ # suppress interrupt
+ return True
+ elif exc_type is None:
+ # save final output
+ self.output = read_channels(self.channels, self.output_keys)
+
+ def _emit(
+ self,
+ mode: StreamMode,
+ values: Callable[P, Iterator[Any]],
+ *args: P.args,
+ **kwargs: P.kwargs,
+ ) -> None:
+ if self.stream is None:
+ return
+ debug_remap = mode in ("checkpoints", "tasks") and "debug" in self.stream.modes
+ if mode not in self.stream.modes and not debug_remap:
+ return
+ for v in values(*args, **kwargs):
+ if mode in self.stream.modes:
+ self.stream((self.checkpoint_ns, mode, v))
+ # "debug" mode is "checkpoints" or "tasks" with a wrapper dict
+ if debug_remap:
+ self.stream(
+ (
+ self.checkpoint_ns,
+ "debug",
+ {
+ "step": self.step - 1
+ if mode == "checkpoints"
+ else self.step,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "type": "checkpoint"
+ if mode == "checkpoints"
+ else "task_result"
+ if "result" in v
+ else "task",
+ "payload": v,
+ },
+ )
+ )
+
+ def output_writes(
+ self, task_id: str, writes: WritesT, *, cached: bool = False
+ ) -> None:
+ if task := self.tasks.get(task_id):
+ if task.config is not None and TAG_HIDDEN in task.config.get(
+ "tags", EMPTY_SEQ
+ ):
+ return
+ if writes[0][0] == INTERRUPT:
+ # in loop.py we append a bool to the PUSH task paths to indicate
+ # whether or not a call was present. If so,
+ # we don't emit the interrupt as it'll be emitted by the parent
+ if task.path[0] == PUSH and task.path[-1] is True:
+ return
+ interrupts = [
+ {
+ INTERRUPT: tuple(
+ v
+ for w in writes
+ if w[0] == INTERRUPT
+ for v in (w[1] if isinstance(w[1], Sequence) else (w[1],))
+ )
+ }
+ ]
+ stream_modes = self.stream.modes if self.stream else []
+ if "updates" in stream_modes:
+ self._emit("updates", lambda: iter(interrupts))
+ if "values" in stream_modes:
+ current_values = read_channels(self.channels, self.output_keys)
+ # self.output_keys is a sequence, stream chunk contains entire state and interrupts
+ if isinstance(current_values, dict):
+ current_values[INTERRUPT] = interrupts[0][INTERRUPT]
+ self._emit("values", lambda: iter([current_values]))
+ # self.output_keys is a string, stream chunk contains only interrupts
+ else:
+ self._emit("values", lambda: iter(interrupts))
+ elif writes[0][0] != ERROR:
+ self._emit(
+ "updates",
+ map_output_updates,
+ self.output_keys,
+ [(task, writes)],
+ cached,
+ )
+ if not cached:
+ self._emit(
+ "tasks",
+ map_debug_task_results,
+ (task, writes),
+ self.stream_keys,
+ )
+
+
+class SyncPregelLoop(PregelLoop, AbstractContextManager):
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ input_keys: str | Sequence[str] = EMPTY_SEQ,
+ output_keys: str | Sequence[str] = EMPTY_SEQ,
+ stream_keys: str | Sequence[str] = EMPTY_SEQ,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ super().__init__(
+ input,
+ stream=stream,
+ config=config,
+ checkpointer=checkpointer,
+ cache=cache,
+ store=store,
+ nodes=nodes,
+ specs=specs,
+ input_keys=input_keys,
+ output_keys=output_keys,
+ stream_keys=stream_keys,
+ interrupt_after=interrupt_after,
+ interrupt_before=interrupt_before,
+ manager=manager,
+ migrate_checkpoint=migrate_checkpoint,
+ trigger_to_nodes=trigger_to_nodes,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ durability=durability,
+ has_graph_lifecycle_callbacks=has_graph_lifecycle_callbacks,
+ )
+ self.stack = ExitStack()
+ if checkpointer:
+ self.checkpointer_get_next_version = checkpointer.get_next_version
+ self.checkpointer_put_writes = checkpointer.put_writes
+ self.checkpointer_put_writes_accepts_task_path = (
+ signature(checkpointer.put_writes).parameters.get("task_path")
+ is not None
+ )
+ else:
+ self.checkpointer_get_next_version = increment
+ self._checkpointer_put_after_previous = None # type: ignore[assignment]
+ self.checkpointer_put_writes = None
+ self.checkpointer_put_writes_accepts_task_path = False
+
+ def _checkpointer_put_after_previous(
+ self,
+ prev: concurrent.futures.Future | None,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ if self._delta_write_futs:
+ futs, self._delta_write_futs = self._delta_write_futs, []
+ concurrent.futures.wait(futs)
+ try:
+ if prev is not None:
+ prev.result()
+ finally:
+ cast(BaseCheckpointSaver, self.checkpointer).put(
+ config, checkpoint, metadata, new_versions
+ )
+
+ def match_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ if self.cache is None:
+ return ()
+ matched: list[PregelExecutableTask] = []
+ if cached := {
+ (t.cache_key.ns, t.cache_key.key): t
+ for t in self.tasks.values()
+ if t.cache_key and not t.writes
+ }:
+ for key, values in self.cache.get(tuple(cached)).items():
+ task = cached[key]
+ task.writes.extend(values)
+ matched.append(task)
+ return matched
+
+ def accept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ if pushed := super().accept_push(task, write_idx, call):
+ for task in self.match_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return pushed
+
+ def schedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ handler_node = self.nodes[failed_task.name].error_handler_node
+ if not handler_node:
+ return None
+ # ensure error + ERROR_SOURCE_NODE writes are durable before handler runs
+ if self._error_handler_write_futs:
+ futs, self._error_handler_write_futs = self._error_handler_write_futs, []
+ concurrent.futures.wait(futs)
+ handler_task = prepare_node_error_handler_task(
+ failed_task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=failed_task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is None:
+ return None
+ self.tasks[handler_task.id] = handler_task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({handler_task.id: handler_task})
+ for task in self.match_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return handler_task
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ super().put_writes(task_id, writes)
+ if not writes or self.cache is None or not hasattr(self, "tasks"):
+ return
+ task = self.tasks.get(task_id)
+ if task is None or task.cache_key is None:
+ return
+ self.submit(
+ self.cache.set,
+ {
+ (task.cache_key.ns, task.cache_key.key): (
+ task.writes,
+ task.cache_key.ttl,
+ )
+ },
+ )
+
+ # context manager
+
+ def __enter__(self) -> Self:
+ self._graph_lifecycle_events = deque()
+ if not self.checkpointer:
+ saved = None
+ elif self.checkpoint_config[CONF].get(CONFIG_KEY_CHECKPOINT_ID):
+ # Explicit checkpoint_id requested — fetch that exact checkpoint.
+ # This covers both normal replay and subgraphs resolved via
+ # checkpoint_map during time-travel.
+ saved = self.checkpointer.get_tuple(self.checkpoint_config)
+ elif replay_state := self.config[CONF].get(CONFIG_KEY_REPLAY_STATE):
+ # Subgraph replay: the parent is replaying and passed us a
+ # replay_state with its checkpoint_id. Look up our checkpoint
+ # from the parent's checkpoint_map instead of fetching latest.
+ saved = replay_state.get_checkpoint(
+ self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, ""),
+ self.checkpointer,
+ self.checkpoint_config,
+ )
+ # Clear RESUMING so _first re-applies input instead of resuming.
+ # This recreates ephemeral routing channels so nodes trigger
+ # naturally via version comparison.
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+ else:
+ # Normal case: fetch the most recent checkpoint for this
+ # graph/thread. Returns None on first invocation.
+ saved = self.checkpointer.get_tuple(self.checkpoint_config)
+
+ # Capture before the synthetic-empty fallback below overwrites `saved`.
+ # `_put_exit_delta_writes` uses this on first run (no persisted parent)
+ # to lazy-create a stub instead of anchoring delta writes on a parent.
+ self._has_persisted_parent = saved is not None
+ if saved is None:
+ saved = CheckpointTuple(
+ self.checkpoint_config, empty_checkpoint(), {"step": -2}, None, []
+ )
+ elif self._migrate_checkpoint is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ **saved.config,
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: "",
+ **self.checkpoint_config.get(CONF, {}),
+ **saved.config.get(CONF, {}),
+ },
+ }
+ self._initial_checkpoint_config = self.checkpoint_config
+ self.prev_checkpoint_config = saved.parent_config
+ self.checkpoint_id_saved = saved.checkpoint["id"]
+ self.checkpoint = saved.checkpoint
+ self.checkpoint_metadata = saved.metadata
+ self.checkpoint_pending_writes = (
+ [(str(tid), k, v) for tid, k, v in saved.pending_writes]
+ if saved.pending_writes is not None
+ else []
+ )
+ self._delta_write_futs = []
+ self._error_handler_write_futs = []
+ self._exit_delta_writes = (
+ [] if self.durability == "exit" and self.checkpointer is not None else None
+ )
+ self.submit = self.stack.enter_context(BackgroundExecutor(self.config))
+ self.channels, self.managed = channels_from_checkpoint(
+ self.specs,
+ self.checkpoint,
+ saver=self.checkpointer,
+ config=self.checkpoint_config,
+ )
+ self.stack.push(self._suppress_interrupt)
+ self.status = "input"
+ self.step = self.checkpoint_metadata["step"] + 1
+ self.stop = self.step + self.config["recursion_limit"] + 1
+ self.checkpoint_previous_versions = self.checkpoint["channel_versions"].copy()
+ self.updated_channels = self._first(
+ input_keys=self.input_keys,
+ updated_channels=set(self.checkpoint.get("updated_channels")) # type: ignore[arg-type]
+ if self.checkpoint.get("updated_channels")
+ else None,
+ )
+
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # unwind stack
+ return self.stack.__exit__(exc_type, exc_value, traceback)
+
+
+class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
+ def __init__(
+ self,
+ input: Any | None,
+ *,
+ stream: StreamProtocol | None,
+ config: RunnableConfig,
+ store: BaseStore | None,
+ cache: BaseCache | None,
+ checkpointer: BaseCheckpointSaver | None,
+ nodes: Mapping[str, PregelNode],
+ specs: Mapping[str, BaseChannel | ManagedValueSpec],
+ trigger_to_nodes: Mapping[str, Sequence[str]],
+ durability: Durability,
+ interrupt_after: All | Sequence[str] = EMPTY_SEQ,
+ interrupt_before: All | Sequence[str] = EMPTY_SEQ,
+ manager: None | AsyncParentRunManager | ParentRunManager = None,
+ input_keys: str | Sequence[str] = EMPTY_SEQ,
+ output_keys: str | Sequence[str] = EMPTY_SEQ,
+ stream_keys: str | Sequence[str] = EMPTY_SEQ,
+ migrate_checkpoint: Callable[[Checkpoint], None] | None = None,
+ retry_policy: Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ has_graph_lifecycle_callbacks: bool = False,
+ ) -> None:
+ super().__init__(
+ input,
+ stream=stream,
+ config=config,
+ checkpointer=checkpointer,
+ cache=cache,
+ store=store,
+ nodes=nodes,
+ specs=specs,
+ input_keys=input_keys,
+ output_keys=output_keys,
+ stream_keys=stream_keys,
+ interrupt_after=interrupt_after,
+ interrupt_before=interrupt_before,
+ manager=manager,
+ migrate_checkpoint=migrate_checkpoint,
+ trigger_to_nodes=trigger_to_nodes,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ durability=durability,
+ has_graph_lifecycle_callbacks=has_graph_lifecycle_callbacks,
+ )
+ self.stack = AsyncExitStack()
+ if checkpointer:
+ self.checkpointer_get_next_version = checkpointer.get_next_version
+ self.checkpointer_put_writes = checkpointer.aput_writes
+ self.checkpointer_put_writes_accepts_task_path = (
+ signature(checkpointer.aput_writes).parameters.get("task_path")
+ is not None
+ )
+ else:
+ self.checkpointer_get_next_version = increment
+ self._checkpointer_put_after_previous = None # type: ignore[assignment]
+ self.checkpointer_put_writes = None
+ self.checkpointer_put_writes_accepts_task_path = False
+
+ async def _checkpointer_put_after_previous(
+ self,
+ prev: asyncio.Task | None,
+ config: RunnableConfig,
+ checkpoint: Checkpoint,
+ metadata: CheckpointMetadata,
+ new_versions: ChannelVersions,
+ ) -> RunnableConfig:
+ # Drain DeltaChannel write futures before committing the checkpoint so
+ # ancestor walks never see a checkpoint without its backing writes.
+ if self._delta_write_futs:
+ futs, self._delta_write_futs = self._delta_write_futs, []
+ await asyncio.gather(*futs)
+ try:
+ if prev is not None:
+ await prev
+ finally:
+ await cast(BaseCheckpointSaver, self.checkpointer).aput(
+ config, checkpoint, metadata, new_versions
+ )
+
+ async def amatch_cached_writes(self) -> Sequence[PregelExecutableTask]:
+ if self.cache is None:
+ return []
+ matched: list[PregelExecutableTask] = []
+ if cached := {
+ (t.cache_key.ns, t.cache_key.key): t
+ for t in self.tasks.values()
+ if t.cache_key and not t.writes
+ }:
+ for key, values in (await self.cache.aget(tuple(cached))).items():
+ task = cached[key]
+ task.writes.extend(values)
+ matched.append(task)
+ return matched
+
+ async def aaccept_push(
+ self, task: PregelExecutableTask, write_idx: int, call: Call | None = None
+ ) -> PregelExecutableTask | None:
+ if pushed := super().accept_push(task, write_idx, call):
+ for task in await self.amatch_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return pushed
+
+ async def aschedule_error_handler(
+ self, failed_task: PregelExecutableTask, error: BaseException
+ ) -> PregelExecutableTask | None:
+ handler_node = self.nodes[failed_task.name].error_handler_node
+ if not handler_node:
+ return None
+ # ensure error + ERROR_SOURCE_NODE writes are durable before handler runs
+ if self._error_handler_write_futs:
+ futs, self._error_handler_write_futs = self._error_handler_write_futs, []
+ await asyncio.gather(*futs)
+ handler_task = prepare_node_error_handler_task(
+ failed_task,
+ handler_node_name=handler_node,
+ failed_error=error,
+ checkpoint=self.checkpoint,
+ pending_writes=self.checkpoint_pending_writes,
+ processes=self.nodes,
+ channels=self.channels,
+ managed=self.managed,
+ config=failed_task.config,
+ step=self.step,
+ stop=self.stop,
+ store=self.store,
+ checkpointer=self.checkpointer,
+ manager=self.manager,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ )
+ if handler_task is None:
+ return None
+ self.tasks[handler_task.id] = handler_task
+ if not self.is_replaying:
+ self._reapply_writes_to_succeeded_nodes({handler_task.id: handler_task})
+ for task in await self.amatch_cached_writes():
+ self.output_writes(task.id, task.writes, cached=True)
+ return handler_task
+
+ def put_writes(self, task_id: str, writes: WritesT) -> None:
+ """Put writes for a task, to be read by the next tick."""
+ super().put_writes(task_id, writes)
+ if not writes or self.cache is None or not hasattr(self, "tasks"):
+ return
+ task = self.tasks.get(task_id)
+ if task is None or task.cache_key is None:
+ return
+ if writes[0][0] in (INTERRUPT, ERROR):
+ # only cache successful tasks
+ return
+ self.submit(
+ self.cache.aset,
+ {
+ (task.cache_key.ns, task.cache_key.key): (
+ task.writes,
+ task.cache_key.ttl,
+ )
+ },
+ )
+
+ # context manager
+
+ async def __aenter__(self) -> Self:
+ self._graph_lifecycle_events = deque()
+ if not self.checkpointer:
+ saved = None
+ elif self.checkpoint_config[CONF].get(CONFIG_KEY_CHECKPOINT_ID):
+ # Explicit checkpoint_id requested — fetch that exact checkpoint.
+ # This covers both normal replay and subgraphs resolved via
+ # checkpoint_map during time-travel.
+ saved = await self.checkpointer.aget_tuple(self.checkpoint_config)
+ elif replay_state := self.config[CONF].get(CONFIG_KEY_REPLAY_STATE):
+ # Subgraph replay: the parent is replaying and passed us a
+ # replay_state with its checkpoint_id. Look up our checkpoint
+ # from the parent's checkpoint_map instead of fetching latest.
+ saved = await replay_state.aget_checkpoint(
+ self.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, ""),
+ self.checkpointer,
+ self.checkpoint_config,
+ )
+ # Clear RESUMING so _first re-applies input instead of resuming.
+ # This recreates ephemeral routing channels so nodes trigger
+ # naturally via version comparison.
+ self.config[CONF].pop(CONFIG_KEY_RESUMING, None)
+ else:
+ # Normal case: fetch the most recent checkpoint for this
+ # graph/thread. Returns None on first invocation.
+ saved = await self.checkpointer.aget_tuple(self.checkpoint_config)
+
+ # Capture before the synthetic-empty fallback below overwrites `saved`.
+ # `_put_exit_delta_writes` uses this on first run (no persisted parent)
+ # to lazy-create a stub instead of anchoring delta writes on a parent.
+ self._has_persisted_parent = saved is not None
+ if saved is None:
+ saved = CheckpointTuple(
+ self.checkpoint_config, empty_checkpoint(), {"step": -2}, None, []
+ )
+ elif self._migrate_checkpoint is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ self.checkpoint_config = {
+ **self.checkpoint_config,
+ **saved.config,
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: "",
+ **self.checkpoint_config.get(CONF, {}),
+ **saved.config.get(CONF, {}),
+ },
+ }
+ self._initial_checkpoint_config = self.checkpoint_config
+ self.prev_checkpoint_config = saved.parent_config
+ self.checkpoint_id_saved = saved.checkpoint["id"]
+ self.checkpoint = saved.checkpoint
+ self.checkpoint_metadata = saved.metadata
+ self.checkpoint_pending_writes = (
+ [(str(tid), k, v) for tid, k, v in saved.pending_writes]
+ if saved.pending_writes is not None
+ else []
+ )
+ self._delta_write_futs = []
+ self._error_handler_write_futs = []
+ self._exit_delta_writes = (
+ [] if self.durability == "exit" and self.checkpointer is not None else None
+ )
+ self.submit = await self.stack.enter_async_context(
+ AsyncBackgroundExecutor(self.config)
+ )
+ self.channels, self.managed = await achannels_from_checkpoint(
+ self.specs,
+ self.checkpoint,
+ saver=self.checkpointer,
+ config=self.checkpoint_config,
+ )
+ self.stack.push(self._suppress_interrupt)
+ self.status = "input"
+ self.step = self.checkpoint_metadata["step"] + 1
+ self.stop = self.step + self.config["recursion_limit"] + 1
+ self.checkpoint_previous_versions = self.checkpoint["channel_versions"].copy()
+ self.updated_channels = self._first(
+ input_keys=self.input_keys,
+ updated_channels=set(self.checkpoint.get("updated_channels")) # type: ignore[arg-type]
+ if self.checkpoint.get("updated_channels")
+ else None,
+ )
+
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool | None:
+ # unwind stack
+ exit_task = asyncio.create_task(
+ self.stack.__aexit__(exc_type, exc_value, traceback)
+ )
+ try:
+ return await exit_task
+ except asyncio.CancelledError as e:
+ # Bubble up the exit task upon cancellation to permit the API
+ # consumer to await it before e.g., reusing the DB connection.
+ e.args = (*e.args, exit_task)
+ raise
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_messages.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_messages.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7d3af16be104919191c9b22df7204657e6cfef
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_messages.py
@@ -0,0 +1,378 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from dataclasses import fields, is_dataclass
+from typing import (
+ Any,
+ TypeVar,
+ cast,
+)
+from uuid import UUID, uuid4
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, LLMResult
+from pydantic import BaseModel
+
+from langgraph._internal._constants import NS_SEP
+from langgraph.constants import TAG_HIDDEN, TAG_NOSTREAM
+from langgraph.pregel.protocol import StreamChunk
+from langgraph.types import Command
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = object # type: ignore
+
+try:
+ from langchain_core.tracers._streaming import _V2StreamingCallbackHandler
+except ImportError:
+ _V2StreamingCallbackHandler = object # type: ignore
+
+T = TypeVar("T")
+Meta = tuple[tuple[str, ...], dict[str, Any]]
+
+
+def _state_values(obj: Any) -> Sequence[Any]:
+ """Extract top-level field values from a state object (dict, BaseModel, or dataclass)."""
+ if isinstance(obj, dict):
+ return list(obj.values())
+ elif isinstance(obj, BaseModel):
+ return [getattr(obj, k) for k in type(obj).model_fields]
+ elif is_dataclass(obj) and not isinstance(obj, type):
+ return [getattr(obj, f.name) for f in fields(obj)]
+ return ()
+
+
+class StreamMessagesHandler(BaseCallbackHandler, _StreamingCallbackHandler):
+ """A callback handler that implements stream_mode=messages.
+
+ Collects messages from:
+ (1) chat model stream events; and
+ (2) node outputs.
+ """
+
+ run_inline = True
+ """We want this callback to run in the main thread to avoid order/locking issues."""
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ """Configure the handler to stream messages from LLMs and nodes.
+
+ Args:
+ stream: A callable that takes a StreamChunk and emits it.
+ subgraphs: Whether to emit messages from subgraphs.
+ parent_ns: The namespace where the handler was created.
+ We keep track of this namespace to allow calls to subgraphs that
+ were explicitly requested as a stream with `messages` mode
+ configured.
+
+ Example:
+ parent_ns is used to handle scenarios where the subgraph is explicitly
+ streamed with `stream_mode="messages"`.
+
+ ```python
+ def parent_graph_node():
+ # This node is in the parent graph.
+ async for event in some_subgraph(..., stream_mode="messages"):
+ do something with event # <-- these events will be emitted
+ return ...
+
+ parent_graph.invoke(subgraphs=False)
+ ```
+ """
+ self.stream = stream
+ self.subgraphs = subgraphs
+ self.metadata: dict[UUID, Meta] = {}
+ self.seen: set[int | str] = set()
+ self.parent_ns = parent_ns
+
+ def _emit(self, meta: Meta, message: BaseMessage, *, dedupe: bool = False) -> None:
+ if dedupe and message.id in self.seen:
+ return
+ else:
+ if message.id is None:
+ message.id = str(uuid4())
+ self.seen.add(message.id)
+ self.stream((meta[0], "messages", (message, meta[1])))
+
+ def _find_and_emit_messages(self, meta: Meta, response: Any) -> None:
+ if isinstance(response, BaseMessage):
+ self._emit(meta, response, dedupe=True)
+ elif isinstance(response, Sequence):
+ for value in response:
+ if isinstance(value, BaseMessage):
+ self._emit(meta, value, dedupe=True)
+ else:
+ for value in _state_values(response):
+ if isinstance(value, BaseMessage):
+ self._emit(meta, value, dedupe=True)
+ elif isinstance(value, Sequence):
+ for item in value:
+ if isinstance(item, BaseMessage):
+ self._emit(meta, item, dedupe=True)
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ return output
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ return output
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if metadata and (not tags or (TAG_NOSTREAM not in tags)):
+ ns = tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP))[
+ :-1
+ ]
+ if not self.subgraphs and len(ns) > 0 and ns != self.parent_ns:
+ return
+ if tags:
+ if filtered_tags := [t for t in tags if not t.startswith("seq:step")]:
+ metadata["tags"] = filtered_tags
+ self.metadata[run_id] = (ns, metadata)
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not isinstance(chunk, ChatGenerationChunk):
+ return
+ if meta := self.metadata.get(run_id):
+ self._emit(meta, chunk.message)
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.get(run_id):
+ if response.generations and response.generations[0]:
+ gen = response.generations[0][0]
+ if isinstance(gen, ChatGeneration):
+ self._emit(meta, gen.message, dedupe=True)
+ self.metadata.pop(run_id, None)
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.metadata.pop(run_id, None)
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if (
+ metadata
+ and kwargs.get("name") == metadata.get("langgraph_node")
+ and (not tags or TAG_HIDDEN not in tags)
+ ):
+ ns = tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP))[
+ :-1
+ ]
+ if not self.subgraphs and len(ns) > 0:
+ return
+ self.metadata[run_id] = (ns, metadata)
+ for value in _state_values(inputs):
+ if isinstance(value, BaseMessage):
+ if value.id is not None:
+ self.seen.add(value.id)
+ elif isinstance(value, Sequence) and not isinstance(value, str):
+ for item in value:
+ if isinstance(item, BaseMessage):
+ if item.id is not None:
+ self.seen.add(item.id)
+
+ def on_chain_end(
+ self,
+ response: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.pop(run_id, None):
+ # Handle Command node updates
+ if isinstance(response, Command):
+ self._find_and_emit_messages(meta, response.update)
+ # Handle list of Command updates
+ elif isinstance(response, Sequence) and any(
+ isinstance(value, Command) for value in response
+ ):
+ for value in response:
+ if isinstance(value, Command):
+ self._find_and_emit_messages(meta, value.update)
+ else:
+ self._find_and_emit_messages(meta, value)
+ # Handle basic updates / streaming
+ else:
+ self._find_and_emit_messages(meta, response)
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.metadata.pop(run_id, None)
+
+
+class StreamMessagesHandlerV2(StreamMessagesHandler, _V2StreamingCallbackHandler):
+ """v2 variant of `StreamMessagesHandler`.
+
+ Declaring `_V2StreamingCallbackHandler` as a base flips
+ `BaseChatModel.invoke` to route through `_stream_chat_model_events`
+ (firing `on_stream_event`) instead of `_stream` (firing
+ `on_llm_new_token`). Inherits `on_stream_event` from the parent,
+ which forwards protocol events onto the messages stream channel.
+
+ Pregel attaches this class instead of the v1 handler only when
+ `StreamingHandler` opts in via the internal
+ `CONFIG_KEY_STREAM_MESSAGES_V2` config key; direct
+ `graph.stream(stream_mode="messages")` callers keep the v1
+ AIMessageChunk shape.
+ """
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Intentional no-op — v1 chunks are not used on v2-flagged runs.
+
+ The v2 marker already steers `invoke` to the event generator, so
+ `on_llm_new_token` should not fire under normal routing. This
+ override stays a pass-through (no call to `super()`) to make
+ the intent explicit and to guard against any caller (e.g. a
+ node that calls `model.stream()` directly, which still fires
+ the v1 callback) leaking AIMessageChunks onto a v2-flagged
+ messages stream.
+ """
+ # Intentionally empty: v2 handler does not forward v1 chunks.
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ super().__init__(stream, subgraphs, parent_ns=parent_ns)
+ self._streamed_run_ids: set[UUID] = set()
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if meta := self.metadata.get(run_id):
+ if response.generations and response.generations[0]:
+ gen = response.generations[0][0]
+ if isinstance(gen, ChatGeneration):
+ if run_id in self._streamed_run_ids:
+ if gen.message.id is None:
+ gen.message.id = str(uuid4())
+ self.seen.add(gen.message.id)
+ else:
+ self._emit(meta, gen.message, dedupe=True)
+ self._streamed_run_ids.discard(run_id)
+ self.metadata.pop(run_id, None)
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._streamed_run_ids.discard(run_id)
+ super().on_llm_error(
+ error,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ **kwargs,
+ )
+
+ def on_stream_event(
+ self,
+ event: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Forward a protocol event from `stream_events(version="v3")` as a messages stream part.
+
+ Fires once per `MessagesData` event (`message-start`, per-block
+ `content-block-*`, `message-finish`). The transformer layer
+ correlates events back to a single `ChatModelStream` via
+ `metadata["run_id"]` — attached here so the v1
+ `stream_mode="messages"` output (which emits
+ `(AIMessageChunk, metadata)` via `on_llm_new_token`) keeps its
+ original metadata shape.
+
+ Lives on the v2 handler rather than the v1 base: content-block
+ events are a v2-only concept, and forwarding them only when the
+ v2 handler is attached keeps the message channel's shape
+ predictable for v1 callers.
+ """
+ if meta := self.metadata.get(run_id):
+ # Record message_id on message-start so on_chain_end's
+ # dedupe skips the finalized AIMessage the node returns
+ # (otherwise the messages projection double-counts: once
+ # from streaming, once from the chain output).
+ if event.get("event") == "message-start":
+ self._streamed_run_ids.add(run_id)
+ msg_id = event.get("message_id")
+ if msg_id:
+ self.seen.add(msg_id)
+ v2_meta = {**meta[1], "run_id": str(run_id)}
+ self.stream((meta[0], "messages", (event, v2_meta)))
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_read.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_read.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d49fce8562486da82bad592884a07437697f213
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_read.py
@@ -0,0 +1,298 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from datetime import timedelta
+from functools import cached_property
+from typing import (
+ Any,
+)
+
+from langchain_core.runnables import Runnable, RunnableConfig
+
+from langgraph._internal._config import merge_configs
+from langgraph._internal._constants import CONF, CONFIG_KEY_READ
+from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+from langgraph._internal._timeout import coerce_timeout_policy
+from langgraph.pregel._utils import find_subgraph_pregel
+from langgraph.pregel._write import ChannelWrite
+from langgraph.pregel.protocol import PregelProtocol
+from langgraph.types import CachePolicy, RetryPolicy, TimeoutPolicy
+
+READ_TYPE = Callable[[str | Sequence[str], bool], Any | dict[str, Any]]
+INPUT_CACHE_KEY_TYPE = tuple[Callable[..., Any], tuple[str, ...]]
+
+
+class ChannelRead(RunnableCallable):
+ """Implements the logic for reading state from CONFIG_KEY_READ.
+ Usable both as a runnable as well as a static method to call imperatively."""
+
+ channel: str | list[str]
+
+ fresh: bool = False
+
+ mapper: Callable[[Any], Any] | None = None
+
+ def __init__(
+ self,
+ channel: str | list[str],
+ *,
+ fresh: bool = False,
+ mapper: Callable[[Any], Any] | None = None,
+ tags: list[str] | None = None,
+ ) -> None:
+ super().__init__(
+ func=self._read,
+ afunc=self._aread,
+ tags=tags,
+ name=None,
+ trace=False,
+ )
+ self.fresh = fresh
+ self.mapper = mapper
+ self.channel = channel
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ if name:
+ pass
+ elif isinstance(self.channel, str):
+ name = f"ChannelRead<{self.channel}>"
+ else:
+ name = f"ChannelRead<{','.join(self.channel)}>"
+ return super().get_name(suffix, name=name)
+
+ def _read(self, _: Any, config: RunnableConfig) -> Any:
+ return self.do_read(
+ config, select=self.channel, fresh=self.fresh, mapper=self.mapper
+ )
+
+ async def _aread(self, _: Any, config: RunnableConfig) -> Any:
+ return self.do_read(
+ config, select=self.channel, fresh=self.fresh, mapper=self.mapper
+ )
+
+ @staticmethod
+ def do_read(
+ config: RunnableConfig,
+ *,
+ select: str | list[str],
+ fresh: bool = False,
+ mapper: Callable[[Any], Any] | None = None,
+ ) -> Any:
+ try:
+ read: READ_TYPE = config[CONF][CONFIG_KEY_READ]
+ except KeyError:
+ raise RuntimeError(
+ "Not configured with a read function"
+ "Make sure to call in the context of a Pregel process"
+ )
+ if mapper:
+ return mapper(read(select, fresh))
+ else:
+ return read(select, fresh)
+
+
+DEFAULT_BOUND = RunnableCallable(lambda input: input)
+
+
+class PregelNode:
+ """A node in a Pregel graph. This won't be invoked as a runnable by the graph
+ itself, but instead acts as a container for the components necessary to make
+ a PregelExecutableTask for a node."""
+
+ channels: str | list[str]
+ """The channels that will be passed as input to `bound`.
+ If a str, the node will be invoked with its value if it isn't empty.
+ If a list, the node will be invoked with a dict of those channels' values."""
+
+ triggers: list[str]
+ """If any of these channels is written to, this node will be triggered in
+ the next step."""
+
+ mapper: Callable[[Any], Any] | None
+ """A function to transform the input before passing it to `bound`."""
+
+ writers: list[Runnable]
+ """A list of writers that will be executed after `bound`, responsible for
+ taking the output of `bound` and writing it to the appropriate channels."""
+
+ bound: Runnable[Any, Any]
+ """The main logic of the node. This will be invoked with the input from
+ `channels`."""
+
+ retry_policy: Sequence[RetryPolicy] | None
+ """The retry policies to use when invoking the node."""
+
+ cache_policy: CachePolicy | None
+ """The cache policy to use when invoking the node."""
+
+ timeout: TimeoutPolicy | None
+ """Timeout policy for a single invocation.
+
+ If exceeded, `NodeTimeoutError` is raised and the retry policy (if any)
+ decides whether to retry. Supported only for async nodes.
+ """
+
+ tags: Sequence[str] | None
+ """Tags to attach to the node for tracing."""
+
+ metadata: Mapping[str, Any] | None
+ """Metadata to attach to the node for tracing."""
+
+ is_error_handler: bool
+ """Whether this node is registered as an error handler node."""
+
+ error_handler_node: str | None
+ """Optional handler node name for failures from this node."""
+
+ subgraphs: Sequence[PregelProtocol]
+ """Subgraphs used by the node."""
+
+ def __init__(
+ self,
+ *,
+ channels: str | list[str],
+ triggers: Sequence[str],
+ mapper: Callable[[Any], Any] | None = None,
+ writers: list[Runnable] | None = None,
+ tags: list[str] | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ bound: Runnable[Any, Any] | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ is_error_handler: bool = False,
+ error_handler_node: str | None = None,
+ subgraphs: Sequence[PregelProtocol] | None = None,
+ timeout: float | timedelta | TimeoutPolicy | None = None,
+ ) -> None:
+ self.channels = channels
+ self.triggers = list(triggers)
+ self.mapper = mapper
+ self.writers = writers or []
+ self.bound = bound if bound is not None else DEFAULT_BOUND
+ self.cache_policy = cache_policy
+ if isinstance(retry_policy, RetryPolicy):
+ self.retry_policy = (retry_policy,)
+ else:
+ self.retry_policy = retry_policy
+ self.timeout = coerce_timeout_policy(timeout)
+ self.tags = tags
+ self.metadata = metadata
+ self.is_error_handler = is_error_handler
+ self.error_handler_node = error_handler_node
+ if subgraphs is not None:
+ self.subgraphs = subgraphs
+ elif self.bound is not DEFAULT_BOUND:
+ try:
+ subgraph = find_subgraph_pregel(self.bound)
+ except Exception:
+ subgraph = None
+ if subgraph:
+ self.subgraphs = [subgraph]
+ else:
+ self.subgraphs = []
+ else:
+ self.subgraphs = []
+
+ def copy(self, update: dict[str, Any]) -> PregelNode:
+ attrs = {**self.__dict__, **update}
+ # Drop the cached properties
+ attrs.pop("flat_writers", None)
+ attrs.pop("node", None)
+ attrs.pop("input_cache_key", None)
+ return PregelNode(**attrs)
+
+ @cached_property
+ def flat_writers(self) -> list[Runnable]:
+ """Get writers with optimizations applied. Dedupes consecutive ChannelWrites."""
+ writers = self.writers.copy()
+ while (
+ len(writers) > 1
+ and isinstance(writers[-1], ChannelWrite)
+ and isinstance(writers[-2], ChannelWrite)
+ ):
+ # we can combine writes if they are consecutive
+ # careful to not modify the original writers list or ChannelWrite
+ writers[-2] = ChannelWrite(
+ writes=writers[-2].writes + writers[-1].writes,
+ )
+ writers.pop()
+ return writers
+
+ @cached_property
+ def node(self) -> Runnable[Any, Any] | None:
+ """Get a runnable that combines `bound` and `writers`."""
+ writers = self.flat_writers
+ if self.bound is DEFAULT_BOUND and not writers:
+ return None
+ elif self.bound is DEFAULT_BOUND and len(writers) == 1:
+ return writers[0]
+ elif self.bound is DEFAULT_BOUND:
+ return RunnableSeq(*writers)
+ elif writers:
+ return RunnableSeq(self.bound, *writers)
+ else:
+ return self.bound
+
+ @cached_property
+ def input_cache_key(self) -> INPUT_CACHE_KEY_TYPE:
+ """Get a cache key for the input to the node.
+ This is used to avoid calculating the same input multiple times."""
+ return (
+ self.mapper,
+ tuple(self.channels)
+ if isinstance(self.channels, list)
+ else (self.channels,),
+ )
+
+ def invoke(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Any:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ return self.bound.invoke(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ async def ainvoke(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Any:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ return await self.bound.ainvoke(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ def stream(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Any]:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ yield from self.bound.stream(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ )
+
+ async def astream(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Any]:
+ self_config: RunnableConfig = {"metadata": self.metadata, "tags": self.tags}
+ async for item in self.bound.astream(
+ input,
+ merge_configs(self_config, config),
+ **kwargs,
+ ):
+ yield item
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_retry.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..acade9643684bd205ebf672fa83816647473d926
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_retry.py
@@ -0,0 +1,798 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+import sys
+import threading
+import time
+import weakref
+from collections.abc import Awaitable, Callable, Sequence
+from contextlib import suppress
+from dataclasses import dataclass, replace
+from datetime import datetime, timedelta, timezone
+from typing import Any, Literal, NamedTuple
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.runnables import RunnableConfig
+
+from langgraph._internal._config import (
+ merge_configs,
+ patch_configurable,
+ recast_checkpoint_ns,
+)
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CALL,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_RESUMING,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ CONFIG_KEY_TIMED_ATTEMPT_OBSERVER,
+ NS_SEP,
+)
+from langgraph._internal._runnable import create_task_in_config_context
+from langgraph._internal._timeout import sync_timeout_unsupported
+from langgraph.errors import GraphBubbleUp, NodeTimeoutError, ParentCommand
+from langgraph.pregel.protocol import StreamProtocol
+from langgraph.runtime import ExecutionInfo, Runtime
+from langgraph.types import Command, PregelExecutableTask, RetryPolicy, TimeoutPolicy
+
+logger = logging.getLogger(__name__)
+SUPPORTS_EXC_NOTES = sys.version_info >= (3, 11)
+
+
+def _timeout_secs(value: float | timedelta) -> float:
+ return value.total_seconds() if isinstance(value, timedelta) else value
+
+
+@dataclass(frozen=True, slots=True)
+class _ResolvedTimeout:
+ run_timeout_secs: float | None
+ idle_timeout_secs: float | None
+ refresh_on: Literal["auto", "heartbeat"] | None
+
+
+def _resolve_timeout(timeout: TimeoutPolicy) -> _ResolvedTimeout:
+ idle_timeout_secs = (
+ _timeout_secs(timeout.idle_timeout)
+ if timeout.idle_timeout is not None
+ else None
+ )
+ return _ResolvedTimeout(
+ run_timeout_secs=(
+ _timeout_secs(timeout.run_timeout)
+ if timeout.run_timeout is not None
+ else None
+ ),
+ idle_timeout_secs=idle_timeout_secs,
+ refresh_on=timeout.refresh_on if idle_timeout_secs is not None else None,
+ )
+
+
+class _AttemptContext(NamedTuple):
+ """Immutable per-attempt metadata shared across start/progress/finish events.
+
+ Built once at attempt start and referenced (not copied) by every emitted
+ `_AttemptEvent`, so per-event allocation is just the small event wrapper.
+
+ Intentionally underscore-prefixed: this and `_AttemptEvent` are part of an
+ internal observer contract consumed by langgraph-server. Do not move to
+ `langgraph.types` — server imports them by this path.
+ """
+
+ task_id: str
+ task_name: str
+ attempt: int
+ run_id: str | None
+ thread_id: str | None
+ checkpoint_ns: str | None
+ started_at: datetime
+ run_timeout_secs: float | None
+ idle_timeout_secs: float | None
+ refresh_on: Literal["auto", "heartbeat"] | None
+
+
+@dataclass(frozen=True, slots=True)
+class _AttemptEvent:
+ """One lifecycle event for a timed attempt.
+
+ Holds a reference to the shared `_AttemptContext` and the event-specific
+ fields. The observer must treat this and `context` as read-only — they
+ are reused across all events for the same attempt.
+ """
+
+ context: _AttemptContext
+ event: Literal["start", "progress", "finish"]
+ progress_at: datetime | None = None
+ finished_at: datetime | None = None
+ status: Literal["success", "error"] | None = None
+ error_type: str | None = None
+ error_message: str | None = None
+
+
+class _TimedAttemptScope:
+ """Guarded-config window for timed attempts.
+
+ The wrapped config marks writes, stream events, runtime stream writer calls,
+ child task scheduling, and any LangChain callback event emitted under the
+ node's run as observable progress when `refresh_on="auto"`.
+ `runtime.heartbeat()` exposes a manual progress signal for work that doesn't
+ otherwise emit any of these, and is the only progress signal when
+ `refresh_on="heartbeat"`.
+ Guarded writes are serialized with `close()` so cancelled background tasks
+ cannot persist writes past the timeout boundary. Stream/custom output is
+ best-effort: it is dropped after close is observed, but callbacks run outside
+ the lock because they may contain arbitrary user/runtime code.
+ """
+
+ __slots__ = (
+ "__weakref__",
+ "_active",
+ "_last_progress",
+ "_last_progress_emit",
+ "_lock",
+ "_on_progress",
+ "_progress_min_interval",
+ "_refresh_on",
+ )
+
+ def __init__(
+ self,
+ on_progress: Callable[[], None] | None = None,
+ progress_min_interval: float = 0.0,
+ refresh_on: Literal["auto", "heartbeat"] | None = None,
+ ) -> None:
+ self._active = True
+ self._last_progress = time.monotonic()
+ self._lock = threading.Lock()
+ self._on_progress = on_progress
+ self._progress_min_interval = progress_min_interval
+ self._refresh_on = refresh_on
+ # `-inf` so the first touch always passes the rate-limit gate.
+ self._last_progress_emit: float = float("-inf")
+
+ def wrap_config(self, config: RunnableConfig) -> RunnableConfig:
+ configurable = config.get(CONF, {})
+ patch: dict[str, Any] = {}
+ if (send := configurable.get(CONFIG_KEY_SEND)) is not None:
+ patch[CONFIG_KEY_SEND] = self._guard_send(send)
+ if (stream := configurable.get(CONFIG_KEY_STREAM)) is not None:
+ patch[CONFIG_KEY_STREAM] = self._guard_stream(stream)
+ if (call := configurable.get(CONFIG_KEY_CALL)) is not None:
+ patch[CONFIG_KEY_CALL] = self._guard_call(call)
+ if isinstance(runtime := configurable.get(CONFIG_KEY_RUNTIME), Runtime):
+ if self._refresh_on is not None:
+ patch[CONFIG_KEY_RUNTIME] = runtime.override(
+ stream_writer=self._guard_stream_writer(runtime.stream_writer),
+ heartbeat=self.touch,
+ )
+ else:
+ patch[CONFIG_KEY_RUNTIME] = runtime.override(
+ stream_writer=self._guard_stream_writer(runtime.stream_writer)
+ )
+ new_config = patch_configurable(config, patch) if patch else config
+ if self._refresh_on == "auto":
+ return merge_configs(
+ new_config, {"callbacks": [_IdleProgressCallbackHandler(self)]}
+ )
+ return new_config
+
+ def touch(self) -> None:
+ # Avoid locking this hot progress path. We accept a small race window in
+ # timestamp ordering because idle_timeout is expected to be coarse compared
+ # with scheduler/thread timing.
+ now = time.monotonic()
+ self._last_progress = now
+ if self._on_progress is None:
+ return
+ # Best-effort rate limit: a benign race may emit a duplicate progress
+ # event under heavy concurrency, which observers must already tolerate
+ # (callbacks fire from arbitrary threads).
+ if now - self._last_progress_emit < self._progress_min_interval:
+ return
+ self._last_progress_emit = now
+ self._on_progress()
+
+ def close(self) -> None:
+ with self._lock:
+ self._active = False
+
+ async def wait_for_idle_timeout(self, idle_timeout_s: float) -> None:
+ while True:
+ with self._lock:
+ if not self._active:
+ return
+ remaining = self._last_progress + idle_timeout_s - time.monotonic()
+ if remaining <= 0:
+ raise asyncio.TimeoutError
+ await asyncio.sleep(remaining)
+
+ def _guard_send(
+ self, send: Callable[[Sequence[tuple[str, Any]]], None]
+ ) -> Callable[[Sequence[tuple[str, Any]]], None]:
+ def guarded_send(writes: Sequence[tuple[str, Any]]) -> None:
+ with self._lock:
+ if self._active:
+ if writes and self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ send(writes)
+
+ return guarded_send
+
+ def _guard_stream(self, stream: StreamProtocol) -> StreamProtocol:
+ # No lock: stream callbacks fire from the event loop only, so the
+ # active-check + write happen atomically between awaits.
+ def guarded_stream(chunk: tuple[tuple[str, ...], str, Any]) -> None:
+ if not self._active:
+ return
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ stream(chunk)
+
+ return StreamProtocol(guarded_stream, stream.modes)
+
+ def _guard_call(self, call: Callable[..., Any]) -> Callable[..., Any]:
+ # No lock: child-task scheduling happens from the event loop only.
+ def guarded_call(*args: Any, **kwargs: Any) -> Any:
+ if not self._active:
+ raise asyncio.CancelledError
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ return call(*args, **kwargs)
+
+ return guarded_call
+
+ def _guard_stream_writer(
+ self, stream_writer: Callable[[Any], None]
+ ) -> Callable[[Any], None]:
+ def guarded_stream_writer(chunk: Any) -> None:
+ with self._lock:
+ if not self._active:
+ return
+ if self._refresh_on == "auto":
+ self._last_progress = time.monotonic()
+ stream_writer(chunk)
+
+ return guarded_stream_writer
+
+
+class _IdleProgressCallbackHandler(BaseCallbackHandler):
+ """Resets the idle timeout clock on any LangChain callback event.
+
+ Inherits via `config["callbacks"]`, so it sees only events emitted by
+ runs descended from the node's attempt — sibling nodes do not bleed
+ through. Holds the scope by weakref so a child manager that outlives
+ the attempt cannot keep the scope alive.
+ """
+
+ # Run inline so progress is recorded in callback emission order;
+ # thread-pool dispatch would introduce extra reordering.
+ run_inline = True
+
+ def __init__(self, scope: _TimedAttemptScope) -> None:
+ self._scope_ref = weakref.ref(scope)
+
+ def _touch(self, *args: Any, **kwargs: Any) -> None:
+ if (scope := self._scope_ref()) is not None:
+ scope.touch()
+
+ on_llm_start = _touch
+ on_chat_model_start = _touch
+ on_llm_new_token = _touch
+ on_llm_end = _touch
+ on_llm_error = _touch
+ on_chain_start = _touch
+ on_chain_end = _touch
+ on_chain_error = _touch
+ on_tool_start = _touch
+ on_tool_end = _touch
+ on_tool_error = _touch
+ on_retriever_start = _touch
+ on_retriever_end = _touch
+ on_retriever_error = _touch
+ on_agent_action = _touch
+ on_agent_finish = _touch
+ on_text = _touch
+ on_retry = _touch
+ on_custom_event = _touch
+
+
+def _drain_cancelled(task: asyncio.Task[Any]) -> None:
+ # Mark the abandoned task's exception as retrieved so asyncio doesn't log it.
+ with suppress(asyncio.CancelledError):
+ task.exception()
+
+
+def _start_timed_attempt(
+ task: PregelExecutableTask, config: RunnableConfig, timeout: _ResolvedTimeout
+) -> _AttemptContext | None:
+ configurable = config.get(CONF, {})
+ callback = configurable.get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is None:
+ return None
+ runtime = configurable.get(CONFIG_KEY_RUNTIME)
+ execution_info = runtime.execution_info if isinstance(runtime, Runtime) else None
+ context = _AttemptContext(
+ task_id=task.id,
+ task_name=task.name,
+ attempt=execution_info.node_attempt if execution_info is not None else 1,
+ run_id=execution_info.run_id if execution_info is not None else None,
+ thread_id=execution_info.thread_id if execution_info is not None else None,
+ checkpoint_ns=(
+ execution_info.checkpoint_ns if execution_info is not None else None
+ ),
+ started_at=datetime.now(timezone.utc),
+ run_timeout_secs=timeout.run_timeout_secs,
+ idle_timeout_secs=timeout.idle_timeout_secs,
+ refresh_on=timeout.refresh_on,
+ )
+ _dispatch_observer(callback, _AttemptEvent(context=context, event="start"))
+ return context
+
+
+def _finish_timed_attempt(
+ config: RunnableConfig,
+ context: _AttemptContext | None,
+ error: BaseException | None = None,
+) -> None:
+ if context is None:
+ return
+ callback = config.get(CONF, {}).get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is None:
+ return
+ _dispatch_observer(
+ callback,
+ _AttemptEvent(
+ context=context,
+ event="finish",
+ finished_at=datetime.now(timezone.utc),
+ status="error" if error is not None else "success",
+ error_type=type(error).__name__ if error is not None else None,
+ error_message=str(error) if error is not None else None,
+ ),
+ )
+
+
+def _emit_progress(
+ callback: Callable[[_AttemptEvent], None],
+ context: _AttemptContext,
+) -> None:
+ _dispatch_observer(
+ callback,
+ _AttemptEvent(
+ context=context,
+ event="progress",
+ progress_at=datetime.now(timezone.utc),
+ ),
+ )
+
+
+def _dispatch_observer(
+ callback: Callable[[_AttemptEvent], None],
+ event: _AttemptEvent,
+) -> None:
+ try:
+ callback(event)
+ except Exception:
+ logger.warning("Timed attempt observer failed", exc_info=True)
+
+
+async def _run_timeout_watchdog(run_timeout_s: float) -> None:
+ await asyncio.sleep(run_timeout_s)
+ raise asyncio.TimeoutError
+
+
+async def _arun_with_timeout(
+ task: PregelExecutableTask,
+ config: RunnableConfig,
+ timeout: _ResolvedTimeout,
+ attempt_ctx: _AttemptContext | None,
+ *,
+ stream: bool,
+) -> Any:
+ run_timeout_s = timeout.run_timeout_secs
+ idle_timeout_s = timeout.idle_timeout_secs
+ on_progress: Callable[[], None] | None = None
+ if attempt_ctx is not None:
+ callback = config.get(CONF, {}).get(CONFIG_KEY_TIMED_ATTEMPT_OBSERVER)
+ if callback is not None and idle_timeout_s is not None:
+ on_progress = lambda: _emit_progress(callback, attempt_ctx) # noqa: E731
+ scope = _TimedAttemptScope(
+ on_progress=on_progress,
+ # Cap progress emission at ~4 events per idle window so token-rate
+ # callbacks don't flood the observer.
+ progress_min_interval=idle_timeout_s / 4 if idle_timeout_s is not None else 0.0,
+ refresh_on=timeout.refresh_on,
+ )
+ scoped_config = scope.wrap_config(config)
+ start = time.monotonic()
+ if stream:
+ # Yielded chunks count as progress only under `refresh_on="auto"`.
+ # `refresh_on="heartbeat"` is the strict mode where only explicit
+ # `runtime.heartbeat()` calls reset the idle clock.
+ async def run() -> Any:
+ async for _ in task.proc.astream(task.input, scoped_config):
+ if timeout.refresh_on == "auto":
+ scope.touch()
+
+ else:
+
+ async def run() -> Any:
+ return await task.proc.ainvoke(task.input, scoped_config)
+
+ bg = create_task_in_config_context(run, scoped_config)
+ watchdogs: dict[asyncio.Task[None], Literal["idle", "run"]] = {}
+ if idle_timeout_s is not None:
+ watchdogs[asyncio.create_task(scope.wait_for_idle_timeout(idle_timeout_s))] = (
+ "idle"
+ )
+ if run_timeout_s is not None:
+ watchdogs[asyncio.create_task(_run_timeout_watchdog(run_timeout_s))] = "run"
+ try:
+ done, _ = await asyncio.wait(
+ {bg, *watchdogs}, return_when=asyncio.FIRST_COMPLETED
+ )
+ if bg in done:
+ # Task completed in time.
+ for watchdog in watchdogs:
+ watchdog.cancel()
+ # FIRST_COMPLETED can return both; a watchdog may have
+ # already raised TimeoutError before we cancelled it.
+ for watchdog in watchdogs:
+ with suppress(asyncio.CancelledError, asyncio.TimeoutError):
+ await watchdog
+ return await bg
+ # bg was not in `done`, so every member of `done` is one of our
+ # watchdogs. Only a watchdog's TimeoutError converts to
+ # NodeTimeoutError; any TimeoutError raised by the proc itself
+ # propagates unchanged.
+ for watchdog in done:
+ kind = watchdogs[watchdog]
+ try:
+ await watchdog
+ except asyncio.TimeoutError as exc:
+ elapsed = time.monotonic() - start
+ scope.close()
+ task.writes.clear()
+ bg.cancel()
+ bg.add_done_callback(_drain_cancelled)
+ raise NodeTimeoutError(
+ task.name,
+ elapsed,
+ kind=kind,
+ idle_timeout=idle_timeout_s,
+ run_timeout=run_timeout_s,
+ ) from exc
+ raise RuntimeError(
+ f"{kind} timeout watchdog completed without raising TimeoutError"
+ )
+ raise RuntimeError("timeout wait completed without task or watchdog")
+ except asyncio.CancelledError:
+ scope.close()
+ bg.cancel()
+ for watchdog in watchdogs:
+ watchdog.cancel()
+ bg.add_done_callback(_drain_cancelled)
+ raise
+ finally:
+ scope.close()
+ for watchdog in watchdogs:
+ watchdog.cancel()
+
+
+def _ensure_execution_info(
+ runtime: Runtime, config: RunnableConfig, task: PregelExecutableTask
+) -> Runtime:
+ """Ensure runtime has execution_info, creating one from config if needed.
+
+ In the distributed runtime (LangGraph Platform), tasks are prepared by the
+ server and deserialized in the executor, bypassing the OSS _algo.py code
+ that normally creates ExecutionInfo. This function fills in execution_info
+ from the task config when it's missing.
+ """
+ if runtime.execution_info is not None:
+ return runtime
+ configurable = config.get(CONF, {})
+ return runtime.override(
+ execution_info=ExecutionInfo(
+ checkpoint_id=configurable.get(CONFIG_KEY_CHECKPOINT_ID) or "",
+ checkpoint_ns=configurable.get(CONFIG_KEY_CHECKPOINT_NS) or "",
+ task_id=configurable.get(CONFIG_KEY_TASK_ID) or task.id,
+ thread_id=configurable.get(CONFIG_KEY_THREAD_ID),
+ run_id=str(rid) if (rid := config.get("run_id")) else None,
+ ),
+ )
+
+
+def _checkpoint_ns_for_parent_command(ns: str) -> str:
+ """Return the checkpoint namespace for the parent graph.
+
+ The checkpoint namespace is a `|`-separated path. Each segment is usually
+ of the form `name:task_id` (e.g. `parent_first:|node:`), but the
+ runtime may also insert a purely-numeric segment (e.g. `|1`) to disambiguate
+ concurrent tasks (e.g. `parent_first:|1|node:`).
+
+ Numeric segments are not real path levels, so we drop them before computing
+ the parent namespace.
+ """
+
+ parts = ns.split(NS_SEP)
+
+ # Drop any trailing numeric selectors for the current frame (e.g. `...|node:|1`).
+ while parts and parts[-1].isdigit():
+ parts.pop()
+
+ # Drop the current frame segment itself (e.g. the `node:`).
+ if parts:
+ parts.pop()
+
+ # Drop any trailing numeric selectors for the parent frame (e.g. `...|1|node:`).
+ while parts and parts[-1].isdigit():
+ parts.pop()
+
+ return NS_SEP.join(parts)
+
+
+def run_with_retry(
+ task: PregelExecutableTask,
+ retry_policy: Sequence[RetryPolicy] | None,
+ configurable: dict[str, Any] | None = None,
+) -> None:
+ """Run a task with retries."""
+ retry_policy = task.retry_policy or retry_policy
+ if task.timeout is not None:
+ # `validate_timeout_supported` catches sync nodes at compile time;
+ # this is a runtime safety net for paths that may bypass that validation.
+ raise sync_timeout_unsupported(task.name)
+ attempts = 0
+ node_first_attempt_time = time.time()
+ config = task.config
+ if configurable is not None:
+ config = patch_configurable(config, configurable)
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ runtime = _ensure_execution_info(runtime, config, task)
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ node_first_attempt_time=node_first_attempt_time,
+ )
+ },
+ )
+ while True:
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ # node_attempt is execution count (1-indexed): 1 on first run,
+ # then 2, 3, ... on subsequent retries.
+ node_attempt=attempts + 1,
+ )
+ },
+ )
+ try:
+ # clear any writes from previous attempts
+ task.writes.clear()
+ # run the task
+ return task.proc.invoke(task.input, config)
+ except ParentCommand as exc:
+ ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
+ cmd = exc.args[0]
+ # strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
+ if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
+ # this command is for the current graph, handle it
+ for w in task.writers:
+ w.invoke(cmd, config)
+ break
+ elif cmd.graph == Command.PARENT:
+ # this command is for the parent graph, assign it to the parent.
+ exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
+ # bubble up
+ raise
+ except GraphBubbleUp:
+ # if interrupted, end
+ raise
+ except Exception as exc:
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
+ if not retry_policy:
+ raise
+
+ # Check which retry policy applies to this exception
+ matching_policy = None
+ for policy in retry_policy:
+ if _should_retry_on(policy, exc):
+ matching_policy = policy
+ break
+
+ if not matching_policy:
+ raise
+
+ # attempts tracks failed tries only; it increments after a failure.
+ attempts += 1
+ # check if we should give up
+ if attempts >= matching_policy.max_attempts:
+ raise
+ # sleep before retrying
+ interval = matching_policy.initial_interval
+ # Apply backoff factor based on attempt count
+ interval = min(
+ matching_policy.max_interval,
+ interval * (matching_policy.backoff_factor ** (attempts - 1)),
+ )
+
+ # Apply jitter if configured
+ sleep_time = (
+ interval + random.uniform(0, 1) if matching_policy.jitter else interval
+ )
+ time.sleep(sleep_time)
+
+ # log the retry
+ logger.info(
+ f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
+ exc_info=exc,
+ )
+ # signal subgraphs to resume (if available)
+ config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
+
+
+async def arun_with_retry(
+ task: PregelExecutableTask,
+ retry_policy: Sequence[RetryPolicy] | None,
+ stream: bool = False,
+ match_cached_writes: Callable[[], Awaitable[Sequence[PregelExecutableTask]]]
+ | None = None,
+ configurable: dict[str, Any] | None = None,
+) -> None:
+ """Run a task asynchronously with retries."""
+ retry_policy = task.retry_policy or retry_policy
+ resolved_timeout = (
+ _resolve_timeout(task.timeout) if task.timeout is not None else None
+ )
+ attempts = 0
+ node_first_attempt_time = time.time()
+ config = task.config
+ if configurable is not None:
+ config = patch_configurable(config, configurable)
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ runtime = _ensure_execution_info(runtime, config, task)
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ node_first_attempt_time=node_first_attempt_time,
+ )
+ },
+ )
+ if match_cached_writes is not None and task.cache_key is not None:
+ for t in await match_cached_writes():
+ if t is task:
+ # if the task is already cached, return
+ return
+ while True:
+ runtime = config.get(CONF, {}).get(CONFIG_KEY_RUNTIME)
+ if isinstance(runtime, Runtime):
+ config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_RUNTIME: runtime.patch_execution_info(
+ # node_attempt is execution count (1-indexed): 1 on first run,
+ # then 2, 3, ... on subsequent retries.
+ node_attempt=attempts + 1,
+ )
+ },
+ )
+ attempt_ctx = (
+ _start_timed_attempt(task, config, resolved_timeout)
+ if resolved_timeout is not None
+ else None
+ )
+ try:
+ task.writes.clear()
+ if resolved_timeout is None:
+ if stream:
+ async for _ in task.proc.astream(task.input, config):
+ pass
+ break
+ return await task.proc.ainvoke(task.input, config)
+ result = await _arun_with_timeout(
+ task, config, resolved_timeout, attempt_ctx, stream=stream
+ )
+ _finish_timed_attempt(config, attempt_ctx)
+ if stream:
+ # if successful, end
+ break
+ return result
+ except ParentCommand as exc:
+ ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
+ cmd = exc.args[0]
+ # strip task_ids from namespace for comparison (ns format: "node1|node2:task_id")
+ if cmd.graph in (ns, recast_checkpoint_ns(ns), task.name):
+ try:
+ # this command is for the current graph, handle it
+ for w in task.writers:
+ w.invoke(cmd, config)
+ except Exception as writer_exc:
+ _finish_timed_attempt(config, attempt_ctx, writer_exc)
+ raise
+ _finish_timed_attempt(config, attempt_ctx)
+ break
+ elif cmd.graph == Command.PARENT:
+ # this command is for the parent graph, assign it to the parent.
+ exc.args = (replace(cmd, graph=_checkpoint_ns_for_parent_command(ns)),)
+ _finish_timed_attempt(config, attempt_ctx)
+ # bubble up the exception to the parent graph
+ raise
+ except GraphBubbleUp:
+ # if interrupted, end
+ _finish_timed_attempt(config, attempt_ctx)
+ raise
+ except Exception as exc:
+ _finish_timed_attempt(config, attempt_ctx, exc)
+ if SUPPORTS_EXC_NOTES:
+ exc.add_note(f"During task with name '{task.name}' and id '{task.id}'")
+ if not retry_policy:
+ raise
+
+ # Check which retry policy applies to this exception
+ matching_policy = None
+ for policy in retry_policy:
+ if _should_retry_on(policy, exc):
+ matching_policy = policy
+ break
+
+ if not matching_policy:
+ raise
+
+ # attempts tracks failed tries only; it increments after a failure.
+ # The next execution's node_attempt is derived as attempts + 1.
+ attempts += 1
+ # check if we should give up
+ if attempts >= matching_policy.max_attempts:
+ raise
+ # sleep before retrying
+ interval = matching_policy.initial_interval
+ # Apply backoff factor based on attempt count
+ interval = min(
+ matching_policy.max_interval,
+ interval * (matching_policy.backoff_factor ** (attempts - 1)),
+ )
+
+ # Apply jitter if configured
+ sleep_time = (
+ interval + random.uniform(0, 1) if matching_policy.jitter else interval
+ )
+ await asyncio.sleep(sleep_time)
+
+ # log the retry
+ logger.info(
+ f"Retrying task {task.name} after {sleep_time:.2f} seconds (attempt {attempts}) after {exc.__class__.__name__} {exc}",
+ exc_info=exc,
+ )
+ # signal subgraphs to resume (if available)
+ config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
+
+
+def _should_retry_on(retry_policy: RetryPolicy, exc: Exception) -> bool:
+ """Check if the given exception should be retried based on the retry policy."""
+ if isinstance(retry_policy.retry_on, Sequence):
+ return isinstance(exc, tuple(retry_policy.retry_on))
+ elif isinstance(retry_policy.retry_on, type) and issubclass(
+ retry_policy.retry_on, Exception
+ ):
+ return isinstance(exc, retry_policy.retry_on)
+ elif callable(retry_policy.retry_on):
+ return retry_policy.retry_on(exc) # type: ignore[call-arg]
+ else:
+ raise TypeError(
+ "retry_on must be an Exception class, a list or tuple of Exception classes, or a callable"
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_runner.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d53b9f9de80dc397ec23c79f0707e38152f9519
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_runner.py
@@ -0,0 +1,941 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import inspect
+import threading
+import time
+import weakref
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Collection,
+ Iterable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from functools import partial
+from typing import (
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.callbacks import Callbacks
+
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CALL,
+ CONFIG_KEY_SCRATCHPAD,
+ ERROR,
+ ERROR_SOURCE_NODE,
+ INTERRUPT,
+ NO_WRITES,
+ RESUME,
+ RETURN,
+)
+from langgraph._internal._future import chain_future, run_coroutine_threadsafe
+from langgraph._internal._scratchpad import PregelScratchpad
+from langgraph._internal._typing import MISSING
+from langgraph.constants import TAG_HIDDEN
+from langgraph.errors import GraphBubbleUp, GraphInterrupt
+from langgraph.pregel._algo import Call
+from langgraph.pregel._executor import Submit
+from langgraph.pregel._retry import arun_with_retry, run_with_retry
+from langgraph.types import (
+ CachePolicy,
+ PregelExecutableTask,
+ RetryPolicy,
+ TimeoutPolicy,
+)
+
+F = TypeVar("F", concurrent.futures.Future, asyncio.Future)
+E = TypeVar("E", threading.Event, asyncio.Event)
+
+# List of filenames to exclude from exception traceback
+# Note: Frames will be removed if they are the last frame in traceback, recursively
+EXCLUDED_FRAME_FNAMES = (
+ "langgraph/pregel/retry.py",
+ "langgraph/pregel/runner.py",
+ "langgraph/pregel/executor.py",
+ "langgraph/utils/runnable.py",
+ "langchain_core/runnables/config.py",
+ "concurrent/futures/thread.py",
+ "concurrent/futures/_base.py",
+)
+
+SKIP_RERAISE_SET: weakref.WeakSet[concurrent.futures.Future | asyncio.Future] = (
+ weakref.WeakSet()
+)
+
+
+class FuturesDict(Generic[F, E], dict[F, PregelExecutableTask | None]):
+ event: E
+ callback: weakref.ref[Callable[[PregelExecutableTask, BaseException | None], None]]
+ # Stop condition is injected by PregelRunner instead of hard-coded here.
+ # This lets the runner treat graph-error-handled exceptions as non-fatal
+ # so `on_done` does not trigger an early stop for those futures.
+ should_stop: Callable[[set[F]], bool]
+ counter: int
+ done: set[F]
+ lock: threading.Lock
+
+ def __init__(
+ self,
+ event: E,
+ callback: weakref.ref[
+ Callable[[PregelExecutableTask, BaseException | None], None]
+ ],
+ should_stop: Callable[[set[F]], bool],
+ future_type: type[F],
+ # used for generic typing, newer py supports FutureDict[...](...)
+ ) -> None:
+ super().__init__()
+ self.lock = threading.Lock()
+ self.event = event
+ self.callback = callback
+ self.should_stop = should_stop
+ self.counter = 0
+ self.done: set[F] = set()
+
+ def __setitem__(
+ self,
+ key: F,
+ value: PregelExecutableTask | None,
+ ) -> None:
+ super().__setitem__(key, value) # type: ignore[index]
+ if value is not None:
+ with self.lock:
+ self.event.clear()
+ self.counter += 1
+ key.add_done_callback(partial(self.on_done, value))
+
+ def on_done(
+ self,
+ task: PregelExecutableTask,
+ fut: F,
+ ) -> None:
+ # Called automatically by future.add_done_callback registered in __setitem__.
+ try:
+ if cb := self.callback():
+ cb(task, _exception(fut))
+ finally:
+ with self.lock:
+ self.done.add(fut)
+ self.counter -= 1
+ # Wake waiter when all tracked futures are done, or when runner-level
+ # stop condition is met (for example, a non-handled fatal exception).
+ if self.counter == 0 or self.should_stop(self.done):
+ self.event.set()
+
+
+class PregelRunner:
+ """Responsible for executing a set of Pregel tasks concurrently, committing
+ their writes, yielding control to caller when there is output to emit, and
+ interrupting other tasks if appropriate."""
+
+ def __init__(
+ self,
+ *,
+ submit: weakref.ref[Submit],
+ put_writes: weakref.ref[Callable[[str, Sequence[tuple[str, Any]]], None]],
+ use_astream: bool = False,
+ node_finished: Callable[[str], None] | None = None,
+ node_error_handler_map: Mapping[str, str] | None = None,
+ schedule_error_handler: Callable[
+ [PregelExecutableTask, BaseException], PregelExecutableTask | None
+ ]
+ | None = None,
+ aschedule_error_handler: Callable[
+ [PregelExecutableTask, BaseException],
+ Awaitable[PregelExecutableTask | None],
+ ]
+ | None = None,
+ ) -> None:
+ self.submit = submit
+ self.put_writes = put_writes
+ self.use_astream = use_astream
+ self.node_finished = node_finished
+ self.node_error_handler_map = dict(node_error_handler_map or {})
+ self.error_handler_nodes = set(self.node_error_handler_map.values())
+ self.schedule_error_handler = schedule_error_handler
+ self.aschedule_error_handler = aschedule_error_handler
+ # Exception object ids that are already routed to graph-level error handler.
+ # These ids are consulted by stop/panic checks to avoid re-raising handled
+ # exceptions via the normal fatal path in the same run.
+ self._handled_exception_ids: set[int] = set()
+
+ def _should_route_to_error_handler(self, task: PregelExecutableTask) -> bool:
+ if task.name in self.error_handler_nodes:
+ return False
+ return task.name in self.node_error_handler_map
+
+ def tick(
+ self,
+ tasks: Iterable[PregelExecutableTask],
+ *,
+ reraise: bool = True,
+ timeout: float | None = None,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ get_waiter: Callable[[], concurrent.futures.Future[None]] | None = None,
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ PregelExecutableTask | None,
+ ],
+ ) -> Iterator[None]:
+ tasks = tuple(tasks)
+ futures = FuturesDict(
+ callback=weakref.WeakMethod(self.commit),
+ event=threading.Event(),
+ should_stop=partial(
+ _should_stop_others, handled_exception_ids=self._handled_exception_ids
+ ),
+ future_type=concurrent.futures.Future,
+ )
+ # give control back to the caller
+ yield
+ # fast path if single task with no timeout and no waiter
+ if len(tasks) == 0:
+ return
+ elif len(tasks) == 1 and timeout is None and get_waiter is None:
+ t = tasks[0]
+ scheduled_error_handler = False
+ try:
+ run_with_retry(
+ t,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ )
+ self.commit(t, None)
+ except Exception as exc:
+ self.commit(t, exc)
+ if (
+ not isinstance(exc, GraphBubbleUp)
+ and self._should_route_to_error_handler(t)
+ and self.schedule_error_handler is not None
+ ):
+ self._handled_exception_ids.add(id(exc))
+ if handler_task := self.schedule_error_handler(t, exc):
+ tasks = (handler_task,)
+ scheduled_error_handler = True
+ # Continue to the regular scheduling path for handler execution.
+ if reraise and futures:
+ if id(exc) not in self._handled_exception_ids:
+ # will be re-raised after futures are done
+ fut: concurrent.futures.Future = concurrent.futures.Future()
+ fut.set_exception(exc)
+ futures.done.add(fut)
+ elif reraise and id(exc) not in self._handled_exception_ids:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+ if not futures and not scheduled_error_handler:
+ # maybe `t` scheduled another task
+ return
+ else:
+ if not scheduled_error_handler:
+ tasks = () # don't reschedule this task
+ # add waiter task if requested
+ if get_waiter is not None:
+ futures[get_waiter()] = None
+ # schedule tasks
+ for t in tasks:
+ fut = self.submit()( # type: ignore[misc]
+ run_with_retry,
+ t,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ __reraise_on_exit__=reraise,
+ )
+ futures[fut] = t
+ # execute tasks, and wait for one to fail or all to finish.
+ # each task is independent from all other concurrent tasks
+ # yield updates/debug output as each task finishes
+ end_time = timeout + time.monotonic() if timeout else None
+ handled_futures: set[concurrent.futures.Future[Any]] = set()
+ while len(futures) > (1 if get_waiter is not None else 0):
+ done, inflight = concurrent.futures.wait(
+ futures,
+ return_when=concurrent.futures.FIRST_COMPLETED,
+ timeout=(max(0, end_time - time.monotonic()) if end_time else None),
+ )
+ if not done:
+ break # timed out
+ done_for_stop: set[concurrent.futures.Future[Any]] = set()
+ for fut in done:
+ task = futures.pop(fut)
+ if task is None:
+ # waiter task finished, schedule another
+ if inflight and get_waiter is not None:
+ futures[get_waiter()] = None
+ elif (
+ (task_exc := _exception(fut))
+ and self._should_route_to_error_handler(task)
+ and not isinstance(task_exc, GraphBubbleUp)
+ ):
+ self._handled_exception_ids.add(id(task_exc))
+ SKIP_RERAISE_SET.add(fut)
+ handled_futures.add(fut)
+ if self.schedule_error_handler is not None:
+ if handler_task := self.schedule_error_handler(task, task_exc):
+ handler_fut = self.submit()( # type: ignore[misc]
+ run_with_retry,
+ handler_task,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(handler_task),
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ ),
+ },
+ __reraise_on_exit__=reraise,
+ )
+ futures[handler_fut] = handler_task
+ else:
+ done_for_stop.add(fut)
+ else:
+ # remove references to loop vars
+ del fut, task
+ # maybe stop other tasks
+ if _should_stop_others(
+ done_for_stop, handled_exception_ids=self._handled_exception_ids
+ ):
+ break
+ # give control back to the caller
+ yield
+ # wait for done callbacks
+ futures.event.wait(
+ timeout=(max(0, end_time - time.monotonic()) if end_time else None)
+ )
+ # give control back to the caller
+ yield
+ # panic on failure or timeout
+ try:
+ _panic_or_proceed(
+ futures.done.union(f for f, t in futures.items() if t is not None),
+ panic=reraise,
+ handled_exception_ids=self._handled_exception_ids,
+ handled_futures=handled_futures,
+ )
+ except Exception as exc:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+
+ async def atick(
+ self,
+ tasks: Iterable[PregelExecutableTask],
+ *,
+ reraise: bool = True,
+ timeout: float | None = None,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ get_waiter: Callable[[], asyncio.Future[None]] | None = None,
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ ) -> AsyncIterator[None]:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ tasks = tuple(tasks)
+ futures = FuturesDict(
+ callback=weakref.WeakMethod(self.commit),
+ event=asyncio.Event(),
+ should_stop=partial(
+ _should_stop_others, handled_exception_ids=self._handled_exception_ids
+ ),
+ future_type=asyncio.Future,
+ )
+ # give control back to the caller
+ yield
+ # fast path if single task with no waiter and no timeout
+ if len(tasks) == 0:
+ return
+ elif len(tasks) == 1 and get_waiter is None and timeout is None:
+ t = tasks[0]
+ scheduled_error_handler = False
+ try:
+ await arun_with_retry(
+ t,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(t),
+ stream=self.use_astream,
+ retry_policy=retry_policy,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ )
+ self.commit(t, None)
+ except Exception as exc:
+ self.commit(t, exc)
+ if (
+ not isinstance(exc, GraphBubbleUp)
+ and self._should_route_to_error_handler(t)
+ and self.aschedule_error_handler is not None
+ ):
+ self._handled_exception_ids.add(id(exc))
+ if handler_task := await self.aschedule_error_handler(t, exc):
+ tasks = (handler_task,)
+ scheduled_error_handler = True
+ if reraise and futures:
+ if id(exc) not in self._handled_exception_ids:
+ # will be re-raised after futures are done
+ fut: asyncio.Future = loop.create_future()
+ fut.set_exception(exc)
+ futures.done.add(fut)
+ elif reraise and id(exc) not in self._handled_exception_ids:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+ if not futures and not scheduled_error_handler:
+ # maybe `t` scheduled another task
+ return
+ else:
+ if not scheduled_error_handler:
+ tasks = () # don't reschedule this task
+ # add waiter task if requested
+ if get_waiter is not None:
+ futures[get_waiter()] = None
+ # schedule tasks
+ for t in tasks:
+ fut = cast(
+ asyncio.Future,
+ self.submit()( # type: ignore[misc]
+ arun_with_retry,
+ t,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(t),
+ retry_policy=retry_policy,
+ stream=self.use_astream,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ __name__=t.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=reraise,
+ ),
+ )
+ futures[fut] = t
+ # execute tasks, and wait for one to fail or all to finish.
+ # each task is independent from all other concurrent tasks
+ # yield updates/debug output as each task finishes
+ end_time = timeout + loop.time() if timeout else None
+ handled_futures: set[asyncio.Future[Any]] = set()
+ while len(futures) > (1 if get_waiter is not None else 0):
+ done, inflight = await asyncio.wait(
+ futures,
+ return_when=asyncio.FIRST_COMPLETED,
+ timeout=(max(0, end_time - loop.time()) if end_time else None),
+ )
+ if not done:
+ break # timed out
+ done_for_stop: set[asyncio.Future[Any]] = set()
+ for fut in done:
+ task = futures.pop(fut)
+ if task is None:
+ # waiter task finished, schedule another
+ if inflight and get_waiter is not None:
+ futures[get_waiter()] = None
+ elif (
+ (task_exc := _exception(fut))
+ and self._should_route_to_error_handler(task)
+ and not isinstance(task_exc, GraphBubbleUp)
+ ):
+ self._handled_exception_ids.add(id(task_exc))
+ SKIP_RERAISE_SET.add(fut)
+ handled_futures.add(fut)
+ if self.aschedule_error_handler is not None:
+ if handler_task := await self.aschedule_error_handler(
+ task, task_exc
+ ):
+ handler_fut = cast(
+ asyncio.Future,
+ self.submit()( # type: ignore[misc]
+ arun_with_retry,
+ handler_task,
+ retry_policy,
+ stream=self.use_astream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(handler_task),
+ retry_policy=retry_policy,
+ stream=self.use_astream,
+ futures=weakref.ref(futures),
+ schedule_task=schedule_task,
+ submit=self.submit,
+ loop=loop,
+ ),
+ },
+ __name__=handler_task.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=reraise,
+ ),
+ )
+ futures[handler_fut] = handler_task
+ else:
+ done_for_stop.add(fut)
+ else:
+ # remove references to loop vars
+ del fut, task
+ # maybe stop other tasks
+ if _should_stop_others(
+ done_for_stop, handled_exception_ids=self._handled_exception_ids
+ ):
+ break
+ # give control back to the caller
+ yield
+ # wait for done callbacks
+ await asyncio.wait_for(
+ futures.event.wait(),
+ timeout=(max(0, end_time - loop.time()) if end_time else None),
+ )
+ # give control back to the caller
+ yield
+ # cancel waiter task
+ for fut in futures:
+ fut.cancel()
+ # panic on failure or timeout
+ try:
+ _panic_or_proceed(
+ futures.done.union(f for f, t in futures.items() if t is not None),
+ timeout_exc_cls=asyncio.TimeoutError,
+ panic=reraise,
+ handled_exception_ids=self._handled_exception_ids,
+ handled_futures=handled_futures,
+ )
+ except Exception as exc:
+ if tb := exc.__traceback__:
+ while tb.tb_next is not None and any(
+ tb.tb_frame.f_code.co_filename.endswith(name)
+ for name in EXCLUDED_FRAME_FNAMES
+ ):
+ tb = tb.tb_next
+ exc.__traceback__ = tb
+ raise
+
+ def commit(
+ self,
+ task: PregelExecutableTask,
+ exception: BaseException | None,
+ ) -> None:
+ if isinstance(exception, asyncio.CancelledError):
+ # for cancelled tasks, also save error in task,
+ # so loop can finish super-step
+ task.writes.append((ERROR, exception))
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+ elif exception:
+ if isinstance(exception, GraphInterrupt):
+ # save interrupt to checkpointer
+ if exception.args[0]:
+ writes = [(INTERRUPT, exception.args[0])]
+ if resumes := [w for w in task.writes if w[0] == RESUME]:
+ writes.extend(resumes)
+ self.put_writes()(task.id, writes) # type: ignore[misc]
+ elif isinstance(exception, GraphBubbleUp):
+ # exception will be raised in _panic_or_proceed
+ pass
+ else:
+ # save error to checkpointer
+ task.writes.append((ERROR, exception))
+ if self._should_route_to_error_handler(task) and not isinstance(
+ exception, GraphBubbleUp
+ ):
+ task.writes.append((ERROR_SOURCE_NODE, task.name))
+ self._handled_exception_ids.add(id(exception))
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+ else:
+ if self.node_finished and (
+ task.config is None or TAG_HIDDEN not in task.config.get("tags", [])
+ ):
+ self.node_finished(task.name)
+ if not task.writes:
+ # add no writes marker
+ task.writes.append((NO_WRITES, None))
+ # save task writes to checkpointer
+ self.put_writes()(task.id, task.writes) # type: ignore[misc]
+
+
+def _should_stop_others(
+ done: set[F],
+ *,
+ handled_exception_ids: set[int] | None = None,
+) -> bool:
+ """Check if any task failed, if so, cancel all other tasks.
+ GraphInterrupts are not considered failures."""
+ for fut in done:
+ if fut.cancelled():
+ continue
+ elif exc := fut.exception():
+ if (
+ id(exc) not in (handled_exception_ids or set())
+ and not isinstance(exc, GraphBubbleUp)
+ and fut not in SKIP_RERAISE_SET
+ ):
+ return True
+
+ return False
+
+
+def _exception(
+ fut: concurrent.futures.Future[Any] | asyncio.Future[Any],
+) -> BaseException | None:
+ """Return the exception from a future, without raising CancelledError."""
+ if fut.cancelled():
+ if isinstance(fut, asyncio.Future):
+ return asyncio.CancelledError()
+ else:
+ return concurrent.futures.CancelledError()
+ else:
+ return fut.exception()
+
+
+def _panic_or_proceed(
+ futs: set[concurrent.futures.Future] | set[asyncio.Future],
+ *,
+ timeout_exc_cls: type[Exception] = TimeoutError,
+ panic: bool = True,
+ handled_exception_ids: set[int] | None = None,
+ handled_futures: Collection[concurrent.futures.Future[Any] | asyncio.Future[Any]]
+ | None = None,
+) -> None:
+ """Cancel remaining tasks if any failed, re-raise exception if panic is True."""
+ done: set[concurrent.futures.Future[Any] | asyncio.Future[Any]] = set()
+ inflight: set[concurrent.futures.Future[Any] | asyncio.Future[Any]] = set()
+ for fut in futs:
+ if fut.cancelled():
+ continue
+ elif fut.done():
+ done.add(fut)
+ else:
+ inflight.add(fut)
+ interrupts: list[GraphInterrupt] = []
+ while done:
+ # if any task failed
+ fut = done.pop()
+ if exc := _exception(fut):
+ if fut in (handled_futures or set()):
+ continue
+ if id(exc) in (handled_exception_ids or set()):
+ continue
+ # cancel all pending tasks
+ while inflight:
+ inflight.pop().cancel()
+ # raise the exception
+ if panic:
+ if isinstance(exc, GraphInterrupt):
+ # collect interrupts
+ interrupts.append(exc)
+ elif fut not in SKIP_RERAISE_SET:
+ raise exc
+ # raise combined interrupts
+ if interrupts:
+ raise GraphInterrupt(tuple(i for exc in interrupts for i in exc.args[0]))
+ if inflight:
+ # if we got here means we timed out
+ while inflight:
+ # cancel all pending tasks
+ inflight.pop().cancel()
+ # raise timeout error
+ raise timeout_exc_cls("Timed out")
+
+
+def _call(
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ futures: weakref.ref[FuturesDict],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None], PregelExecutableTask | None
+ ],
+ submit: weakref.ref[Submit],
+) -> concurrent.futures.Future[Any]:
+ if inspect.iscoroutinefunction(func):
+ raise RuntimeError("In an sync context async tasks cannot be called")
+
+ fut: concurrent.futures.Future | None = None
+ # schedule PUSH tasks, collect futures
+ scratchpad: PregelScratchpad = task().config[CONF][CONFIG_KEY_SCRATCHPAD] # type: ignore[union-attr]
+ # schedule the next task, if the callback returns one
+ if next_task := schedule_task(
+ task(), # type: ignore[arg-type]
+ scratchpad.call_counter(),
+ Call(
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=callbacks,
+ timeout=timeout,
+ ),
+ ):
+ if fut := next(
+ (
+ f
+ for f, t in list(futures().items()) # type: ignore[union-attr]
+ if t is not None and t == next_task.id
+ ),
+ None,
+ ):
+ # if the parent task was retried,
+ # the next task might already be running
+ pass
+ elif next_task.writes:
+ # if it already ran, return the result
+ fut = concurrent.futures.Future()
+ ret = next((v for c, v in next_task.writes if c == RETURN), MISSING)
+ if ret is not MISSING:
+ fut.set_result(ret)
+ elif exc := next((v for c, v in next_task.writes if c == ERROR), None):
+ fut.set_exception(
+ exc if isinstance(exc, BaseException) else Exception(exc)
+ )
+ else:
+ fut.set_result(None)
+ else:
+ # schedule the next task
+ fut = submit()( # type: ignore[misc]
+ run_with_retry,
+ next_task,
+ retry_policy,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _call,
+ weakref.ref(next_task),
+ futures=futures,
+ retry_policy=retry_policy,
+ callbacks=callbacks,
+ schedule_task=schedule_task,
+ submit=submit,
+ ),
+ },
+ __reraise_on_exit__=False,
+ # starting a new task in the next tick ensures
+ # updates from this tick are committed/streamed first
+ __next_tick__=True,
+ )
+ # exceptions for call() tasks are raised into the parent task
+ # so we should not re-raise at the end of the tick
+ SKIP_RERAISE_SET.add(fut)
+ futures()[fut] = next_task # type: ignore[index]
+ fut = cast(asyncio.Future | concurrent.futures.Future, fut)
+ # return a chained future to ensure commit() callback is called
+ # before the returned future is resolved, to ensure stream order etc
+ return chain_future(fut, concurrent.futures.Future())
+
+
+def _acall(
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ # injected dependencies
+ futures: weakref.ref[FuturesDict],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ submit: weakref.ref[Submit],
+ loop: asyncio.AbstractEventLoop,
+ stream: bool = False,
+) -> asyncio.Future[Any] | concurrent.futures.Future[Any]:
+ # return a chained future to ensure commit() callback is called
+ # before the returned future is resolved, to ensure stream order etc
+ try:
+ in_async = asyncio.current_task() is not None
+ except RuntimeError:
+ in_async = False
+ # if in async context return an async future, otherwise return a sync future
+ if in_async:
+ fut: asyncio.Future[Any] | concurrent.futures.Future[Any] = asyncio.Future(
+ loop=loop
+ )
+ else:
+ fut = concurrent.futures.Future()
+ # schedule the next task
+ run_coroutine_threadsafe(
+ _acall_impl(
+ fut,
+ task,
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ timeout=timeout,
+ callbacks=callbacks,
+ futures=futures,
+ schedule_task=schedule_task,
+ submit=submit,
+ loop=loop,
+ stream=stream,
+ ),
+ loop,
+ lazy=False,
+ )
+ return fut
+
+
+async def _acall_impl(
+ destination: asyncio.Future[Any] | concurrent.futures.Future[Any],
+ task: weakref.ref[PregelExecutableTask],
+ func: Callable[[Any], Awaitable[Any] | Any],
+ input: Any,
+ *,
+ retry_policy: Sequence[RetryPolicy] | None = None,
+ cache_policy: CachePolicy | None = None,
+ timeout: TimeoutPolicy | None = None,
+ callbacks: Callbacks = None,
+ # injected dependencies
+ futures: weakref.ref[FuturesDict[asyncio.Future, asyncio.Event]],
+ schedule_task: Callable[
+ [PregelExecutableTask, int, Call | None],
+ Awaitable[PregelExecutableTask | None],
+ ],
+ submit: weakref.ref[Submit],
+ loop: asyncio.AbstractEventLoop,
+ stream: bool = False,
+) -> None:
+ try:
+ fut: asyncio.Future | None = None
+ # schedule PUSH tasks, collect futures
+ scratchpad: PregelScratchpad = task().config[CONF][CONFIG_KEY_SCRATCHPAD] # type: ignore[union-attr]
+ # schedule the next task, if the callback returns one
+ if next_task := await schedule_task(
+ task(), # type: ignore[arg-type]
+ scratchpad.call_counter(),
+ Call(
+ func,
+ input,
+ retry_policy=retry_policy,
+ cache_policy=cache_policy,
+ callbacks=callbacks,
+ timeout=timeout,
+ ),
+ ):
+ if fut := next(
+ (
+ f
+ for f, t in list(futures().items()) # type: ignore[union-attr]
+ if t is not None and t == next_task.id
+ ),
+ None,
+ ):
+ # if the parent task was retried,
+ # the next task might already be running
+ pass
+ elif next_task.writes:
+ # if it already ran, return the result
+ fut = asyncio.Future(loop=loop)
+ ret = next((v for c, v in next_task.writes if c == RETURN), MISSING)
+ if ret is not MISSING:
+ fut.set_result(ret)
+ elif exc := next((v for c, v in next_task.writes if c == ERROR), None):
+ fut.set_exception(
+ exc if isinstance(exc, BaseException) else Exception(exc)
+ )
+ else:
+ fut.set_result(None)
+ else:
+ # schedule the next task
+ fut = cast(
+ asyncio.Future,
+ submit()( # type: ignore[misc]
+ arun_with_retry,
+ next_task,
+ retry_policy,
+ stream=stream,
+ configurable={
+ CONFIG_KEY_CALL: partial(
+ _acall,
+ weakref.ref(next_task),
+ stream=stream,
+ futures=futures,
+ schedule_task=schedule_task,
+ submit=submit,
+ loop=loop,
+ ),
+ },
+ __name__=next_task.name,
+ __cancel_on_exit__=True,
+ __reraise_on_exit__=False,
+ # starting a new task in the next tick ensures
+ # updates from this tick are committed/streamed first
+ __next_tick__=True,
+ ),
+ )
+ # exceptions for call() tasks are raised into the parent task
+ # so we should not re-raise at the end of the tick
+ SKIP_RERAISE_SET.add(fut)
+ futures()[fut] = next_task # type: ignore[index]
+ if fut is not None:
+ chain_future(fut, destination)
+ else:
+ destination.set_exception(RuntimeError("Task not scheduled"))
+ except Exception as exc:
+ destination.set_exception(exc)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_tools.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd7bb63bc0ce57c1100e33beabd751d10831f07e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_tools.py
@@ -0,0 +1,268 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Callable, Iterator
+from contextvars import ContextVar, Token
+from typing import Any, TypeVar, cast
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+
+from langgraph._internal._constants import NS_SEP
+from langgraph.constants import TAG_NOSTREAM
+from langgraph.pregel.protocol import StreamChunk
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = object # type: ignore[assignment,misc]
+
+
+T = TypeVar("T")
+
+ToolCallWriter = Callable[[Any], None]
+"""A closure bound to a single tool call that emits `tool-output-delta` events."""
+
+_tool_call_writer: ContextVar[ToolCallWriter | None] = ContextVar(
+ "langgraph_tool_call_writer", default=None
+)
+"""ContextVar holding the writer for the currently-executing tool call.
+
+Set by `StreamToolCallHandler.on_tool_start` and reset on end/error.
+Read by `ToolRuntime.emit_output_delta` (in `langgraph.prebuilt`).
+"""
+
+
+class StreamToolCallHandler(BaseCallbackHandler, _StreamingCallbackHandler):
+ """Callback handler that emits tool-call lifecycle events on the stream.
+
+ Fires on LangChain's `on_tool_*` callbacks and pushes to the `tools`
+ stream mode. Emits `tool-started` / `tool-output-delta` /
+ `tool-finished` / `tool-error` payloads keyed by `tool_call_id`.
+
+ While a tool is executing, this handler sets `_tool_call_writer` to a
+ closure bound to that call's namespace and `tool_call_id`.
+ `ToolRuntime.emit_output_delta` reads that ContextVar so tool bodies
+ can stream partial output without threading the writer through their
+ own signature.
+
+ Attached by `Pregel.stream` / `astream` when `"tools"` is in
+ `stream_modes`. `run_inline = True` keeps event ordering
+ deterministic.
+ """
+
+ run_inline = True
+
+ def __init__(
+ self,
+ stream: Callable[[StreamChunk], None],
+ subgraphs: bool,
+ *,
+ parent_ns: tuple[str, ...] | None = None,
+ ) -> None:
+ """Configure the handler to stream tool-call events.
+
+ Args:
+ stream: Callable that accepts a `StreamChunk` tuple
+ `(namespace, mode, payload)` and enqueues it.
+ subgraphs: Whether to emit events from tools called inside
+ nested subgraphs. When False, only tools at the
+ handler's own scope (`parent_ns`) emit.
+ parent_ns: Namespace where the handler was attached.
+ Mirrors the `StreamMessagesHandler` escape hatch:
+ tools whose containing namespace equals `parent_ns`
+ still emit even with `subgraphs=False`, so a node that
+ explicitly streams a subgraph with `stream_mode="tools"`
+ sees its own tools.
+ """
+ self.stream = stream
+ self.subgraphs = subgraphs
+ self.parent_ns = parent_ns
+ # run_id → (namespace, tool_call_id, ContextVar token)
+ # `on_tool_end` does not receive `tool_call_id` in kwargs, so
+ # we correlate by `run_id` which is present on every callback.
+ self._run_to_call: dict[
+ UUID, tuple[tuple[str, ...], str, Token[ToolCallWriter | None]]
+ ] = {}
+
+ def _ns_for_emit(
+ self,
+ metadata: dict[str, Any] | None,
+ tags: list[str] | None,
+ ) -> tuple[str, ...] | None:
+ """Resolve the namespace this tool call should emit at, or `None` to skip.
+
+ Mirrors `StreamMessagesHandler.on_chat_model_start`'s namespace
+ derivation: parses `langgraph_checkpoint_ns` (which ends with
+ the `node_name:task_id` of the calling node), drops that
+ trailing segment, and returns the containing subgraph's own
+ namespace. Returns `None` when the call should be silently
+ suppressed:
+
+ - `metadata` is missing — handler is attached to a context
+ without Pregel routing info.
+ - `TAG_NOSTREAM` is in `tags` — caller explicitly opted out.
+ - Tool runs in a subgraph (`len(ns) > 0`) and the handler was
+ attached with `subgraphs=False` and a different `parent_ns`
+ than the call's containing subgraph.
+ """
+ if not metadata:
+ return None
+ if tags and TAG_NOSTREAM in tags:
+ return None
+ nskey = metadata.get("langgraph_checkpoint_ns")
+ if not nskey:
+ ns: tuple[str, ...] = ()
+ else:
+ ns = tuple(cast(str, nskey).split(NS_SEP))[:-1]
+ if not self.subgraphs and len(ns) > 0 and ns != self.parent_ns:
+ return None
+ return ns
+
+ def _start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ *,
+ run_id: UUID,
+ metadata: dict[str, Any] | None,
+ tags: list[str] | None,
+ inputs: dict[str, Any] | None,
+ kwargs: dict[str, Any],
+ ) -> None:
+ ns = self._ns_for_emit(metadata, tags)
+ if ns is None:
+ return
+ tool_call_id = cast("str | None", kwargs.get("tool_call_id")) or str(run_id)
+ tool_name = (
+ (serialized or {}).get("name")
+ or cast("str | None", kwargs.get("name"))
+ or ""
+ )
+
+ def writer(delta: Any) -> None:
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-output-delta",
+ "tool_call_id": tool_call_id,
+ "delta": delta,
+ },
+ )
+ )
+
+ token = _tool_call_writer.set(writer)
+ self._run_to_call[run_id] = (ns, tool_call_id, token)
+
+ payload: dict[str, Any] = {
+ "event": "tool-started",
+ "tool_call_id": tool_call_id,
+ "tool_name": tool_name,
+ }
+ if inputs is not None:
+ payload["input"] = inputs
+ self.stream((ns, "tools", payload))
+
+ def _end(self, output: Any, *, run_id: UUID) -> None:
+ info = self._run_to_call.pop(run_id, None)
+ if info is None:
+ return
+ ns, tool_call_id, token = info
+ self._reset_writer(token)
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-finished",
+ "tool_call_id": tool_call_id,
+ "output": output,
+ },
+ )
+ )
+
+ def _error(self, error: BaseException, *, run_id: UUID) -> None:
+ info = self._run_to_call.pop(run_id, None)
+ if info is None:
+ return
+ ns, tool_call_id, token = info
+ self._reset_writer(token)
+ self.stream(
+ (
+ ns,
+ "tools",
+ {
+ "event": "tool-error",
+ "tool_call_id": tool_call_id,
+ "message": str(error),
+ },
+ )
+ )
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Pass-through — required by the `_StreamingCallbackHandler` protocol."""
+ return output
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Pass-through — sync counterpart to `tap_output_aiter`."""
+ return output
+
+ @staticmethod
+ def _reset_writer(token: Token[ToolCallWriter | None]) -> None:
+ # Token is invalid if `on_tool_end` runs in a different context
+ # than `on_tool_start` (e.g. langchain may hand off to a thread
+ # worker without copying the context). Swallow that case; the
+ # ContextVar lifetime is bounded by the enclosing task anyway.
+ try:
+ _tool_call_writer.reset(token)
+ except ValueError:
+ pass
+
+ # ------------------------------------------------------------------
+ # Sync callbacks
+ # ------------------------------------------------------------------
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._start(
+ serialized,
+ input_str,
+ run_id=run_id,
+ metadata=metadata,
+ tags=tags,
+ inputs=inputs,
+ kwargs=kwargs,
+ )
+
+ def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._end(output, run_id=run_id)
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ self._error(error, run_id=run_id)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_utils.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f91e08b61cd38b61de518928ca5f89b3c5f35d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_utils.py
@@ -0,0 +1,291 @@
+from __future__ import annotations
+
+import ast
+import inspect
+import re
+import textwrap
+from collections.abc import Callable, Sequence
+from functools import partial
+from typing import Any
+
+from langchain_core.runnables import (
+ Runnable,
+ RunnableLambda,
+ RunnableParallel,
+ RunnableSequence,
+)
+from langchain_core.runnables.base import RunnableBindingBase
+from langchain_core.runnables.config import run_in_executor
+from langgraph.checkpoint.base import ChannelVersions
+from typing_extensions import override
+
+from langgraph._internal._runnable import RunnableCallable, RunnableSeq
+from langgraph._internal._timeout import sync_timeout_unsupported
+from langgraph.pregel.protocol import PregelProtocol
+
+_SEQUENCE_TYPES = (RunnableSeq, RunnableSequence)
+
+
+def get_new_channel_versions(
+ previous_versions: ChannelVersions, current_versions: ChannelVersions
+) -> ChannelVersions:
+ """Get subset of current_versions that are newer than previous_versions."""
+ if previous_versions:
+ version_type = type(next(iter(current_versions.values()), None))
+ null_version = version_type() # type: ignore[misc]
+ new_versions = {
+ k: v
+ for k, v in current_versions.items()
+ if v > previous_versions.get(k, null_version) # type: ignore[operator]
+ }
+ else:
+ new_versions = current_versions
+
+ return new_versions
+
+
+def find_subgraph_pregel(candidate: Runnable) -> PregelProtocol | None:
+ from langgraph.pregel import Pregel
+
+ candidates: list[Runnable] = [candidate]
+
+ for c in candidates:
+ if (
+ isinstance(c, PregelProtocol)
+ # subgraphs that disabled checkpointing are not considered
+ and (not isinstance(c, Pregel) or c.checkpointer is not False)
+ ):
+ return c
+ elif isinstance(c, RunnableSequence) or isinstance(c, RunnableSeq):
+ candidates.extend(c.steps)
+ elif isinstance(c, RunnableLambda):
+ candidates.extend(c.deps)
+ elif isinstance(c, RunnableCallable):
+ if c.func is not None:
+ candidates.extend(
+ nl.__self__ if hasattr(nl, "__self__") else nl
+ for nl in get_function_nonlocals(c.func)
+ )
+ elif c.afunc is not None:
+ candidates.extend(
+ nl.__self__ if hasattr(nl, "__self__") else nl
+ for nl in get_function_nonlocals(c.afunc)
+ )
+
+ return None
+
+
+def _sequence_steps(runnable: Runnable) -> Sequence[Runnable] | None:
+ if isinstance(runnable, _SEQUENCE_TYPES):
+ return runnable.steps
+ return None
+
+
+def _parallel_steps(runnable: Runnable) -> Sequence[Runnable] | None:
+ if isinstance(runnable, RunnableParallel):
+ return tuple(runnable.steps__.values())
+ return None
+
+
+def _has_method_override(runnable: Runnable, method_name: str) -> bool:
+ method = getattr(type(runnable), method_name, None)
+ return method is not None and method is not getattr(Runnable, method_name)
+
+
+def _is_executor_backed_afunc(afunc: Callable[..., Any] | None) -> bool:
+ return isinstance(afunc, partial) and afunc.func is run_in_executor
+
+
+def _has_native_async(runnable: Runnable) -> bool:
+ if isinstance(runnable, RunnableCallable):
+ return runnable.afunc is not None and not _is_executor_backed_afunc(
+ runnable.afunc
+ )
+ if isinstance(runnable, RunnableLambda):
+ return bool(getattr(runnable, "afunc", False))
+ return _has_method_override(runnable, "ainvoke")
+
+
+def _runnable_has_native_async(runnable: Runnable) -> bool:
+ """Return whether a runnable can be idle-timed without known sync code.
+
+ For custom runnable subclasses, an `ainvoke` override is treated as the
+ async contract. We do not introspect whether that implementation delegates
+ to blocking work internally — e.g. a subclass whose `ainvoke` calls
+ `asyncio.to_thread(self.invoke, ...)` will pass this check but the wrapped
+ sync work is still uncancellable. Idle-timeout enforcement on such a
+ runnable will fire `NodeTimeoutError` correctly, but the background thread
+ will keep running until its sync work returns.
+ """
+
+ while isinstance(runnable, RunnableBindingBase):
+ runnable = runnable.bound
+ steps = _sequence_steps(runnable)
+ if steps is None:
+ steps = _parallel_steps(runnable)
+ if steps is not None:
+ return all(_runnable_has_native_async(step) for step in steps)
+ # Raw callables and the common composition wrappers created by graph
+ # builders fall through here. We do not exhaustively unwrap every Runnable
+ # wrapper — wrappers that provide `ainvoke` are treated as owning the async
+ # contract.
+ return _has_native_async(runnable)
+
+
+def validate_timeout_supported(runnable: Runnable, *, name: str) -> None:
+ if not _runnable_has_native_async(runnable):
+ raise sync_timeout_unsupported(name)
+
+
+def get_function_nonlocals(func: Callable) -> list[Any]:
+ """Get the nonlocal variables accessed by a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ List[Any]: The nonlocal variables accessed by the function.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = FunctionNonLocals()
+ visitor.visit(tree)
+ values: list[Any] = []
+ closure = (
+ inspect.getclosurevars(func.__wrapped__)
+ if hasattr(func, "__wrapped__") and callable(func.__wrapped__)
+ else inspect.getclosurevars(func)
+ )
+ candidates = {**closure.globals, **closure.nonlocals}
+ for k, v in candidates.items():
+ if k in visitor.nonlocals:
+ values.append(v)
+ for kk in visitor.nonlocals:
+ if "." in kk and kk.startswith(k):
+ vv = v
+ for part in kk.split(".")[1:]:
+ if vv is None:
+ break
+ else:
+ try:
+ vv = getattr(vv, part)
+ except AttributeError:
+ break
+ else:
+ values.append(vv)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return []
+
+ return values
+
+
+class FunctionNonLocals(ast.NodeVisitor):
+ """Get the nonlocal variables accessed of a function."""
+
+ def __init__(self) -> None:
+ self.nonlocals: set[str] = set()
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> Any:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+
+class NonLocals(ast.NodeVisitor):
+ """Get nonlocal variables accessed."""
+
+ def __init__(self) -> None:
+ self.loads: set[str] = set()
+ self.stores: set[str] = set()
+
+ @override
+ def visit_Name(self, node: ast.Name) -> Any:
+ """Visit a name node.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ self.loads.add(node.id)
+ elif isinstance(node.ctx, ast.Store):
+ self.stores.add(node.id)
+
+ @override
+ def visit_Attribute(self, node: ast.Attribute) -> Any:
+ """Visit an attribute node.
+
+ Args:
+ node: The node to visit.
+
+ Returns:
+ Any: The result of the visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ parent = node.value
+ attr_expr = node.attr
+ while isinstance(parent, ast.Attribute):
+ attr_expr = parent.attr + "." + attr_expr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+ self.loads.discard(parent.id)
+ elif isinstance(parent, ast.Call):
+ if isinstance(parent.func, ast.Name):
+ self.loads.add(parent.func.id)
+ else:
+ parent = parent.func
+ attr_expr = ""
+ while isinstance(parent, ast.Attribute):
+ if attr_expr:
+ attr_expr = parent.attr + "." + attr_expr
+ else:
+ attr_expr = parent.attr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+
+
+def is_xxh3_128_hexdigest(value: str) -> bool:
+ """Check if the given string matches the format of xxh3_128_hexdigest."""
+ return bool(re.fullmatch(r"[0-9a-f]{32}", value))
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_validate.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcfb54c9a1241699490dcb562020bc9ee83c50d8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_validate.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from langgraph._internal._constants import RESERVED
+from langgraph.channels.base import BaseChannel
+from langgraph.managed.base import ManagedValueMapping
+from langgraph.pregel._read import PregelNode
+from langgraph.types import All
+
+
+def validate_graph(
+ nodes: Mapping[str, PregelNode],
+ channels: dict[str, BaseChannel],
+ managed: ManagedValueMapping,
+ input_channels: str | Sequence[str],
+ output_channels: str | Sequence[str],
+ stream_channels: str | Sequence[str] | None,
+ interrupt_after_nodes: All | Sequence[str],
+ interrupt_before_nodes: All | Sequence[str],
+) -> None:
+ for chan in channels:
+ if chan in RESERVED:
+ raise ValueError(f"Channel name '{chan}' is reserved")
+ for name in managed:
+ if name in RESERVED:
+ raise ValueError(f"Managed name '{name}' is reserved")
+
+ subscribed_channels = set[str]()
+ for name, node in nodes.items():
+ if name in RESERVED:
+ raise ValueError(f"Node name '{name}' is reserved")
+ if isinstance(node, PregelNode):
+ subscribed_channels.update(node.triggers)
+ if isinstance(node.channels, str):
+ if node.channels not in channels:
+ raise ValueError(
+ f"Node {name} reads channel '{node.channels}' "
+ f"not in known channels: '{repr(sorted(channels))[:100]}'"
+ )
+ else:
+ for chan in node.channels:
+ if chan not in channels and chan not in managed:
+ raise ValueError(
+ f"Node {name} reads channel '{chan}' "
+ f"not in known channels: '{repr(sorted(channels))[:100]}'"
+ )
+ else:
+ raise TypeError(
+ f"Invalid node type {type(node)}, expected PregelNode or NodeBuilder"
+ )
+
+ for chan in subscribed_channels:
+ if chan not in channels:
+ raise ValueError(
+ f"Subscribed channel '{chan}' not "
+ f"in known channels: '{repr(sorted(channels))[:100]}'"
+ )
+
+ if isinstance(input_channels, str):
+ if input_channels not in channels:
+ raise ValueError(
+ f"Input channel '{input_channels}' not "
+ f"in known channels: '{repr(sorted(channels))[:100]}'"
+ )
+ if input_channels not in subscribed_channels:
+ raise ValueError(
+ f"Input channel {input_channels} is not subscribed to by any node"
+ )
+ else:
+ for chan in input_channels:
+ if chan not in channels:
+ raise ValueError(
+ f"Input channel '{chan}' not in '{repr(sorted(channels))[:100]}'"
+ )
+ if all(chan not in subscribed_channels for chan in input_channels):
+ raise ValueError(
+ f"None of the input channels {input_channels} "
+ f"are subscribed to by any node"
+ )
+
+ all_output_channels = set[str]()
+ if isinstance(output_channels, str):
+ all_output_channels.add(output_channels)
+ else:
+ all_output_channels.update(output_channels)
+ if isinstance(stream_channels, str):
+ all_output_channels.add(stream_channels)
+ elif stream_channels is not None:
+ all_output_channels.update(stream_channels)
+
+ for chan in all_output_channels:
+ if chan not in channels:
+ raise ValueError(
+ f"Output channel '{chan}' not "
+ f"in known channels: '{repr(sorted(channels))[:100]}'"
+ )
+
+ if interrupt_after_nodes != "*":
+ for n in interrupt_after_nodes:
+ if n not in nodes:
+ raise ValueError(f"Node {n} not in nodes")
+ if interrupt_before_nodes != "*":
+ for n in interrupt_before_nodes:
+ if n not in nodes:
+ raise ValueError(f"Node {n} not in nodes")
+
+
+def validate_keys(
+ keys: str | Sequence[str] | None,
+ channels: Mapping[str, Any],
+) -> None:
+ if isinstance(keys, str):
+ if keys not in channels:
+ raise ValueError(f"Key {keys} not in channels")
+ elif keys is not None:
+ for chan in keys:
+ if chan not in channels:
+ raise ValueError(f"Key {chan} not in channels")
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/_write.py b/python/user_packages/Python313/site-packages/langgraph/pregel/_write.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b4508257653e54c94cb2360bd32de91bb161bfd
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/_write.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+from collections.abc import Callable, Sequence
+from typing import (
+ Any,
+ NamedTuple,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.runnables import Runnable, RunnableConfig
+
+from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, TASKS
+from langgraph._internal._runnable import RunnableCallable
+from langgraph._internal._typing import MISSING
+from langgraph.errors import InvalidUpdateError
+from langgraph.types import Send
+
+TYPE_SEND = Callable[[Sequence[tuple[str, Any]]], None]
+R = TypeVar("R", bound=Runnable)
+
+SKIP_WRITE = object()
+PASSTHROUGH = object()
+
+
+class ChannelWriteEntry(NamedTuple):
+ channel: str
+ """Channel name to write to."""
+ value: Any = PASSTHROUGH
+ """Value to write, or PASSTHROUGH to use the input."""
+ skip_none: bool = False
+ """Whether to skip writing if the value is None."""
+ mapper: Callable | None = None
+ """Function to transform the value before writing."""
+
+
+class ChannelWriteTupleEntry(NamedTuple):
+ mapper: Callable[[Any], Sequence[tuple[str, Any]] | None]
+ """Function to extract tuples from value."""
+ value: Any = PASSTHROUGH
+ """Value to write, or PASSTHROUGH to use the input."""
+ static: Sequence[tuple[str, Any, str | None]] | None = None
+ """Optional, declared writes for static analysis."""
+
+
+class ChannelWrite(RunnableCallable):
+ """Implements the logic for sending writes to CONFIG_KEY_SEND.
+ Can be used as a runnable or as a static method to call imperatively."""
+
+ writes: list[ChannelWriteEntry | ChannelWriteTupleEntry | Send]
+ """Sequence of write entries or Send objects to write."""
+
+ def __init__(
+ self,
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+ *,
+ tags: Sequence[str] | None = None,
+ ):
+ super().__init__(
+ func=self._write,
+ afunc=self._awrite,
+ name=None,
+ tags=tags,
+ trace=False,
+ )
+ self.writes = cast(
+ list[ChannelWriteEntry | ChannelWriteTupleEntry | Send], writes
+ )
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ if not name:
+ name = f"ChannelWrite<{','.join(w.channel if isinstance(w, ChannelWriteEntry) else '...' if isinstance(w, ChannelWriteTupleEntry) else w.node for w in self.writes)}>"
+ return super().get_name(suffix, name=name)
+
+ def _write(self, input: Any, config: RunnableConfig) -> None:
+ writes = [
+ ChannelWriteEntry(write.channel, input, write.skip_none, write.mapper)
+ if isinstance(write, ChannelWriteEntry) and write.value is PASSTHROUGH
+ else ChannelWriteTupleEntry(write.mapper, input)
+ if isinstance(write, ChannelWriteTupleEntry) and write.value is PASSTHROUGH
+ else write
+ for write in self.writes
+ ]
+ self.do_write(
+ config,
+ writes,
+ )
+ return input
+
+ async def _awrite(self, input: Any, config: RunnableConfig) -> None:
+ writes = [
+ ChannelWriteEntry(write.channel, input, write.skip_none, write.mapper)
+ if isinstance(write, ChannelWriteEntry) and write.value is PASSTHROUGH
+ else ChannelWriteTupleEntry(write.mapper, input)
+ if isinstance(write, ChannelWriteTupleEntry) and write.value is PASSTHROUGH
+ else write
+ for write in self.writes
+ ]
+ self.do_write(
+ config,
+ writes,
+ )
+ return input
+
+ @staticmethod
+ def do_write(
+ config: RunnableConfig,
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+ allow_passthrough: bool = True,
+ ) -> None:
+ # validate
+ for w in writes:
+ if isinstance(w, ChannelWriteEntry):
+ if w.channel == TASKS:
+ raise InvalidUpdateError(
+ "Cannot write to the reserved channel TASKS"
+ )
+ if w.value is PASSTHROUGH and not allow_passthrough:
+ raise InvalidUpdateError("PASSTHROUGH value must be replaced")
+ if isinstance(w, ChannelWriteTupleEntry):
+ if w.value is PASSTHROUGH and not allow_passthrough:
+ raise InvalidUpdateError("PASSTHROUGH value must be replaced")
+ # if we want to persist writes found before hitting a ParentCommand
+ # can move this to a finally block
+ write: TYPE_SEND = config[CONF][CONFIG_KEY_SEND]
+ write(_assemble_writes(writes))
+
+ @staticmethod
+ def is_writer(runnable: Runnable) -> bool:
+ """Used by PregelNode to distinguish between writers and other runnables."""
+ return (
+ isinstance(runnable, ChannelWrite)
+ or getattr(runnable, "_is_channel_writer", MISSING) is not MISSING
+ )
+
+ @staticmethod
+ def get_static_writes(
+ runnable: Runnable,
+ ) -> Sequence[tuple[str, Any, str | None]] | None:
+ """Used to get conditional writes a writer declares for static analysis."""
+ if isinstance(runnable, ChannelWrite):
+ return [
+ w
+ for entry in runnable.writes
+ if isinstance(entry, ChannelWriteTupleEntry) and entry.static
+ for w in entry.static
+ ] or None
+ elif writes := getattr(runnable, "_is_channel_writer", MISSING):
+ if writes is not MISSING:
+ writes = cast(
+ Sequence[tuple[ChannelWriteEntry | Send, str | None]],
+ writes,
+ )
+ entries = [e for e, _ in writes]
+ labels = [la for _, la in writes]
+ return [(*t, la) for t, la in zip(_assemble_writes(entries), labels)]
+
+ @staticmethod
+ def register_writer(
+ runnable: R,
+ static: Sequence[tuple[ChannelWriteEntry | Send, str | None]] | None = None,
+ ) -> R:
+ """Used to mark a runnable as a writer, so that it can be detected by is_writer.
+ Instances of ChannelWrite are automatically marked as writers.
+ Optionally, a list of declared writes can be passed for static analysis."""
+ # using object.__setattr__ to work around objects that override __setattr__
+ # eg. pydantic models and dataclasses
+ object.__setattr__(runnable, "_is_channel_writer", static)
+ return runnable
+
+
+def _assemble_writes(
+ writes: Sequence[ChannelWriteEntry | ChannelWriteTupleEntry | Send],
+) -> list[tuple[str, Any]]:
+ """Assembles the writes into a list of tuples."""
+ tuples: list[tuple[str, Any]] = []
+ for w in writes:
+ if isinstance(w, Send):
+ tuples.append((TASKS, w))
+ elif isinstance(w, ChannelWriteTupleEntry):
+ if ww := w.mapper(w.value):
+ tuples.extend(ww)
+ elif isinstance(w, ChannelWriteEntry):
+ value = w.mapper(w.value) if w.mapper is not None else w.value
+ if value is SKIP_WRITE:
+ continue
+ if w.skip_none and value is None:
+ continue
+ tuples.append((w.channel, value))
+ else:
+ raise ValueError(f"Invalid write entry: {w}")
+ return tuples
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/debug.py b/python/user_packages/Python313/site-packages/langgraph/pregel/debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..519a36488f8c4918efcf3cd3e032e957e23954c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/debug.py
@@ -0,0 +1,279 @@
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator, Mapping, Sequence
+from dataclasses import asdict
+from typing import Any
+from uuid import UUID
+
+from langchain_core.runnables import RunnableConfig
+from langgraph.checkpoint.base import CheckpointMetadata, PendingWrite
+
+from langgraph._internal._config import patch_checkpoint_map
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_NS,
+ ERROR,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ RETURN,
+)
+from langgraph._internal._typing import MISSING
+from langgraph.channels.base import BaseChannel
+from langgraph.constants import TAG_HIDDEN
+from langgraph.pregel._io import read_channels
+from langgraph.types import (
+ CheckpointPayload,
+ PregelExecutableTask,
+ PregelTask,
+ StateSnapshot,
+ TaskPayload,
+ TaskResultPayload,
+)
+
+TASK_NAMESPACE = UUID("6ba7b831-9dad-11d1-80b4-00c04fd430c8")
+
+
+def map_debug_tasks(tasks: Iterable[PregelExecutableTask]) -> Iterator[TaskPayload]:
+ """Produce "task" events for stream_mode=debug."""
+ for task in tasks:
+ if task.config is not None and TAG_HIDDEN in task.config.get("tags", []):
+ continue
+
+ yield {
+ "id": task.id,
+ "name": task.name,
+ "input": task.input,
+ "triggers": task.triggers,
+ }
+
+
+def is_multiple_channel_write(value: Any) -> bool:
+ """Return True if the payload already wraps multiple writes from the same channel."""
+ return (
+ isinstance(value, dict)
+ and "$writes" in value
+ and isinstance(value["$writes"], list)
+ )
+
+
+def map_task_result_writes(writes: Sequence[tuple[str, Any]]) -> dict[str, Any]:
+ """Folds task writes into a result dict and aggregates multiple writes to the same channel.
+
+ If the channel contains a single write, we record the write in the result dict as `{channel: write}`
+ If the channel contains multiple writes, we record the writes in the result dict as `{channel: {'$writes': [write1, write2, ...]}}`"""
+
+ result: dict[str, Any] = {}
+ for channel, value in writes:
+ existing = result.get(channel)
+
+ if existing is not None:
+ channel_writes = (
+ existing["$writes"]
+ if is_multiple_channel_write(existing)
+ else [existing]
+ )
+ channel_writes.append(value)
+ result[channel] = {"$writes": channel_writes}
+ else:
+ result[channel] = value
+ return result
+
+
+def map_debug_task_results(
+ task_tup: tuple[PregelExecutableTask, Sequence[tuple[str, Any]]],
+ stream_keys: str | Sequence[str],
+) -> Iterator[TaskResultPayload]:
+ """Produce "task_result" events for stream_mode=debug."""
+ stream_channels_list = (
+ [stream_keys] if isinstance(stream_keys, str) else stream_keys
+ )
+ task, writes = task_tup
+ yield {
+ "id": task.id,
+ "name": task.name,
+ "error": next((w[1] for w in writes if w[0] == ERROR), None),
+ "result": map_task_result_writes(
+ [w for w in writes if w[0] in stream_channels_list or w[0] == RETURN]
+ ),
+ "interrupts": [
+ asdict(v)
+ for w in writes
+ if w[0] == INTERRUPT
+ for v in (w[1] if isinstance(w[1], Sequence) else [w[1]])
+ ],
+ }
+
+
+def rm_pregel_keys(config: RunnableConfig | None) -> RunnableConfig | None:
+ """Remove pregel-specific keys from the config."""
+ if config is None:
+ return config
+ return {
+ "configurable": {
+ k: v
+ for k, v in config.get("configurable", {}).items()
+ if not k.startswith("__pregel_")
+ }
+ }
+
+
+def map_debug_checkpoint(
+ config: RunnableConfig,
+ channels: Mapping[str, BaseChannel],
+ stream_channels: str | Sequence[str],
+ metadata: CheckpointMetadata,
+ tasks: Iterable[PregelExecutableTask],
+ pending_writes: list[PendingWrite],
+ parent_config: RunnableConfig | None,
+ output_keys: str | Sequence[str],
+) -> Iterator[CheckpointPayload]:
+ """Produce "checkpoint" events for stream_mode=debug."""
+
+ parent_ns = config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+
+ for task in tasks:
+ if not task.subgraphs:
+ continue
+
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+
+ # set config as signal that subgraph checkpoints exist
+ task_states[task.id] = {
+ CONF: {
+ "thread_id": config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+
+ yield {
+ "config": rm_pregel_keys(patch_checkpoint_map(config, metadata)),
+ "parent_config": rm_pregel_keys(patch_checkpoint_map(parent_config, metadata)),
+ "values": read_channels(channels, stream_channels),
+ "metadata": metadata,
+ "next": [t.name for t in tasks],
+ "tasks": [
+ {
+ "id": t.id,
+ "name": t.name,
+ "error": t.error,
+ "state": t.state,
+ }
+ if t.error
+ else {
+ "id": t.id,
+ "name": t.name,
+ "result": t.result,
+ "interrupts": tuple(asdict(i) for i in t.interrupts),
+ "state": t.state,
+ }
+ if t.result
+ else {
+ "id": t.id,
+ "name": t.name,
+ "interrupts": tuple(asdict(i) for i in t.interrupts),
+ "state": t.state,
+ }
+ for t in tasks_w_writes(tasks, pending_writes, task_states, output_keys)
+ ],
+ }
+
+
+def tasks_w_writes(
+ tasks: Iterable[PregelTask | PregelExecutableTask],
+ pending_writes: list[PendingWrite] | None,
+ states: dict[str, RunnableConfig | StateSnapshot] | None,
+ output_keys: str | Sequence[str],
+) -> tuple[PregelTask, ...]:
+ """Apply writes / subgraph states to tasks to be returned in a StateSnapshot."""
+ pending_writes = pending_writes or []
+ out: list[PregelTask] = []
+ for task in tasks:
+ rtn = next(
+ (
+ val
+ for tid, chan, val in pending_writes
+ if tid == task.id and chan == RETURN
+ ),
+ MISSING,
+ )
+ task_error = next(
+ (exc for tid, n, exc in pending_writes if tid == task.id and n == ERROR),
+ None,
+ )
+ task_interrupts = tuple(
+ v
+ for tid, n, vv in pending_writes
+ if tid == task.id and n == INTERRUPT
+ for v in (vv if isinstance(vv, Sequence) else [vv])
+ )
+
+ task_writes = [
+ (chan, val)
+ for tid, chan, val in pending_writes
+ if tid == task.id and chan not in (ERROR, INTERRUPT, RETURN)
+ ]
+
+ if rtn is not MISSING:
+ task_result = rtn
+ elif isinstance(output_keys, str):
+ # unwrap single channel writes to just the write value
+ filtered_writes = [
+ (chan, val) for chan, val in task_writes if chan == output_keys
+ ]
+ mapped_writes = map_task_result_writes(filtered_writes)
+ task_result = mapped_writes.get(str(output_keys)) if mapped_writes else None
+ else:
+ if isinstance(output_keys, str):
+ output_keys = [output_keys]
+ # map task result writes to the desired output channels
+ # repeateed writes to the same channel are aggregated into: {'$writes': [write1, write2, ...]}
+ filtered_writes = [
+ (chan, val) for chan, val in task_writes if chan in output_keys
+ ]
+ mapped_writes = map_task_result_writes(filtered_writes)
+ task_result = mapped_writes if filtered_writes else {}
+
+ has_writes = rtn is not MISSING or any(
+ w[0] == task.id and w[1] not in (ERROR, INTERRUPT) for w in pending_writes
+ )
+
+ out.append(
+ PregelTask(
+ task.id,
+ task.name,
+ task.path,
+ task_error,
+ task_interrupts,
+ states.get(task.id) if states else None,
+ task_result if has_writes else None,
+ )
+ )
+ return tuple(out)
+
+
+COLOR_MAPPING = {
+ "black": "0;30",
+ "red": "0;31",
+ "green": "0;32",
+ "yellow": "0;33",
+ "blue": "0;34",
+ "magenta": "0;35",
+ "cyan": "0;36",
+ "white": "0;37",
+ "gray": "1;30",
+}
+
+
+def get_colored_text(text: str, color: str) -> str:
+ """Get colored text."""
+ return f"\033[1;3{COLOR_MAPPING[color]}m{text}\033[0m"
+
+
+def get_bolded_text(text: str) -> str:
+ """Get bolded text."""
+ return f"\033[1m{text}\033[0m"
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/main.py b/python/user_packages/Python313/site-packages/langgraph/pregel/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1550e5a92390bd70cdff256f6c482020940548ed
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/main.py
@@ -0,0 +1,4314 @@
+from __future__ import annotations
+
+import asyncio
+import concurrent
+import concurrent.futures
+import contextlib
+import queue
+import warnings
+import weakref
+from collections import defaultdict, deque
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from dataclasses import is_dataclass, replace
+from datetime import timedelta
+from functools import partial
+from inspect import isclass
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ cast,
+ get_type_hints,
+ overload,
+)
+from uuid import UUID, uuid5
+
+from langchain_core._api import beta
+from langchain_core.globals import get_debug
+from langchain_core.runnables import (
+ RunnableSequence,
+)
+from langchain_core.runnables.base import Input, Output
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+)
+from langchain_core.runnables.graph import Graph
+from langchain_core.runnables.schema import StreamEvent
+from langgraph.cache.base import BaseCache
+from langgraph.checkpoint.base import (
+ BaseCheckpointSaver,
+ Checkpoint,
+ CheckpointTuple,
+)
+from langgraph.store.base import BaseStore
+from pydantic import BaseModel, TypeAdapter
+from typing_extensions import Self, Unpack, deprecated, is_typeddict
+
+from langgraph._internal import _serde
+from langgraph._internal._config import (
+ ensure_config,
+ merge_configs,
+ patch_checkpoint_map,
+ patch_config,
+ patch_configurable,
+ recast_checkpoint_ns,
+)
+from langgraph._internal._constants import (
+ CACHE_NS_WRITES,
+ CONF,
+ CONFIG_KEY_CACHE,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_CHECKPOINTER,
+ CONFIG_KEY_DURABILITY,
+ CONFIG_KEY_NODE_FINISHED,
+ CONFIG_KEY_READ,
+ CONFIG_KEY_RUNNER_SUBMIT,
+ CONFIG_KEY_RUNTIME,
+ CONFIG_KEY_SEND,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_STREAM_MESSAGES_V2,
+ CONFIG_KEY_TASK_ID,
+ CONFIG_KEY_THREAD_ID,
+ ERROR,
+ INPUT,
+ INTERRUPT,
+ NS_END,
+ NS_SEP,
+ NULL_TASK_ID,
+ PUSH,
+ TASKS,
+)
+from langgraph._internal._pydantic import create_model
+from langgraph._internal._queue import ( # type: ignore[attr-defined]
+ AsyncQueue,
+ SyncQueue,
+)
+from langgraph._internal._runnable import (
+ Runnable,
+ RunnableLike,
+ RunnableSeq,
+ coerce_to_runnable,
+)
+from langgraph._internal._timeout import coerce_timeout_policy
+from langgraph._internal._typing import MISSING, DeprecatedKwargs
+from langgraph.callbacks import (
+ GraphInterruptEvent,
+ GraphResumeEvent,
+ get_async_graph_callback_manager_for_config,
+ get_sync_graph_callback_manager_for_config,
+)
+from langgraph.channels.base import BaseChannel
+from langgraph.channels.topic import Topic
+from langgraph.config import get_config
+from langgraph.constants import END
+from langgraph.errors import (
+ ErrorCode,
+ GraphDrained,
+ GraphRecursionError,
+ InvalidUpdateError,
+ create_error_message,
+)
+from langgraph.managed.base import ManagedValueSpec
+from langgraph.pregel._algo import (
+ PregelTaskWrites,
+ _scratchpad,
+ apply_writes,
+ local_read,
+ prepare_next_tasks,
+)
+from langgraph.pregel._call import identifier
+from langgraph.pregel._checkpoint import (
+ achannels_from_checkpoint,
+ channels_from_checkpoint,
+ copy_checkpoint,
+ create_checkpoint,
+ empty_checkpoint,
+)
+from langgraph.pregel._draw import draw_graph
+from langgraph.pregel._io import map_input, read_channels
+from langgraph.pregel._loop import (
+ AsyncPregelLoop,
+ SyncPregelLoop,
+)
+from langgraph.pregel._messages import (
+ StreamMessagesHandler,
+ StreamMessagesHandlerV2,
+)
+from langgraph.pregel._read import DEFAULT_BOUND, PregelNode
+from langgraph.pregel._retry import RetryPolicy
+from langgraph.pregel._runner import PregelRunner
+from langgraph.pregel._tools import StreamToolCallHandler
+from langgraph.pregel._utils import (
+ get_new_channel_versions,
+ validate_timeout_supported,
+)
+from langgraph.pregel._validate import validate_graph, validate_keys
+from langgraph.pregel._write import ChannelWrite, ChannelWriteEntry
+from langgraph.pregel.debug import get_bolded_text, get_colored_text, tasks_w_writes
+from langgraph.pregel.protocol import PregelProtocol, StreamChunk, StreamProtocol
+from langgraph.runtime import (
+ DEFAULT_RUNTIME,
+ BaseUser,
+ RunControl,
+ Runtime,
+ ServerInfo,
+)
+from langgraph.stream._mux import StreamMux
+from langgraph.stream._types import StreamTransformer
+from langgraph.stream.run_stream import AsyncGraphRunStream, GraphRunStream
+from langgraph.stream.transformers import (
+ LifecycleTransformer,
+ MessagesTransformer,
+ SubgraphTransformer,
+ ValuesTransformer,
+)
+from langgraph.types import (
+ All,
+ CachePolicy,
+ Checkpointer,
+ Command,
+ Durability,
+ GraphOutput,
+ Interrupt,
+ Send,
+ StateSnapshot,
+ StateUpdate,
+ StreamMode,
+ StreamPart,
+ TimeoutPolicy,
+ ensure_valid_checkpointer,
+)
+from langgraph.typing import ContextT, InputT, OutputT, StateT
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+
+try:
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
+except ImportError:
+ _StreamingCallbackHandler = None # type: ignore
+
+__all__ = ("NodeBuilder", "Pregel")
+
+_WriteValue = Callable[[Input], Output] | Any
+
+
+class NodeBuilder:
+ __slots__ = (
+ "_channels",
+ "_triggers",
+ "_tags",
+ "_metadata",
+ "_writes",
+ "_bound",
+ "_retry_policy",
+ "_cache_policy",
+ "_timeout",
+ )
+
+ _channels: str | list[str]
+ _triggers: list[str]
+ _tags: list[str]
+ _metadata: dict[str, Any]
+ _writes: list[ChannelWriteEntry]
+ _bound: Runnable
+ _retry_policy: list[RetryPolicy]
+ _cache_policy: CachePolicy | None
+ _timeout: TimeoutPolicy | None
+
+ def __init__(
+ self,
+ ) -> None:
+ self._channels = []
+ self._triggers = []
+ self._tags = []
+ self._metadata = {}
+ self._writes = []
+ self._bound = DEFAULT_BOUND
+ self._retry_policy = []
+ self._cache_policy = None
+ self._timeout = None
+
+ def subscribe_only(
+ self,
+ channel: str,
+ ) -> Self:
+ """Subscribe to a single channel."""
+ if not self._channels:
+ self._channels = channel
+ else:
+ raise ValueError(
+ "Cannot subscribe to single channels when other channels are already subscribed to"
+ )
+
+ self._triggers.append(channel)
+
+ return self
+
+ def subscribe_to(
+ self,
+ *channels: str,
+ read: bool = True,
+ ) -> Self:
+ """Add channels to subscribe to.
+
+ Node will be invoked when any of these channels are updated, with a dict of the
+ channel values as input.
+
+ Args:
+ channels: Channel name(s) to subscribe to
+ read: If `True`, the channels will be included in the input to the node.
+ Otherwise, they will trigger the node without being sent in input.
+
+ Returns:
+ Self for chaining
+ """
+ if isinstance(self._channels, str):
+ raise ValueError(
+ "Cannot subscribe to channels when subscribed to a single channel"
+ )
+ if read:
+ if not self._channels:
+ self._channels = list(channels)
+ else:
+ self._channels.extend(channels)
+
+ if isinstance(channels, str):
+ self._triggers.append(channels)
+ else:
+ self._triggers.extend(channels)
+
+ return self
+
+ def read_from(
+ self,
+ *channels: str,
+ ) -> Self:
+ """Adds the specified channels to read from, without subscribing to them."""
+ assert isinstance(self._channels, list), (
+ "Cannot read additional channels when subscribed to single channels"
+ )
+ self._channels.extend(channels)
+ return self
+
+ def do(
+ self,
+ node: RunnableLike,
+ ) -> Self:
+ """Adds the specified node."""
+ if self._bound is not DEFAULT_BOUND:
+ self._bound = RunnableSeq(
+ self._bound, coerce_to_runnable(node, name=None, trace=True)
+ )
+ else:
+ self._bound = coerce_to_runnable(node, name=None, trace=True)
+ return self
+
+ def write_to(
+ self,
+ *channels: str | ChannelWriteEntry,
+ **kwargs: _WriteValue,
+ ) -> Self:
+ """Add channel writes.
+
+ Args:
+ *channels: Channel names to write to.
+ **kwargs: Channel name and value mappings.
+
+ Returns:
+ Self for chaining
+ """
+ self._writes.extend(
+ ChannelWriteEntry(c) if isinstance(c, str) else c for c in channels
+ )
+ self._writes.extend(
+ ChannelWriteEntry(k, mapper=v)
+ if callable(v)
+ else ChannelWriteEntry(k, value=v)
+ for k, v in kwargs.items()
+ )
+
+ return self
+
+ def meta(self, *tags: str, **metadata: Any) -> Self:
+ """Add tags or metadata to the node."""
+ self._tags.extend(tags)
+ self._metadata.update(metadata)
+ return self
+
+ def add_retry_policies(self, *policies: RetryPolicy) -> Self:
+ """Adds retry policies to the node."""
+ self._retry_policy.extend(policies)
+ return self
+
+ def add_cache_policy(self, policy: CachePolicy) -> Self:
+ """Adds cache policies to the node."""
+ self._cache_policy = policy
+ return self
+
+ def set_timeout(self, timeout: float | timedelta | TimeoutPolicy | None) -> Self:
+ """Set the per-attempt timeout policy for this node."""
+ self._timeout = coerce_timeout_policy(timeout)
+ return self
+
+ def build(self) -> PregelNode:
+ """Builds the node."""
+ return PregelNode(
+ channels=self._channels,
+ triggers=self._triggers,
+ tags=self._tags,
+ metadata=self._metadata,
+ writers=[ChannelWrite(self._writes)],
+ bound=self._bound,
+ retry_policy=self._retry_policy,
+ cache_policy=self._cache_policy,
+ timeout=self._timeout,
+ )
+
+
+# Kwargs that ``stream_events(version="v3")`` / ``astream_events(version="v3")``
+# manage internally and must not be overridden by callers. ``stream_mode`` is
+# derived from the transformer mux; ``subgraphs`` is forced True so nested
+# namespaces flow through scoped muxes. Forwarding either to the inner
+# ``stream(...)`` would silently break v3's invariants, so we raise instead.
+_V3_INVARIANT_KWARGS: tuple[str, ...] = ("stream_mode", "subgraphs")
+
+
+def _reject_v3_invariant_kwargs(kwargs: dict[str, Any]) -> None:
+ collisions = [k for k in _V3_INVARIANT_KWARGS if k in kwargs]
+ if collisions:
+ raise TypeError(
+ "stream_events(version='v3') / astream_events(version='v3') do "
+ f"not accept {', '.join(collisions)}; v3 owns these "
+ "(stream_mode is built from the transformer mux, subgraphs is "
+ "forced True so nested namespaces flow through scoped muxes)."
+ )
+
+
+def _collect_stream_modes(mux: Any) -> list[StreamMode]:
+ """Return the union of `required_stream_modes` across registered transformers.
+
+ Transformers declare the stream modes they need to function, and
+ `stream_events(version="v3")` asks the graph for exactly that union — no hardcoded
+ default set. If zero transformers declare a given mode, the graph
+ does not stream events for it.
+ """
+ modes: set[StreamMode] = set()
+ for transformer in mux._transformers:
+ modes.update(
+ cast(
+ "tuple[StreamMode, ...]",
+ getattr(transformer, "required_stream_modes", ()),
+ )
+ )
+ return list(modes)
+
+
+def _normalize_stream_transformer_factories(
+ specs: Sequence[Callable[[tuple[str, ...]], Any]] | None,
+) -> list[Callable[[tuple[str, ...]], Any]]:
+ """Normalize stream transformer specs to scoped factories.
+
+ A stream transformer spec is a callable that accepts
+ `scope: tuple[str, ...]` and returns a fresh `StreamTransformer`.
+ Transformer classes work when their constructor follows the same
+ shape. Pre-built instances are rejected because they cannot be
+ cloned into subgraph scopes.
+ """
+ factories: list[Callable[[tuple[str, ...]], Any]] = []
+ for spec in specs or ():
+ if isinstance(spec, StreamTransformer):
+ raise TypeError(
+ "stream_events(version='v3') transformers must be scope-aware callables, "
+ f"got pre-built instance {type(spec).__name__}. Pass the "
+ "transformer class or a factory like "
+ "`lambda scope: MyTransformer(scope, ...)`."
+ )
+ if not callable(spec):
+ raise TypeError(
+ "stream_events(version='v3') transformers must be scope-aware callables, "
+ f"got {type(spec).__name__}."
+ )
+
+ def factory(scope: tuple[str, ...], _spec: Callable[..., Any] = spec) -> Any:
+ return _spec(scope)
+
+ factories.append(factory)
+ return factories
+
+
+class Pregel(
+ PregelProtocol[StateT, ContextT, InputT, OutputT],
+ Generic[StateT, ContextT, InputT, OutputT],
+):
+ """Pregel manages the runtime behavior for LangGraph applications.
+
+ ## Overview
+
+ Pregel combines [**actors**](https://en.wikipedia.org/wiki/Actor_model)
+ and **channels** into a single application.
+ **Actors** read data from channels and write data to channels.
+ Pregel organizes the execution of the application into multiple steps,
+ following the **Pregel Algorithm**/**Bulk Synchronous Parallel** model.
+
+ Each step consists of three phases:
+
+ - **Plan**: Determine which **actors** to execute in this step. For example,
+ in the first step, select the **actors** that subscribe to the special
+ **input** channels; in subsequent steps,
+ select the **actors** that subscribe to channels updated in the previous step.
+ - **Execution**: Execute all selected **actors** in parallel,
+ until all complete, or one fails, or a timeout is reached. During this
+ phase, channel updates are invisible to actors until the next step.
+ - **Update**: Update the channels with the values written by the **actors**
+ in this step.
+
+ Repeat until no **actors** are selected for execution, or a maximum number of
+ steps is reached.
+
+ ## Actors
+
+ An **actor** is a `PregelNode`.
+ It subscribes to channels, reads data from them, and writes data to them.
+ It can be thought of as an **actor** in the Pregel algorithm.
+ `PregelNodes` implement LangChain's
+ Runnable interface.
+
+ ## Channels
+
+ Channels are used to communicate between actors (`PregelNodes`).
+ Each channel has a value type, an update type, and an update function – which
+ takes a sequence of updates and
+ modifies the stored value. Channels can be used to send data from one chain to
+ another, or to send data from a chain to itself in a future step. LangGraph
+ provides a number of built-in channels:
+
+ ### Basic channels: LastValue and Topic
+
+ - `LastValue`: The default channel, stores the last value sent to the channel,
+ useful for input and output values, or for sending data from one step to the next
+ - `Topic`: A configurable PubSub Topic, useful for sending multiple values
+ between *actors*, or for accumulating output. Can be configured to deduplicate
+ values, and/or to accumulate values over the course of multiple steps.
+
+ ### Advanced channels: Context and BinaryOperatorAggregate
+
+ - `Context`: exposes the value of a context manager, managing its lifecycle.
+ Useful for accessing external resources that require setup and/or teardown. e.g.
+ `client = Context(httpx.Client)`
+ - `BinaryOperatorAggregate`: stores a persistent value, updated by applying
+ a binary operator to the current value and each update
+ sent to the channel, useful for computing aggregates over multiple steps. e.g.
+ `total = BinaryOperatorAggregate(int, operator.add)`
+
+ ## Examples
+
+ Most users will interact with Pregel via a
+ [StateGraph (Graph API)][langgraph.graph.StateGraph] or via an
+ [entrypoint (Functional API)][langgraph.func.entrypoint].
+
+ However, for **advanced** use cases, Pregel can be used directly. If you're
+ not sure whether you need to use Pregel directly, then the answer is probably no
+ - you should use the Graph API or Functional API instead. These are higher-level
+ interfaces that will compile down to Pregel under the hood.
+
+ Here are some examples to give you a sense of how it works:
+
+ Example: Single node application
+ ```python
+ from langgraph.channels import EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b")
+ )
+
+ app = Pregel(
+ nodes={"node1": node1},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ },
+ input_channels=["a"],
+ output_channels=["b"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'b': 'foofoo'}
+ ```
+
+ Example: Using multiple nodes and multiple output channels
+ ```python
+ from langgraph.channels import LastValue, EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_to("b")
+ .do(lambda x: x["b"] + x["b"])
+ .write_to("c")
+ )
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": LastValue(str),
+ "c": EphemeralValue(str),
+ },
+ input_channels=["a"],
+ output_channels=["b", "c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'b': 'foofoo', 'c': 'foofoofoofoo'}
+ ```
+
+ Example: Using a Topic channel
+ ```python
+ from langgraph.channels import LastValue, EphemeralValue, Topic
+ from langgraph.pregel import Pregel, NodeBuilder
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b", "c")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_only("b")
+ .do(lambda x: x + x)
+ .write_to("c")
+ )
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ "c": Topic(str, accumulate=True),
+ },
+ input_channels=["a"],
+ output_channels=["c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```pycon
+ {"c": ["foofoo", "foofoofoofoo"]}
+ ```
+
+ Example: Using a `BinaryOperatorAggregate` channel
+ ```python
+ from langgraph.channels import EphemeralValue, BinaryOperatorAggregate
+ from langgraph.pregel import Pregel, NodeBuilder
+
+
+ node1 = (
+ NodeBuilder().subscribe_only("a")
+ .do(lambda x: x + x)
+ .write_to("b", "c")
+ )
+
+ node2 = (
+ NodeBuilder().subscribe_only("b")
+ .do(lambda x: x + x)
+ .write_to("c")
+ )
+
+
+ def reducer(current, update):
+ if current:
+ return current + " | " + update
+ else:
+ return update
+
+
+ app = Pregel(
+ nodes={"node1": node1, "node2": node2},
+ channels={
+ "a": EphemeralValue(str),
+ "b": EphemeralValue(str),
+ "c": BinaryOperatorAggregate(str, operator=reducer),
+ },
+ input_channels=["a"],
+ output_channels=["c"],
+ )
+
+ app.invoke({"a": "foo"})
+ ```
+
+ ```con
+ {'c': 'foofoo | foofoofoofoo'}
+ ```
+
+ Example: Introducing a cycle
+ This example demonstrates how to introduce a cycle in the graph, by having
+ a chain write to a channel it subscribes to.
+
+ Execution will continue until a `None` value is written to the channel.
+
+ ```python
+ from langgraph.channels import EphemeralValue
+ from langgraph.pregel import Pregel, NodeBuilder, ChannelWriteEntry
+
+ example_node = (
+ NodeBuilder()
+ .subscribe_only("value")
+ .do(lambda x: x + x if len(x) < 10 else None)
+ .write_to(ChannelWriteEntry(channel="value", skip_none=True))
+ )
+
+ app = Pregel(
+ nodes={"example_node": example_node},
+ channels={
+ "value": EphemeralValue(str),
+ },
+ input_channels=["value"],
+ output_channels=["value"],
+ )
+
+ app.invoke({"value": "a"})
+ ```
+
+ ```con
+ {'value': 'aaaaaaaaaaaaaaaa'}
+ ```
+ """
+
+ nodes: dict[str, PregelNode]
+
+ channels: dict[str, BaseChannel | ManagedValueSpec]
+
+ stream_mode: StreamMode = "values"
+ """Mode to stream output, defaults to 'values'."""
+
+ stream_eager: bool = False
+ """Whether to force emitting stream events eagerly, automatically turned on
+ for stream_mode "messages" and "custom"."""
+
+ output_channels: str | Sequence[str]
+
+ stream_channels: str | Sequence[str] | None = None
+ """Channels to stream, defaults to all channels not in reserved channels"""
+
+ interrupt_after_nodes: All | Sequence[str]
+
+ interrupt_before_nodes: All | Sequence[str]
+
+ input_channels: str | Sequence[str]
+
+ step_timeout: float | None = None
+ """Maximum time to wait for a step to complete, in seconds."""
+
+ debug: bool
+ """Whether to print debug information during execution."""
+
+ checkpointer: Checkpointer = None
+ """`Checkpointer` used to save and load graph state."""
+
+ store: BaseStore | None = None
+ """Memory store to use for SharedValues."""
+
+ cache: BaseCache | None = None
+ """Cache to use for storing node results."""
+
+ retry_policy: Sequence[RetryPolicy] = ()
+ """Retry policies to use when running tasks. Empty set disables retries."""
+
+ cache_policy: CachePolicy | None = None
+ """Cache policy to use for all nodes. Can be overridden by individual nodes."""
+
+ context_schema: type[ContextT] | None = None
+ """Specifies the schema for the context object that will be passed to the workflow."""
+
+ config: RunnableConfig | None = None
+
+ name: str = "LangGraph"
+
+ trigger_to_nodes: Mapping[str, Sequence[str]]
+ node_error_handler_map: Mapping[str, str]
+
+ def __init__(
+ self,
+ *,
+ nodes: dict[str, PregelNode | NodeBuilder],
+ channels: dict[str, BaseChannel | ManagedValueSpec] | None,
+ auto_validate: bool = True,
+ stream_mode: StreamMode = "values",
+ stream_eager: bool = False,
+ output_channels: str | Sequence[str],
+ stream_channels: str | Sequence[str] | None = None,
+ interrupt_after_nodes: All | Sequence[str] = (),
+ interrupt_before_nodes: All | Sequence[str] = (),
+ input_channels: str | Sequence[str],
+ step_timeout: float | None = None,
+ debug: bool | None = None,
+ checkpointer: Checkpointer = None,
+ store: BaseStore | None = None,
+ cache: BaseCache | None = None,
+ retry_policy: RetryPolicy | Sequence[RetryPolicy] = (),
+ cache_policy: CachePolicy | None = None,
+ context_schema: type[ContextT] | None = None,
+ config: RunnableConfig | None = None,
+ trigger_to_nodes: Mapping[str, Sequence[str]] | None = None,
+ node_error_handler_map: Mapping[str, str] | None = None,
+ name: str = "LangGraph",
+ stream_transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **deprecated_kwargs: Unpack[DeprecatedKwargs],
+ ) -> None:
+ if (
+ config_type := deprecated_kwargs.get("config_type", MISSING)
+ ) is not MISSING:
+ warnings.warn(
+ "`config_type` is deprecated and will be removed. Please use `context_schema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ if context_schema is None:
+ context_schema = cast(type[ContextT], config_type)
+
+ checkpointer = ensure_valid_checkpointer(checkpointer)
+
+ self.nodes = {
+ k: v.build() if isinstance(v, NodeBuilder) else v for k, v in nodes.items()
+ }
+ self.channels = channels or {}
+ if TASKS in self.channels and not isinstance(self.channels[TASKS], Topic):
+ raise ValueError(
+ f"Channel '{TASKS}' is reserved and cannot be used in the graph."
+ )
+ else:
+ self.channels[TASKS] = Topic(Send, accumulate=False)
+ self.stream_mode = stream_mode
+ self.stream_eager = stream_eager
+ self.output_channels = output_channels
+ self.stream_channels = stream_channels
+ self.interrupt_after_nodes = interrupt_after_nodes
+ self.interrupt_before_nodes = interrupt_before_nodes
+ self.input_channels = input_channels
+ self.step_timeout = step_timeout
+ self.debug = debug if debug is not None else get_debug()
+ self.checkpointer = checkpointer
+ self.store = store
+ self.cache = cache
+ self.retry_policy = (
+ (retry_policy,) if isinstance(retry_policy, RetryPolicy) else retry_policy
+ )
+ self.cache_policy = cache_policy
+ self.context_schema = context_schema
+ self.config = config
+ self.trigger_to_nodes = trigger_to_nodes or {}
+ self.node_error_handler_map = node_error_handler_map or {}
+ self.name = name
+ self.stream_transformers: tuple[Callable[[tuple[str, ...]], Any], ...] = tuple(
+ stream_transformers or ()
+ )
+ self._serde_allowlist: set[tuple[str, ...]] | None = None
+ if auto_validate:
+ self.validate()
+
+ def _apply_checkpointer_allowlist(
+ self, checkpointer: BaseCheckpointSaver | None
+ ) -> BaseCheckpointSaver | None:
+ if not _serde.STRICT_MSGPACK_ENABLED:
+ return checkpointer
+ return _serde.apply_checkpointer_allowlist(checkpointer, self._serde_allowlist)
+
+ def get_graph(
+ self, config: RunnableConfig | None = None, *, xray: int | bool = False
+ ) -> Graph:
+ """Return a drawable representation of the computation graph."""
+ # gather subgraphs
+ if xray:
+ subgraphs = {
+ k: v.get_graph(
+ config,
+ xray=xray if isinstance(xray, bool) or xray <= 0 else xray - 1,
+ )
+ for k, v in self.get_subgraphs()
+ }
+ else:
+ subgraphs = {}
+
+ return draw_graph(
+ merge_configs(self.config, config),
+ nodes=self.nodes,
+ specs=self.channels,
+ input_channels=self.input_channels,
+ interrupt_after_nodes=self.interrupt_after_nodes,
+ interrupt_before_nodes=self.interrupt_before_nodes,
+ trigger_to_nodes=self.trigger_to_nodes,
+ checkpointer=self.checkpointer,
+ subgraphs=subgraphs,
+ )
+
+ async def aget_graph(
+ self, config: RunnableConfig | None = None, *, xray: int | bool = False
+ ) -> Graph:
+ """Return a drawable representation of the computation graph."""
+
+ # gather subgraphs
+ if xray:
+ subpregels: dict[str, PregelProtocol] = {
+ k: v async for k, v in self.aget_subgraphs()
+ }
+ subgraphs = {
+ k: v
+ for k, v in zip(
+ subpregels,
+ await asyncio.gather(
+ *(
+ p.aget_graph(
+ config,
+ xray=xray
+ if isinstance(xray, bool) or xray <= 0
+ else xray - 1,
+ )
+ for p in subpregels.values()
+ )
+ ),
+ )
+ }
+ else:
+ subgraphs = {}
+
+ return draw_graph(
+ merge_configs(self.config, config),
+ nodes=self.nodes,
+ specs=self.channels,
+ input_channels=self.input_channels,
+ interrupt_after_nodes=self.interrupt_after_nodes,
+ interrupt_before_nodes=self.interrupt_before_nodes,
+ trigger_to_nodes=self.trigger_to_nodes,
+ checkpointer=self.checkpointer,
+ subgraphs=subgraphs,
+ )
+
+ def _repr_mimebundle_(self, **kwargs: Any) -> dict[str, Any]:
+ """Mime bundle used by Jupyter to display the graph"""
+ return {
+ "text/plain": repr(self),
+ "image/png": self.get_graph().draw_mermaid_png(),
+ }
+
+ def copy(self, update: dict[str, Any] | None = None) -> Self:
+ attrs = {k: v for k, v in self.__dict__.items() if k != "__orig_class__"}
+ attrs.update(update or {})
+ return self.__class__(**attrs)
+
+ def with_config(self, config: RunnableConfig | None = None, **kwargs: Any) -> Self:
+ """Create a copy of the Pregel object with an updated config."""
+ return self.copy(
+ {"config": merge_configs(self.config, config, cast(RunnableConfig, kwargs))}
+ )
+
+ def validate(self) -> Self:
+ for name, node in self.nodes.items():
+ if node.timeout is not None:
+ validate_timeout_supported(node.node or node.bound, name=name)
+ validate_graph(
+ self.nodes,
+ {k: v for k, v in self.channels.items() if isinstance(v, BaseChannel)},
+ {k: v for k, v in self.channels.items() if not isinstance(v, BaseChannel)},
+ self.input_channels,
+ self.output_channels,
+ self.stream_channels,
+ self.interrupt_after_nodes,
+ self.interrupt_before_nodes,
+ )
+ self.trigger_to_nodes = _trigger_to_nodes(self.nodes)
+ return self
+
+ @deprecated(
+ "`config_schema` is deprecated. Use `get_context_jsonschema` for the relevant schema instead.",
+ category=None,
+ )
+ def config_schema(self, *, include: Sequence[str] | None = None) -> type[BaseModel]:
+ warnings.warn(
+ "`config_schema` is deprecated. Use `get_context_jsonschema` for the relevant schema instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ include = include or []
+ fields = {
+ **(
+ {"configurable": (self.context_schema, None)}
+ if self.context_schema
+ else {}
+ ),
+ **{
+ field_name: (field_type, None)
+ for field_name, field_type in get_type_hints(RunnableConfig).items()
+ if field_name in [i for i in include if i != "configurable"]
+ },
+ }
+ return create_model(self.get_name("Config"), field_definitions=fields)
+
+ @deprecated(
+ "`get_config_jsonschema` is deprecated. Use `get_context_jsonschema` instead.",
+ category=None,
+ )
+ def get_config_jsonschema(
+ self, *, include: Sequence[str] | None = None
+ ) -> dict[str, Any]:
+ warnings.warn(
+ "`get_config_jsonschema` is deprecated. Use `get_context_jsonschema` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=LangGraphDeprecatedSinceV10)
+ schema = self.config_schema(include=include)
+ return schema.model_json_schema()
+
+ def get_context_jsonschema(self) -> dict[str, Any] | None:
+ if (context_schema := self.context_schema) is None:
+ return None
+
+ if isclass(context_schema) and issubclass(context_schema, BaseModel):
+ return context_schema.model_json_schema()
+ elif is_typeddict(context_schema) or is_dataclass(context_schema):
+ return TypeAdapter(context_schema).json_schema()
+ else:
+ raise ValueError(
+ f"Invalid context schema type: {context_schema}. Must be a BaseModel, TypedDict or dataclass."
+ )
+
+ @property
+ def InputType(self) -> Any:
+ if isinstance(self.input_channels, str):
+ channel = self.channels[self.input_channels]
+ if isinstance(channel, BaseChannel):
+ return channel.UpdateType
+
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ config = merge_configs(self.config, config)
+ if isinstance(self.input_channels, str):
+ return super().get_input_schema(config)
+ else:
+ return create_model(
+ self.get_name("Input"),
+ field_definitions={
+ k: (c.UpdateType, None)
+ for k in self.input_channels or self.channels.keys()
+ if (c := self.channels[k]) and isinstance(c, BaseChannel)
+ },
+ )
+
+ def get_input_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ schema = self.get_input_schema(config)
+ return schema.model_json_schema()
+
+ @property
+ def OutputType(self) -> Any:
+ if isinstance(self.output_channels, str):
+ channel = self.channels[self.output_channels]
+ if isinstance(channel, BaseChannel):
+ return channel.ValueType
+
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ config = merge_configs(self.config, config)
+ if isinstance(self.output_channels, str):
+ return super().get_output_schema(config)
+ else:
+ return create_model(
+ self.get_name("Output"),
+ field_definitions={
+ k: (c.ValueType, None)
+ for k in self.output_channels
+ if (c := self.channels[k]) and isinstance(c, BaseChannel)
+ },
+ )
+
+ def get_output_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ schema = self.get_output_schema(config)
+ return schema.model_json_schema()
+
+ @property
+ def stream_channels_list(self) -> Sequence[str]:
+ stream_channels = self.stream_channels_asis
+ return (
+ [stream_channels] if isinstance(stream_channels, str) else stream_channels
+ )
+
+ @property
+ def stream_channels_asis(self) -> str | Sequence[str]:
+ return self.stream_channels or [
+ k for k in self.channels if isinstance(self.channels[k], BaseChannel)
+ ]
+
+ def get_subgraphs(
+ self, *, namespace: str | None = None, recurse: bool = False
+ ) -> Iterator[tuple[str, PregelProtocol]]:
+ """Get the subgraphs of the graph.
+
+ Args:
+ namespace: The namespace to filter the subgraphs by.
+ recurse: Whether to recurse into the subgraphs.
+ If `False`, only the immediate subgraphs will be returned.
+
+ Returns:
+ An iterator of the `(namespace, subgraph)` pairs.
+ """
+ for name, node in self.nodes.items():
+ # filter by prefix
+ if namespace is not None:
+ if not namespace.startswith(name):
+ continue
+
+ # find the subgraph, if any
+ graph = node.subgraphs[0] if node.subgraphs else None
+
+ # if found, yield recursively
+ if graph:
+ if name == namespace:
+ yield name, graph
+ return # we found it, stop searching
+ if namespace is None:
+ yield name, graph
+ if recurse and isinstance(graph, Pregel):
+ if namespace is not None:
+ namespace = namespace[len(name) + 1 :]
+ yield from (
+ (f"{name}{NS_SEP}{n}", s)
+ for n, s in graph.get_subgraphs(
+ namespace=namespace, recurse=recurse
+ )
+ )
+
+ async def aget_subgraphs(
+ self, *, namespace: str | None = None, recurse: bool = False
+ ) -> AsyncIterator[tuple[str, PregelProtocol]]:
+ """Get the subgraphs of the graph.
+
+ Args:
+ namespace: The namespace to filter the subgraphs by.
+ recurse: Whether to recurse into the subgraphs.
+ If `False`, only the immediate subgraphs will be returned.
+
+ Returns:
+ An iterator of the `(namespace, subgraph)` pairs.
+ """
+ for name, node in self.get_subgraphs(namespace=namespace, recurse=recurse):
+ yield name, node
+
+ # Mappers for v2 stream coercion (pydantic/dataclass).
+ # Set by CompiledStateGraph; None for base Pregel.
+ _output_mapper: Callable[[Any], Any] | None = None
+ _state_mapper: Callable[[Any], Any] | None = None
+
+ def _migrate_checkpoint(self, checkpoint: Checkpoint) -> None:
+ """Migrate a saved checkpoint to new channel layout."""
+ if checkpoint["v"] < 4 and checkpoint.get("pending_sends"):
+ pending_sends: list[Send] = checkpoint.pop("pending_sends")
+ checkpoint["channel_values"][TASKS] = pending_sends
+ checkpoint["channel_versions"][TASKS] = max(
+ checkpoint["channel_versions"].values()
+ )
+
+ def _prepare_state_snapshot(
+ self,
+ config: RunnableConfig,
+ saved: CheckpointTuple | None,
+ recurse: BaseCheckpointSaver | None = None,
+ apply_pending_writes: bool = False,
+ ) -> StateSnapshot:
+ if not saved:
+ return StateSnapshot(
+ values={},
+ next=(),
+ config=config,
+ metadata=None,
+ created_at=None,
+ parent_config=None,
+ tasks=(),
+ interrupts=(),
+ )
+
+ # migrate checkpoint if needed
+ self._migrate_checkpoint(saved.checkpoint)
+
+ step = saved.metadata.get("step", -1) + 1
+ stop = step + 2
+ channels, managed = channels_from_checkpoint(
+ self.channels,
+ saved.checkpoint,
+ saver=self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config,
+ )
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ saved.checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step,
+ stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=(
+ self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None
+ ),
+ manager=None,
+ )
+ # get the subgraphs
+ subgraphs = dict(self.get_subgraphs())
+ parent_ns = saved.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+ for task in next_tasks.values():
+ if task.name not in subgraphs:
+ continue
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+ if not recurse:
+ # set config as signal that subgraph checkpoints exist
+ config = {
+ CONF: {
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = config
+ else:
+ # get the state of the subgraph
+ config = {
+ CONF: {
+ CONFIG_KEY_CHECKPOINTER: recurse,
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = subgraphs[task.name].get_state(
+ config, subgraphs=True
+ )
+ # apply pending writes
+ if null_writes := [
+ w[1:] for w in saved.pending_writes or [] if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ saved.checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ None,
+ self.trigger_to_nodes,
+ )
+ if apply_pending_writes and saved.pending_writes:
+ for tid, k, v in saved.pending_writes:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ if tasks := [t for t in next_tasks.values() if t.writes]:
+ apply_writes(
+ saved.checkpoint, channels, tasks, None, self.trigger_to_nodes
+ )
+ tasks_with_writes = tasks_w_writes(
+ next_tasks.values(),
+ saved.pending_writes,
+ task_states,
+ self.stream_channels_asis,
+ )
+ # assemble the state snapshot
+ return StateSnapshot(
+ read_channels(channels, self.stream_channels_asis),
+ tuple(t.name for t in next_tasks.values() if not t.writes),
+ patch_checkpoint_map(saved.config, saved.metadata),
+ saved.metadata,
+ saved.checkpoint["ts"],
+ patch_checkpoint_map(saved.parent_config, saved.metadata),
+ tasks_with_writes,
+ tuple([i for task in tasks_with_writes for i in task.interrupts]),
+ )
+
+ async def _aprepare_state_snapshot(
+ self,
+ config: RunnableConfig,
+ saved: CheckpointTuple | None,
+ recurse: BaseCheckpointSaver | None = None,
+ apply_pending_writes: bool = False,
+ ) -> StateSnapshot:
+ if not saved:
+ return StateSnapshot(
+ values={},
+ next=(),
+ config=config,
+ metadata=None,
+ created_at=None,
+ parent_config=None,
+ tasks=(),
+ interrupts=(),
+ )
+
+ # migrate checkpoint if needed
+ self._migrate_checkpoint(saved.checkpoint)
+
+ step = saved.metadata.get("step", -1) + 1
+ stop = step + 2
+ channels, managed = await achannels_from_checkpoint(
+ self.channels,
+ saved.checkpoint,
+ saver=self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config,
+ )
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ saved.checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step,
+ stop,
+ for_execution=True,
+ store=self.store,
+ checkpointer=(
+ self.checkpointer
+ if isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None
+ ),
+ manager=None,
+ )
+ # get the subgraphs
+ subgraphs = {n: g async for n, g in self.aget_subgraphs()}
+ parent_ns = saved.config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ task_states: dict[str, RunnableConfig | StateSnapshot] = {}
+ for task in next_tasks.values():
+ if task.name not in subgraphs:
+ continue
+ # assemble checkpoint_ns for this task
+ task_ns = f"{task.name}{NS_END}{task.id}"
+ if parent_ns:
+ task_ns = f"{parent_ns}{NS_SEP}{task_ns}"
+ if not recurse:
+ # set config as signal that subgraph checkpoints exist
+ config = {
+ CONF: {
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = config
+ else:
+ # get the state of the subgraph
+ config = {
+ CONF: {
+ CONFIG_KEY_CHECKPOINTER: recurse,
+ "thread_id": saved.config[CONF]["thread_id"],
+ CONFIG_KEY_CHECKPOINT_NS: task_ns,
+ }
+ }
+ task_states[task.id] = await subgraphs[task.name].aget_state(
+ config, subgraphs=True
+ )
+ # apply pending writes
+ if null_writes := [
+ w[1:] for w in saved.pending_writes or [] if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ saved.checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ None,
+ self.trigger_to_nodes,
+ )
+ if apply_pending_writes and saved.pending_writes:
+ for tid, k, v in saved.pending_writes:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ if tasks := [t for t in next_tasks.values() if t.writes]:
+ apply_writes(
+ saved.checkpoint, channels, tasks, None, self.trigger_to_nodes
+ )
+
+ tasks_with_writes = tasks_w_writes(
+ next_tasks.values(),
+ saved.pending_writes,
+ task_states,
+ self.stream_channels_asis,
+ )
+ # assemble the state snapshot
+ return StateSnapshot(
+ read_channels(channels, self.stream_channels_asis),
+ tuple(t.name for t in next_tasks.values() if not t.writes),
+ patch_checkpoint_map(saved.config, saved.metadata),
+ saved.metadata,
+ saved.checkpoint["ts"],
+ patch_checkpoint_map(saved.parent_config, saved.metadata),
+ tasks_with_writes,
+ tuple([i for task in tasks_with_writes for i in task.interrupts]),
+ )
+
+ def get_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot:
+ """Get the current state of the graph."""
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ return pregel.get_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ subgraphs=subgraphs,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(self.config, config) if self.config else config
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config = merge_configs(
+ config, {CONF: {CONFIG_KEY_CHECKPOINT_NS: recast_checkpoint_ns(ns)}}
+ )
+ thread_id = config[CONF][CONFIG_KEY_THREAD_ID]
+ if not isinstance(thread_id, str):
+ config[CONF][CONFIG_KEY_THREAD_ID] = str(thread_id)
+
+ saved = checkpointer.get_tuple(config)
+ return self._prepare_state_snapshot(
+ config,
+ saved,
+ recurse=checkpointer if subgraphs else None,
+ apply_pending_writes=CONFIG_KEY_CHECKPOINT_ID not in config[CONF],
+ )
+
+ async def aget_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot:
+ """Get the current state of the graph."""
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ return await pregel.aget_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ subgraphs=subgraphs,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(self.config, config) if self.config else config
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config = merge_configs(
+ config, {CONF: {CONFIG_KEY_CHECKPOINT_NS: recast_checkpoint_ns(ns)}}
+ )
+ thread_id = config[CONF][CONFIG_KEY_THREAD_ID]
+ if not isinstance(thread_id, str):
+ config[CONF][CONFIG_KEY_THREAD_ID] = str(thread_id)
+
+ saved = await checkpointer.aget_tuple(config)
+ return await self._aprepare_state_snapshot(
+ config,
+ saved,
+ recurse=checkpointer if subgraphs else None,
+ apply_pending_writes=CONFIG_KEY_CHECKPOINT_ID not in config[CONF],
+ )
+
+ def get_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> Iterator[StateSnapshot]:
+ """Get the history of the state of the graph."""
+ config = ensure_config(config)
+ checkpointer: BaseCheckpointSaver | None = config[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ yield from pregel.get_state_history(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ filter=filter,
+ before=before,
+ limit=limit,
+ )
+ return
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(
+ self.config,
+ config,
+ {
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: checkpoint_ns,
+ CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID]),
+ }
+ },
+ )
+ # eagerly consume list() to avoid holding up the db cursor
+ for checkpoint_tuple in list(
+ checkpointer.list(config, before=before, limit=limit, filter=filter)
+ ):
+ yield self._prepare_state_snapshot(
+ checkpoint_tuple.config, checkpoint_tuple
+ )
+
+ async def aget_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[StateSnapshot]:
+ """Asynchronously get the history of the state of the graph."""
+ config = ensure_config(config)
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ async for state in pregel.aget_state_history(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ filter=filter,
+ before=before,
+ limit=limit,
+ ):
+ yield state
+ return
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ config = merge_configs(
+ self.config,
+ config,
+ {
+ CONF: {
+ CONFIG_KEY_CHECKPOINT_NS: checkpoint_ns,
+ CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID]),
+ }
+ },
+ )
+ # eagerly consume list() to avoid holding up the db cursor
+ for checkpoint_tuple in [
+ c
+ async for c in checkpointer.alist(
+ config, before=before, limit=limit, filter=filter
+ )
+ ]:
+ yield await self._aprepare_state_snapshot(
+ checkpoint_tuple.config, checkpoint_tuple
+ )
+
+ def bulk_update_state(
+ self,
+ config: RunnableConfig,
+ supersteps: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig:
+ """Apply updates to the graph state in bulk. Requires a checkpointer to be set.
+
+ Args:
+ config: The config to apply the updates to.
+ supersteps: A list of supersteps, each including a list of updates to apply sequentially to a graph state.
+
+ Each update is a tuple of the form `(values, as_node, task_id)` where `task_id` is optional.
+
+ Raises:
+ ValueError: If no checkpointer is set or no updates are provided.
+ InvalidUpdateError: If an invalid update is provided.
+
+ Returns:
+ RunnableConfig: The updated config.
+ """
+
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if len(supersteps) == 0:
+ raise ValueError("No supersteps provided")
+
+ if any(len(u) == 0 for u in supersteps):
+ raise ValueError("No updates provided")
+
+ # delegate to subgraph
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ for _, pregel in self.get_subgraphs(namespace=recast, recurse=True):
+ return pregel.bulk_update_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ supersteps,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ def perform_superstep(
+ input_config: RunnableConfig, updates: Sequence[StateUpdate]
+ ) -> RunnableConfig:
+ # get last checkpoint
+ config = ensure_config(self.config, input_config)
+ saved = checkpointer.get_tuple(config)
+ if saved is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ checkpoint = (
+ copy_checkpoint(saved.checkpoint) if saved else empty_checkpoint()
+ )
+ checkpoint_previous_versions = (
+ saved.checkpoint["channel_versions"].copy() if saved else {}
+ )
+ step = saved.metadata.get("step", -1) if saved else -1
+ # merge configurable fields with previous checkpoint config
+ checkpoint_config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ )
+ },
+ )
+ if saved:
+ checkpoint_config = patch_configurable(config, saved.config[CONF])
+ channels, managed = channels_from_checkpoint(
+ self.channels,
+ checkpoint,
+ saver=self.checkpointer
+ if saved is not None
+ and isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config if saved is not None else None,
+ )
+ values, as_node = updates[0][:2]
+
+ # no values as END, just clear all tasks
+ if values is None and as_node == END:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when clearing state"
+ )
+
+ if saved is not None:
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # apply null writes
+ if null_writes := [
+ w[1:]
+ for w in saved.pending_writes or []
+ if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # apply writes from tasks that already ran
+ for tid, k, v in saved.pending_writes or []:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ # clear all current tasks
+ apply_writes(
+ checkpoint,
+ channels,
+ next_tasks.values(),
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # save checkpoint
+ next_config = checkpointer.put(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, step),
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # act as an input
+ if as_node == INPUT:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when updating as input"
+ )
+
+ if input_writes := deque(map_input(self.input_channels, values)):
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, input_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+
+ # apply input write to channels
+ next_step = (
+ step + 1
+ if saved and saved.metadata.get("step") is not None
+ else -1
+ )
+ next_config = checkpointer.put(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, next_step),
+ {
+ "source": "input",
+ "step": next_step,
+ "parents": saved.metadata.get("parents", {})
+ if saved
+ else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+
+ # store the writes
+ checkpointer.put_writes(
+ next_config,
+ input_writes,
+ str(uuid5(UUID(checkpoint["id"]), INPUT)),
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+ else:
+ raise InvalidUpdateError(
+ f"Received no input writes for {self.input_channels}"
+ )
+
+ # copy checkpoint
+ if as_node == "__copy__":
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot copy checkpoint with multiple updates"
+ )
+
+ if saved is None:
+ raise InvalidUpdateError("Cannot copy a non-existent checkpoint")
+
+ next_checkpoint = create_checkpoint(checkpoint, None, step)
+
+ # copy checkpoint
+ next_config = checkpointer.put(
+ saved.parent_config
+ or patch_configurable(
+ saved.config, {CONFIG_KEY_CHECKPOINT_ID: None}
+ ),
+ next_checkpoint,
+ {
+ "source": "fork",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}),
+ },
+ {},
+ )
+
+ # we want to both clone a checkpoint and update state in one go.
+ # reuse the same task ID if possible.
+ if isinstance(values, list) and len(values) > 0:
+ # figure out the task IDs for the next update checkpoint
+ next_tasks = prepare_next_tasks(
+ next_checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ next_config,
+ step + 2,
+ step + 4,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+
+ tasks_group_by = defaultdict(list)
+ user_group_by: dict[str, list[StateUpdate]] = defaultdict(list)
+
+ for task in next_tasks.values():
+ tasks_group_by[task.name].append(task.id)
+
+ for item in values:
+ if not isinstance(item, Sequence):
+ raise InvalidUpdateError(
+ f"Invalid update item: {item} when copying checkpoint"
+ )
+
+ values, as_node = item[:2]
+
+ user_group = user_group_by[as_node]
+ tasks_group = tasks_group_by[as_node]
+
+ target_idx = len(user_group)
+ task_id = (
+ tasks_group[target_idx]
+ if target_idx < len(tasks_group)
+ else None
+ )
+
+ user_group_by[as_node].append(
+ StateUpdate(values=values, as_node=as_node, task_id=task_id)
+ )
+
+ return perform_superstep(
+ patch_checkpoint_map(next_config, saved.metadata),
+ [item for lst in user_group_by.values() for item in lst],
+ )
+
+ return patch_checkpoint_map(next_config, saved.metadata)
+
+ # task ids can be provided in the StateUpdate, but if not,
+ # we use the task id generated by prepare_next_tasks
+ node_to_task_ids: dict[str, deque[str]] = defaultdict(deque)
+ if saved is not None and saved.pending_writes is not None:
+ # we call prepare_next_tasks to discover the task IDs that
+ # would have been generated, so we can reuse them and
+ # properly populate task.result in state history
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes,
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # collect task ids to reuse so we can properly attach task results
+ for t in next_tasks.values():
+ node_to_task_ids[t.name].append(t.id)
+
+ valid_updates: list[tuple[str, dict[str, Any] | None, str | None]] = []
+ if len(updates) == 1:
+ values, as_node, task_id = updates[0]
+ # find last node that updated the state, if not provided
+ if as_node is None and len(self.nodes) == 1:
+ as_node = tuple(self.nodes)[0]
+ elif as_node is None and not any(
+ v
+ for vv in checkpoint["versions_seen"].values()
+ for v in vv.values()
+ ):
+ if (
+ isinstance(self.input_channels, str)
+ and self.input_channels in self.nodes
+ ):
+ as_node = self.input_channels
+ elif as_node is None:
+ last_seen_by_node = sorted(
+ (v, n)
+ for n, seen in checkpoint["versions_seen"].items()
+ if n in self.nodes
+ for v in seen.values()
+ )
+ # if two nodes updated the state at the same time, it's ambiguous
+ if last_seen_by_node:
+ if len(last_seen_by_node) == 1:
+ as_node = last_seen_by_node[0][1]
+ elif last_seen_by_node[-1][0] != last_seen_by_node[-2][0]:
+ as_node = last_seen_by_node[-1][1]
+ if as_node is None:
+ raise InvalidUpdateError("Ambiguous update, specify as_node")
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+ valid_updates.append((as_node, values, task_id))
+ else:
+ for values, as_node, task_id in updates:
+ if as_node is None:
+ raise InvalidUpdateError(
+ "as_node is required when applying multiple updates"
+ )
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+
+ valid_updates.append((as_node, values, task_id))
+
+ run_tasks: list[PregelTaskWrites] = []
+ run_task_ids: list[str] = []
+
+ for as_node, values, provided_task_id in valid_updates:
+ # create task to run all writers of the chosen node
+ writers = self.nodes[as_node].flat_writers
+ if not writers:
+ raise InvalidUpdateError(f"Node {as_node} has no writers")
+ writes: deque[tuple[str, Any]] = deque()
+ task = PregelTaskWrites((), as_node, writes, [INTERRUPT])
+ # get the task ids that were prepared for this node
+ # if a task id was provided in the StateUpdate, we use it
+ # otherwise, we use the next available task id
+ prepared_task_ids = node_to_task_ids.get(as_node, deque())
+ task_id = provided_task_id or (
+ prepared_task_ids.popleft()
+ if prepared_task_ids
+ else str(uuid5(UUID(checkpoint["id"]), INTERRUPT))
+ )
+ run_tasks.append(task)
+ run_task_ids.append(task_id)
+ run = RunnableSequence(*writers) if len(writers) > 1 else writers[0]
+ # execute task
+ run.invoke(
+ values,
+ patch_config(
+ config,
+ run_name=self.name + "UpdateState",
+ configurable={
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ _scratchpad(
+ None,
+ [],
+ task_id,
+ "",
+ None,
+ step,
+ step + 2,
+ ),
+ channels,
+ managed,
+ task,
+ ),
+ },
+ ),
+ )
+ # save task writes
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # channel writes are saved to current checkpoint
+ channel_writes = [w for w in task.writes if w[0] != PUSH]
+ if saved and channel_writes:
+ checkpointer.put_writes(checkpoint_config, channel_writes, task_id)
+ # apply to checkpoint and save
+ apply_writes(
+ checkpoint,
+ channels,
+ run_tasks,
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ checkpoint = create_checkpoint(checkpoint, channels, step + 1)
+ next_config = checkpointer.put(
+ checkpoint_config,
+ checkpoint,
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # save push writes
+ if push_writes := [w for w in task.writes if w[0] == PUSH]:
+ checkpointer.put_writes(next_config, push_writes, task_id)
+
+ return patch_checkpoint_map(next_config, saved.metadata if saved else None)
+
+ current_config = patch_configurable(
+ config, {CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID])}
+ )
+ for superstep in supersteps:
+ current_config = perform_superstep(current_config, superstep)
+ return current_config
+
+ async def abulk_update_state(
+ self,
+ config: RunnableConfig,
+ supersteps: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig:
+ """Asynchronously apply updates to the graph state in bulk. Requires a checkpointer to be set.
+
+ Args:
+ config: The config to apply the updates to.
+ supersteps: A list of supersteps, each including a list of updates to apply sequentially to a graph state.
+
+ Each update is a tuple of the form `(values, as_node, task_id)` where `task_id` is optional.
+
+ Raises:
+ ValueError: If no checkpointer is set or no updates are provided.
+ InvalidUpdateError: If an invalid update is provided.
+
+ Returns:
+ RunnableConfig: The updated config.
+ """
+
+ checkpointer: BaseCheckpointSaver | None = ensure_config(config)[CONF].get(
+ CONFIG_KEY_CHECKPOINTER, self.checkpointer
+ )
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if not checkpointer:
+ raise ValueError("No checkpointer set")
+
+ if len(supersteps) == 0:
+ raise ValueError("No supersteps provided")
+
+ if any(len(u) == 0 for u in supersteps):
+ raise ValueError("No updates provided")
+
+ # delegate to subgraph
+ if (
+ checkpoint_ns := config[CONF].get(CONFIG_KEY_CHECKPOINT_NS, "")
+ ) and CONFIG_KEY_CHECKPOINTER not in config[CONF]:
+ # remove task_ids from checkpoint_ns
+ recast = recast_checkpoint_ns(checkpoint_ns)
+ # find the subgraph with the matching name
+ async for _, pregel in self.aget_subgraphs(namespace=recast, recurse=True):
+ return await pregel.abulk_update_state(
+ patch_configurable(config, {CONFIG_KEY_CHECKPOINTER: checkpointer}),
+ supersteps,
+ )
+ else:
+ raise ValueError(f"Subgraph {recast} not found")
+
+ async def aperform_superstep(
+ input_config: RunnableConfig, updates: Sequence[StateUpdate]
+ ) -> RunnableConfig:
+ # get last checkpoint
+ config = ensure_config(self.config, input_config)
+ saved = await checkpointer.aget_tuple(config)
+ if saved is not None:
+ self._migrate_checkpoint(saved.checkpoint)
+ checkpoint = (
+ copy_checkpoint(saved.checkpoint) if saved else empty_checkpoint()
+ )
+ checkpoint_previous_versions = (
+ saved.checkpoint["channel_versions"].copy() if saved else {}
+ )
+ step = saved.metadata.get("step", -1) if saved else -1
+ # merge configurable fields with previous checkpoint config
+ checkpoint_config = patch_configurable(
+ config,
+ {
+ CONFIG_KEY_CHECKPOINT_NS: config[CONF].get(
+ CONFIG_KEY_CHECKPOINT_NS, ""
+ )
+ },
+ )
+ if saved:
+ checkpoint_config = patch_configurable(config, saved.config[CONF])
+ channels, managed = await achannels_from_checkpoint(
+ self.channels,
+ checkpoint,
+ saver=self.checkpointer
+ if saved is not None
+ and isinstance(self.checkpointer, BaseCheckpointSaver)
+ else None,
+ config=saved.config if saved is not None else None,
+ )
+ values, as_node = updates[0][:2]
+ # no values, just clear all tasks
+ if values is None and as_node == END:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when clearing state"
+ )
+ if saved is not None:
+ # tasks for this checkpoint
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # apply null writes
+ if null_writes := [
+ w[1:]
+ for w in saved.pending_writes or []
+ if w[0] == NULL_TASK_ID
+ ]:
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, null_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # apply writes from tasks that already ran
+ for tid, k, v in saved.pending_writes or []:
+ if k in (ERROR, INTERRUPT):
+ continue
+ if tid not in next_tasks:
+ continue
+ next_tasks[tid].writes.append((k, v))
+ # clear all current tasks
+ apply_writes(
+ checkpoint,
+ channels,
+ next_tasks.values(),
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ # save checkpoint
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, step),
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # act as an input
+ if as_node == INPUT:
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot apply multiple updates when updating as input"
+ )
+
+ if input_writes := deque(map_input(self.input_channels, values)):
+ apply_writes(
+ checkpoint,
+ channels,
+ [PregelTaskWrites((), INPUT, input_writes, [])],
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+
+ # apply input write to channels
+ next_step = (
+ step + 1
+ if saved and saved.metadata.get("step") is not None
+ else -1
+ )
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ create_checkpoint(checkpoint, channels, next_step),
+ {
+ "source": "input",
+ "step": next_step,
+ "parents": saved.metadata.get("parents", {})
+ if saved
+ else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions,
+ checkpoint["channel_versions"],
+ ),
+ )
+
+ # store the writes
+ await checkpointer.aput_writes(
+ next_config,
+ input_writes,
+ str(uuid5(UUID(checkpoint["id"]), INPUT)),
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+ else:
+ raise InvalidUpdateError(
+ f"Received no input writes for {self.input_channels}"
+ )
+
+ # no values, copy checkpoint
+ if as_node == "__copy__":
+ if len(updates) > 1:
+ raise InvalidUpdateError(
+ "Cannot copy checkpoint with multiple updates"
+ )
+
+ if saved is None:
+ raise InvalidUpdateError("Cannot copy a non-existent checkpoint")
+
+ next_checkpoint = create_checkpoint(checkpoint, None, step)
+
+ # copy checkpoint
+ next_config = await checkpointer.aput(
+ saved.parent_config
+ or patch_configurable(
+ saved.config, {CONFIG_KEY_CHECKPOINT_ID: None}
+ ),
+ next_checkpoint,
+ {
+ "source": "fork",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}),
+ },
+ {},
+ )
+
+ # we want to both clone a checkpoint and update state in one go.
+ # reuse the same task ID if possible.
+ if isinstance(values, list) and len(values) > 0:
+ # figure out the task IDs for the next update checkpoint
+ next_tasks = prepare_next_tasks(
+ next_checkpoint,
+ saved.pending_writes or [],
+ self.nodes,
+ channels,
+ managed,
+ next_config,
+ step + 2,
+ step + 4,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+
+ tasks_group_by = defaultdict(list)
+ user_group_by: dict[str, list[StateUpdate]] = defaultdict(list)
+
+ for task in next_tasks.values():
+ tasks_group_by[task.name].append(task.id)
+
+ for item in values:
+ if not isinstance(item, Sequence):
+ raise InvalidUpdateError(
+ f"Invalid update item: {item} when copying checkpoint"
+ )
+
+ values, as_node = item[:2]
+ user_group = user_group_by[as_node]
+ tasks_group = tasks_group_by[as_node]
+
+ target_idx = len(user_group)
+ task_id = (
+ tasks_group[target_idx]
+ if target_idx < len(tasks_group)
+ else None
+ )
+
+ user_group_by[as_node].append(
+ StateUpdate(values=values, as_node=as_node, task_id=task_id)
+ )
+
+ return await aperform_superstep(
+ patch_checkpoint_map(next_config, saved.metadata),
+ [item for lst in user_group_by.values() for item in lst],
+ )
+
+ return patch_checkpoint_map(
+ next_config, saved.metadata if saved else None
+ )
+
+ # task ids can be provided in the StateUpdate, but if not,
+ # we use the task id generated by prepare_next_tasks
+ node_to_task_ids: dict[str, deque[str]] = defaultdict(deque)
+ if saved is not None and saved.pending_writes is not None:
+ # we call prepare_next_tasks to discover the task IDs that
+ # would have been generated, so we can reuse them and
+ # properly populate task.result in state history
+ next_tasks = prepare_next_tasks(
+ checkpoint,
+ saved.pending_writes,
+ self.nodes,
+ channels,
+ managed,
+ saved.config,
+ step + 1,
+ step + 3,
+ for_execution=True,
+ store=self.store,
+ checkpointer=checkpointer,
+ manager=None,
+ )
+ # collect task ids to reuse so we can properly attach task results
+ for t in next_tasks.values():
+ node_to_task_ids[t.name].append(t.id)
+
+ valid_updates: list[tuple[str, dict[str, Any] | None, str | None]] = []
+ if len(updates) == 1:
+ values, as_node, task_id = updates[0]
+ # find last node that updated the state, if not provided
+ if as_node is None and len(self.nodes) == 1:
+ as_node = tuple(self.nodes)[0]
+ elif as_node is None and not saved:
+ if (
+ isinstance(self.input_channels, str)
+ and self.input_channels in self.nodes
+ ):
+ as_node = self.input_channels
+ elif as_node is None:
+ last_seen_by_node = sorted(
+ (v, n)
+ for n, seen in checkpoint["versions_seen"].items()
+ if n in self.nodes
+ for v in seen.values()
+ )
+ # if two nodes updated the state at the same time, it's ambiguous
+ if last_seen_by_node:
+ if len(last_seen_by_node) == 1:
+ as_node = last_seen_by_node[0][1]
+ elif last_seen_by_node[-1][0] != last_seen_by_node[-2][0]:
+ as_node = last_seen_by_node[-1][1]
+ if as_node is None:
+ raise InvalidUpdateError("Ambiguous update, specify as_node")
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+ valid_updates.append((as_node, values, task_id))
+ else:
+ for values, as_node, task_id in updates:
+ if as_node is None:
+ raise InvalidUpdateError(
+ "as_node is required when applying multiple updates"
+ )
+ if as_node not in self.nodes:
+ raise InvalidUpdateError(f"Node {as_node} does not exist")
+
+ valid_updates.append((as_node, values, task_id))
+
+ run_tasks: list[PregelTaskWrites] = []
+ run_task_ids: list[str] = []
+
+ for as_node, values, provided_task_id in valid_updates:
+ # create task to run all writers of the chosen node
+ writers = self.nodes[as_node].flat_writers
+ if not writers:
+ raise InvalidUpdateError(f"Node {as_node} has no writers")
+ writes: deque[tuple[str, Any]] = deque()
+ task = PregelTaskWrites((), as_node, writes, [INTERRUPT])
+ # get the task ids that were prepared for this node
+ # if a task id was provided in the StateUpdate, we use it
+ # otherwise, we use the next available task id
+ prepared_task_ids = node_to_task_ids.get(as_node, deque())
+ task_id = provided_task_id or (
+ prepared_task_ids.popleft()
+ if prepared_task_ids
+ else str(uuid5(UUID(checkpoint["id"]), INTERRUPT))
+ )
+ run_tasks.append(task)
+ run_task_ids.append(task_id)
+ run = RunnableSequence(*writers) if len(writers) > 1 else writers[0]
+ # execute task
+ await run.ainvoke(
+ values,
+ patch_config(
+ config,
+ run_name=self.name + "UpdateState",
+ configurable={
+ # deque.extend is thread-safe
+ CONFIG_KEY_SEND: writes.extend,
+ CONFIG_KEY_TASK_ID: task_id,
+ CONFIG_KEY_READ: partial(
+ local_read,
+ _scratchpad(
+ None,
+ [],
+ task_id,
+ "",
+ None,
+ step,
+ step + 2,
+ ),
+ channels,
+ managed,
+ task,
+ ),
+ },
+ ),
+ )
+ # save task writes
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # channel writes are saved to current checkpoint
+ channel_writes = [w for w in task.writes if w[0] != PUSH]
+ if saved and channel_writes:
+ await checkpointer.aput_writes(
+ checkpoint_config, channel_writes, task_id
+ )
+ # apply to checkpoint and save
+ apply_writes(
+ checkpoint,
+ channels,
+ run_tasks,
+ checkpointer.get_next_version,
+ self.trigger_to_nodes,
+ )
+ checkpoint = create_checkpoint(checkpoint, channels, step + 1)
+ # save checkpoint, after applying writes
+ next_config = await checkpointer.aput(
+ checkpoint_config,
+ checkpoint,
+ {
+ "source": "update",
+ "step": step + 1,
+ "parents": saved.metadata.get("parents", {}) if saved else {},
+ },
+ get_new_channel_versions(
+ checkpoint_previous_versions, checkpoint["channel_versions"]
+ ),
+ )
+ for task_id, task in zip(run_task_ids, run_tasks):
+ # save push writes
+ if push_writes := [w for w in task.writes if w[0] == PUSH]:
+ await checkpointer.aput_writes(next_config, push_writes, task_id)
+ return patch_checkpoint_map(next_config, saved.metadata if saved else None)
+
+ current_config = patch_configurable(
+ config, {CONFIG_KEY_THREAD_ID: str(config[CONF][CONFIG_KEY_THREAD_ID])}
+ )
+ for superstep in supersteps:
+ current_config = await aperform_superstep(current_config, superstep)
+ return current_config
+
+ def update_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ task_id: str | None = None,
+ ) -> RunnableConfig:
+ """Update the state of the graph with the given values, as if they came from
+ node `as_node`. If `as_node` is not provided, it will be set to the last node
+ that updated the state, if not ambiguous.
+ """
+ return self.bulk_update_state(config, [[StateUpdate(values, as_node, task_id)]])
+
+ async def aupdate_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any,
+ as_node: str | None = None,
+ task_id: str | None = None,
+ ) -> RunnableConfig:
+ """Asynchronously update the state of the graph with the given values, as if they came from
+ node `as_node`. If `as_node` is not provided, it will be set to the last node
+ that updated the state, if not ambiguous.
+ """
+ return await self.abulk_update_state(
+ config, [[StateUpdate(values, as_node, task_id)]]
+ )
+
+ def _defaults(
+ self,
+ config: RunnableConfig,
+ *,
+ stream_mode: StreamMode | Sequence[StreamMode],
+ print_mode: StreamMode | Sequence[StreamMode],
+ output_keys: str | Sequence[str] | None,
+ interrupt_before: All | Sequence[str] | None,
+ interrupt_after: All | Sequence[str] | None,
+ durability: Durability | None = None,
+ ) -> tuple[
+ set[StreamMode],
+ str | Sequence[str],
+ All | Sequence[str],
+ All | Sequence[str],
+ BaseCheckpointSaver | None,
+ BaseStore | None,
+ BaseCache | None,
+ Durability,
+ ]:
+ if config["recursion_limit"] < 1:
+ raise ValueError("recursion_limit must be at least 1")
+ if output_keys is None:
+ output_keys = self.stream_channels_asis
+ else:
+ validate_keys(output_keys, self.channels)
+ interrupt_before = interrupt_before or self.interrupt_before_nodes
+ interrupt_after = interrupt_after or self.interrupt_after_nodes
+ if isinstance(stream_mode, str):
+ stream_modes = {stream_mode}
+ else:
+ stream_modes = set(stream_mode)
+ if isinstance(print_mode, str):
+ stream_modes.add(print_mode)
+ else:
+ stream_modes.update(print_mode)
+ if self.checkpointer is False:
+ checkpointer: BaseCheckpointSaver | None = None
+ elif CONFIG_KEY_CHECKPOINTER in config.get(CONF, {}):
+ checkpointer = config[CONF][CONFIG_KEY_CHECKPOINTER]
+ elif self.checkpointer is True:
+ raise RuntimeError("checkpointer=True cannot be used for root graphs.")
+ else:
+ checkpointer = self.checkpointer
+ if isinstance(checkpointer, BaseCheckpointSaver):
+ checkpointer = self._apply_checkpointer_allowlist(checkpointer)
+ if checkpointer and not config.get(CONF):
+ raise ValueError(
+ "Checkpointer requires one or more of the following 'configurable' "
+ "keys: thread_id, checkpoint_ns, checkpoint_id"
+ )
+ if CONFIG_KEY_RUNTIME in config.get(CONF, {}):
+ store: BaseStore | None = config[CONF][CONFIG_KEY_RUNTIME].store
+ else:
+ store = self.store
+ if CONFIG_KEY_CACHE in config.get(CONF, {}):
+ cache: BaseCache | None = config[CONF][CONFIG_KEY_CACHE]
+ else:
+ cache = self.cache
+ if durability is None:
+ durability = config.get(CONF, {}).get(CONFIG_KEY_DURABILITY, "async")
+ return (
+ stream_modes,
+ output_keys,
+ interrupt_before,
+ interrupt_after,
+ checkpointer,
+ store,
+ cache,
+ durability,
+ )
+
+ @overload
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v2"],
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> Iterator[dict[str, Any] | Any]:
+ """Stream graph steps for a single input.
+
+ Args:
+ input: The input to the graph.
+ config: The configuration to use for the run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The mode to stream output, defaults to `self.stream_mode`.
+
+ Options are:
+
+ - `"values"`: Emit all values in the state after each step, including interrupts.
+ When used with functional API, values are emitted once at the end of the workflow.
+ - `"updates"`: Emit only the node or task names and updates returned by the nodes or tasks after each step.
+ If multiple updates are made in the same step (e.g. multiple nodes are run) then those updates are emitted separately.
+ - `"custom"`: Emit custom data from inside nodes or tasks using `StreamWriter`.
+ - `"messages"`: Emit LLM messages token-by-token together with metadata for any LLM invocations inside nodes or tasks.
+ - Will be emitted as 2-tuples `(LLM token, metadata)`.
+ - `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
+ - `"tasks"`: Emit events when tasks start and finish, including their results and errors.
+ - `"debug"`: Emit debug events with as much information as possible for each step.
+
+ You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
+ The streamed outputs will be tuples of `(mode, data)`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The keys to stream, defaults to all non-context channels.
+ interrupt_before: Nodes to interrupt before, defaults to all nodes in the graph.
+ interrupt_after: Nodes to interrupt after, defaults to all nodes in the graph.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ subgraphs: Whether to stream events from inside subgraphs, defaults to `False`.
+
+ If `True`, the events will be emitted as tuples `(namespace, data)`,
+ or `(namespace, mode, data)` if `stream_mode` is a list,
+ where `namespace` is a tuple with the path to the node where a subgraph is invoked,
+ e.g. `("parent_node:", "child_node:")`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+
+ Yields:
+ The output of each step in the graph. The output shape depends on the `stream_mode`.
+ """
+ if (checkpoint_during := kwargs.get("checkpoint_during")) is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed. Please use `durability` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if durability is not None:
+ raise ValueError(
+ "Cannot use both `checkpoint_during` and `durability` parameters. Please use `durability` instead."
+ )
+ durability = "async" if checkpoint_during else "exit"
+
+ if stream_mode is None:
+ # if being called as a node in another graph, default to values mode
+ # but don't overwrite stream_mode arg if provided
+ stream_mode = (
+ "values"
+ if config is not None and CONFIG_KEY_TASK_ID in config.get(CONF, {})
+ else self.stream_mode
+ )
+ if debug or self.debug:
+ print_mode = ["updates", "values"]
+
+ stream = SyncQueue()
+
+ config = ensure_config(self.config, config)
+ run_manager = None
+ try:
+ # assign defaults
+ (
+ stream_modes,
+ output_keys,
+ interrupt_before_,
+ interrupt_after_,
+ checkpointer,
+ store,
+ cache,
+ durability_,
+ ) = self._defaults(
+ config,
+ stream_mode=stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ )
+ callback_manager = get_callback_manager_for_config(config)
+ if "messages" in stream_modes and version != "v2":
+ # Strip any inherited v2 messages handler so a v1 stream
+ # does not get routed through the content-block event
+ # protocol. Leave v1 handlers in place — an outer
+ # stream(stream_mode="messages", subgraphs=True) relies
+ # on its inheritable handler to observe events emitted
+ # by inner stream(stream_mode="messages") calls.
+ callback_manager.handlers = [
+ h
+ for h in callback_manager.handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ callback_manager.inheritable_handlers = [
+ h
+ for h in callback_manager.inheritable_handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ if "ls_integration" not in callback_manager.metadata:
+ callback_manager.add_metadata({"ls_integration": "langgraph"})
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name", self.get_name()),
+ run_id=config.get("run_id"),
+ )
+ graph_callback_manager = get_sync_graph_callback_manager_for_config(
+ config,
+ run_id=run_manager.run_id,
+ )
+ if checkpointer is None and durability is not None:
+ warnings.warn(
+ "`durability` has no effect when no checkpointer is present.",
+ )
+ # set up subgraph checkpointing
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS] = recast_checkpoint_ns(ns)
+ # set up messages stream mode
+ if "messages" in stream_modes:
+ ns_ = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ use_stream_messages_v2 = bool(
+ version == "v2" and config[CONF].get(CONFIG_KEY_STREAM_MESSAGES_V2)
+ )
+ messages_handler_cls = (
+ StreamMessagesHandlerV2
+ if use_stream_messages_v2
+ else StreamMessagesHandler
+ )
+ run_manager.inheritable_handlers.append(
+ messages_handler_cls(
+ stream.put,
+ subgraphs,
+ parent_ns=tuple(ns_.split(NS_SEP)) if ns_ else None,
+ )
+ )
+
+ # set up tools stream mode
+ if "tools" in stream_modes:
+ ns_tools = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ run_manager.inheritable_handlers.append(
+ StreamToolCallHandler(
+ stream.put,
+ subgraphs,
+ parent_ns=tuple(ns_tools.split(NS_SEP)) if ns_tools else None,
+ )
+ )
+
+ # set up custom stream mode
+ if "custom" in stream_modes:
+
+ def stream_writer(c: Any) -> None:
+ stream.put(
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(
+ NS_SEP
+ )[:-1]
+ ),
+ "custom",
+ c,
+ )
+ )
+ elif CONFIG_KEY_STREAM in config[CONF]:
+ stream_writer = config[CONF][CONFIG_KEY_RUNTIME].stream_writer
+ else:
+
+ def stream_writer(c: Any) -> None:
+ pass
+
+ # set durability mode for subgraphs
+ if durability is not None:
+ config[CONF][CONFIG_KEY_DURABILITY] = durability_
+
+ # build server_info from metadata + parent runtime
+ parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ server_info = _build_server_info(config, parent_runtime)
+
+ runtime = Runtime(
+ context=_coerce_context(self.context_schema, context),
+ store=store,
+ stream_writer=stream_writer,
+ previous=None,
+ execution_info=None,
+ server_info=server_info,
+ control=control or parent_runtime.control or RunControl(),
+ )
+ runtime = parent_runtime.merge(runtime)
+ config[CONF][CONFIG_KEY_RUNTIME] = runtime
+
+ # resolve mappers for v2 stream coercion
+ _output_mapper = self._output_mapper if version == "v2" else None
+ _state_mapper = self._state_mapper if version == "v2" else None
+
+ def emit_graph_lifecycle_events(loop: SyncPregelLoop) -> None:
+ while (event := loop._pop_lifecycle_event()) is not None:
+ if isinstance(event, GraphResumeEvent):
+ graph_callback_manager.on_resume(
+ replace(event, run_id=graph_callback_manager.run_id)
+ )
+ else:
+ graph_callback_manager.on_interrupt(
+ replace(event, run_id=graph_callback_manager.run_id)
+ )
+
+ with SyncPregelLoop(
+ input,
+ stream=StreamProtocol(stream.put, stream_modes),
+ config=config,
+ store=store,
+ cache=cache,
+ checkpointer=checkpointer,
+ nodes=self.nodes,
+ specs=self.channels,
+ output_keys=output_keys,
+ input_keys=self.input_channels,
+ stream_keys=self.stream_channels_asis,
+ interrupt_before=interrupt_before_,
+ interrupt_after=interrupt_after_,
+ manager=run_manager,
+ durability=durability_,
+ trigger_to_nodes=self.trigger_to_nodes,
+ migrate_checkpoint=self._migrate_checkpoint,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ has_graph_lifecycle_callbacks=bool(graph_callback_manager.handlers),
+ ) as loop:
+ emit_graph_lifecycle_events(loop)
+ # create runner
+ runner = PregelRunner(
+ submit=config[CONF].get(
+ CONFIG_KEY_RUNNER_SUBMIT, weakref.WeakMethod(loop.submit)
+ ),
+ put_writes=weakref.WeakMethod(loop.put_writes),
+ node_finished=config[CONF].get(CONFIG_KEY_NODE_FINISHED),
+ node_error_handler_map=self.node_error_handler_map,
+ schedule_error_handler=loop.schedule_error_handler,
+ )
+ # enable subgraph streaming
+ if subgraphs:
+ loop.config[CONF][CONFIG_KEY_STREAM] = loop.stream
+ # enable concurrent streaming
+ get_waiter: Callable[[], concurrent.futures.Future[None]] | None = None
+ if (
+ self.stream_eager
+ or subgraphs
+ or "messages" in stream_modes
+ or "custom" in stream_modes
+ ):
+ # we are careful to have a single waiter live at any one time
+ # because on exit we increment semaphore count by exactly 1
+ waiter: concurrent.futures.Future | None = None
+ # because sync futures cannot be cancelled, we instead
+ # release the stream semaphore on exit, which will cause
+ # a pending waiter to return immediately
+ loop.stack.callback(stream._count.release)
+
+ def get_waiter() -> concurrent.futures.Future[None]:
+ nonlocal waiter
+ if waiter is None or waiter.done():
+ waiter = loop.submit(stream.wait)
+ return waiter
+ else:
+ return waiter
+
+ # Similarly to Bulk Synchronous Parallel / Pregel model
+ # computation proceeds in steps, while there are channel updates.
+ # Channel updates from step N are only visible in step N+1
+ # channels are guaranteed to be immutable for the duration of the step,
+ # with channel updates applied only at the transition between steps.
+ while loop.tick():
+ for task in loop.match_cached_writes():
+ loop.output_writes(task.id, task.writes, cached=True)
+ for _ in runner.tick(
+ [t for t in loop.tasks.values() if not t.writes],
+ timeout=self.step_timeout,
+ get_waiter=get_waiter,
+ schedule_task=loop.accept_push,
+ ):
+ # emit output
+ yield from _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get,
+ queue.Empty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ )
+ loop.after_tick()
+ emit_graph_lifecycle_events(loop)
+ # wait for checkpoint
+ if durability_ == "sync":
+ loop._put_checkpoint_fut.result()
+ emit_graph_lifecycle_events(loop)
+ # emit output
+ yield from _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get,
+ queue.Empty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ )
+ # handle exit
+ if loop.status == "out_of_steps":
+ msg = create_error_message(
+ message=(
+ f"Recursion limit of {config['recursion_limit']} reached "
+ "without hitting a stop condition. You can increase the "
+ "limit by setting the `recursion_limit` config key."
+ ),
+ error_code=ErrorCode.GRAPH_RECURSION_LIMIT,
+ )
+ raise GraphRecursionError(msg)
+ elif loop.status == "draining":
+ if loop.control is None:
+ raise RuntimeError("Draining status requires run control")
+ raise GraphDrained(loop.control.drain_reason or "shutdown")
+ # set final channel values as run output
+ run_manager.on_chain_end(loop.output)
+ except BaseException as e:
+ if run_manager is not None:
+ run_manager.on_chain_error(e)
+ raise
+
+ @overload
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v2"],
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ async def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ subgraphs: bool = False,
+ debug: bool | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Unpack[DeprecatedKwargs],
+ ) -> AsyncIterator[dict[str, Any] | Any]:
+ """Asynchronously stream graph steps for a single input.
+
+ Args:
+ input: The input to the graph.
+ config: The configuration to use for the run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The mode to stream output, defaults to `self.stream_mode`.
+
+ Options are:
+
+ - `"values"`: Emit all values in the state after each step, including interrupts.
+ When used with functional API, values are emitted once at the end of the workflow.
+ - `"updates"`: Emit only the node or task names and updates returned by the nodes or tasks after each step.
+ If multiple updates are made in the same step (e.g. multiple nodes are run) then those updates are emitted separately.
+ - `"custom"`: Emit custom data from inside nodes or tasks using `StreamWriter`.
+ - `"messages"`: Emit LLM messages token-by-token together with metadata for any LLM invocations inside nodes or tasks.
+ - Will be emitted as 2-tuples `(LLM token, metadata)`.
+ - `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
+ - `"tasks"`: Emit events when tasks start and finish, including their results and errors.
+ - `"debug"`: Emit debug events with as much information as possible for each step.
+
+ You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
+ The streamed outputs will be tuples of `(mode, data)`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The keys to stream, defaults to all non-context channels.
+ interrupt_before: Nodes to interrupt before, defaults to all nodes in the graph.
+ interrupt_after: Nodes to interrupt after, defaults to all nodes in the graph.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ subgraphs: Whether to stream events from inside subgraphs, defaults to `False`.
+
+ If `True`, the events will be emitted as tuples `(namespace, data)`,
+ or `(namespace, mode, data)` if `stream_mode` is a list,
+ where `namespace` is a tuple with the path to the node where a subgraph is invoked,
+ e.g. `("parent_node:", "child_node:")`.
+
+ See [LangGraph streaming guide](https://docs.langchain.com/oss/python/langgraph/streaming) for more details.
+
+ Yields:
+ The output of each step in the graph. The output shape depends on the `stream_mode`.
+ """
+ if (checkpoint_during := kwargs.get("checkpoint_during")) is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed. Please use `durability` instead.",
+ category=LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+ )
+ if durability is not None:
+ raise ValueError(
+ "Cannot use both `checkpoint_during` and `durability` parameters. Please use `durability` instead."
+ )
+ durability = "async" if checkpoint_during else "exit"
+
+ if stream_mode is None:
+ # if being called as a node in another graph, default to values mode
+ # but don't overwrite stream_mode arg if provided
+ stream_mode = (
+ "values"
+ if config is not None and CONFIG_KEY_TASK_ID in config.get(CONF, {})
+ else self.stream_mode
+ )
+ if debug or self.debug:
+ print_mode = ["updates", "values"]
+
+ stream = AsyncQueue()
+ aioloop = asyncio.get_running_loop()
+ stream_put = cast(
+ Callable[[StreamChunk], None],
+ partial(aioloop.call_soon_threadsafe, stream.put_nowait),
+ )
+
+ config = ensure_config(self.config, config)
+ run_manager = None
+ try:
+ # assign defaults
+ (
+ stream_modes,
+ output_keys,
+ interrupt_before_,
+ interrupt_after_,
+ checkpointer,
+ store,
+ cache,
+ durability_,
+ ) = self._defaults(
+ config,
+ stream_mode=stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ )
+ callback_manager = get_async_callback_manager_for_config(config)
+ if "messages" in stream_modes and version != "v2":
+ # Strip any inherited v2 messages handler so a v1 stream
+ # does not get routed through the content-block event
+ # protocol. Leave v1 handlers in place — an outer
+ # astream(stream_mode="messages", subgraphs=True) relies
+ # on its inheritable handler to observe events emitted
+ # by inner astream(stream_mode="messages") calls.
+ callback_manager.handlers = [
+ h
+ for h in callback_manager.handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ callback_manager.inheritable_handlers = [
+ h
+ for h in callback_manager.inheritable_handlers
+ if not isinstance(h, StreamMessagesHandlerV2)
+ ]
+ if "ls_integration" not in callback_manager.metadata:
+ callback_manager.add_metadata({"ls_integration": "langgraph"})
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name", self.get_name()),
+ run_id=config.get("run_id"),
+ )
+ graph_callback_manager = get_async_graph_callback_manager_for_config(
+ config,
+ run_id=run_manager.run_id,
+ )
+ # if running from astream_log() run each proc with streaming
+ do_stream = (
+ next(
+ (
+ True
+ for h in run_manager.handlers
+ if isinstance(h, _StreamingCallbackHandler)
+ and not isinstance(h, StreamMessagesHandler)
+ ),
+ False,
+ )
+ if _StreamingCallbackHandler is not None
+ else False
+ )
+ if checkpointer is None and durability is not None:
+ warnings.warn(
+ "`durability` has no effect when no checkpointer is present.",
+ )
+ # set up subgraph checkpointing
+ if self.checkpointer is True:
+ ns = cast(str, config[CONF][CONFIG_KEY_CHECKPOINT_NS])
+ config[CONF][CONFIG_KEY_CHECKPOINT_NS] = recast_checkpoint_ns(ns)
+ # set up messages stream mode
+ if "messages" in stream_modes:
+ # namespace can be None in a root level graph?
+ ns_ = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ use_stream_messages_v2 = bool(
+ version == "v2" and config[CONF].get(CONFIG_KEY_STREAM_MESSAGES_V2)
+ )
+ messages_handler_cls = (
+ StreamMessagesHandlerV2
+ if use_stream_messages_v2
+ else StreamMessagesHandler
+ )
+ run_manager.inheritable_handlers.append(
+ messages_handler_cls(
+ stream_put,
+ subgraphs,
+ parent_ns=tuple(ns_.split(NS_SEP)) if ns_ else None,
+ )
+ )
+
+ # set up tools stream mode
+ if "tools" in stream_modes:
+ ns_tools = cast(str | None, config[CONF].get(CONFIG_KEY_CHECKPOINT_NS))
+ run_manager.inheritable_handlers.append(
+ StreamToolCallHandler(
+ stream_put,
+ subgraphs,
+ parent_ns=tuple(ns_tools.split(NS_SEP)) if ns_tools else None,
+ )
+ )
+
+ # set up custom stream mode
+ def stream_writer(c: Any) -> None:
+ aioloop.call_soon_threadsafe(
+ stream.put_nowait,
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(NS_SEP)[
+ :-1
+ ]
+ ),
+ "custom",
+ c,
+ ),
+ )
+
+ if "custom" in stream_modes:
+
+ def stream_writer(c: Any) -> None:
+ aioloop.call_soon_threadsafe(
+ stream.put_nowait,
+ (
+ tuple(
+ get_config()[CONF][CONFIG_KEY_CHECKPOINT_NS].split(
+ NS_SEP
+ )[:-1]
+ ),
+ "custom",
+ c,
+ ),
+ )
+ elif CONFIG_KEY_STREAM in config[CONF]:
+ stream_writer = config[CONF][CONFIG_KEY_RUNTIME].stream_writer
+ else:
+
+ def stream_writer(c: Any) -> None:
+ pass
+
+ # set durability mode for subgraphs
+ if durability is not None:
+ config[CONF][CONFIG_KEY_DURABILITY] = durability_
+
+ # build server_info from metadata + parent runtime
+ parent_runtime = config[CONF].get(CONFIG_KEY_RUNTIME, DEFAULT_RUNTIME)
+ server_info = _build_server_info(config, parent_runtime)
+
+ runtime = Runtime(
+ context=_coerce_context(self.context_schema, context),
+ store=store,
+ stream_writer=stream_writer,
+ previous=None,
+ execution_info=None,
+ server_info=server_info,
+ control=control or parent_runtime.control or RunControl(),
+ )
+ runtime = parent_runtime.merge(runtime)
+ config[CONF][CONFIG_KEY_RUNTIME] = runtime
+
+ # resolve mappers for v2 stream coercion
+ _output_mapper = self._output_mapper if version == "v2" else None
+ _state_mapper = self._state_mapper if version == "v2" else None
+
+ async def aemit_graph_lifecycle_events(loop: AsyncPregelLoop) -> None:
+ while (event := loop._pop_lifecycle_event()) is not None:
+ if isinstance(event, GraphResumeEvent):
+ await graph_callback_manager.on_resume(
+ GraphResumeEvent(
+ run_id=graph_callback_manager.run_id,
+ status=event.status,
+ checkpoint_id=event.checkpoint_id,
+ checkpoint_ns=event.checkpoint_ns,
+ )
+ )
+ else:
+ await graph_callback_manager.on_interrupt(
+ GraphInterruptEvent(
+ run_id=graph_callback_manager.run_id,
+ status=event.status,
+ checkpoint_id=event.checkpoint_id,
+ checkpoint_ns=event.checkpoint_ns,
+ interrupts=event.interrupts,
+ )
+ )
+
+ async with AsyncPregelLoop(
+ input,
+ stream=StreamProtocol(stream.put_nowait, stream_modes),
+ config=config,
+ store=store,
+ cache=cache,
+ checkpointer=checkpointer,
+ nodes=self.nodes,
+ specs=self.channels,
+ output_keys=output_keys,
+ input_keys=self.input_channels,
+ stream_keys=self.stream_channels_asis,
+ interrupt_before=interrupt_before_,
+ interrupt_after=interrupt_after_,
+ manager=run_manager,
+ durability=durability_,
+ trigger_to_nodes=self.trigger_to_nodes,
+ migrate_checkpoint=self._migrate_checkpoint,
+ retry_policy=self.retry_policy,
+ cache_policy=self.cache_policy,
+ has_graph_lifecycle_callbacks=bool(graph_callback_manager.handlers),
+ ) as loop:
+ await aemit_graph_lifecycle_events(loop)
+ # create runner
+ runner = PregelRunner(
+ submit=config[CONF].get(
+ CONFIG_KEY_RUNNER_SUBMIT, weakref.WeakMethod(loop.submit)
+ ),
+ put_writes=weakref.WeakMethod(loop.put_writes),
+ use_astream=do_stream,
+ node_finished=config[CONF].get(CONFIG_KEY_NODE_FINISHED),
+ node_error_handler_map=self.node_error_handler_map,
+ aschedule_error_handler=loop.aschedule_error_handler,
+ )
+ # enable subgraph streaming
+ if subgraphs:
+ loop.config[CONF][CONFIG_KEY_STREAM] = StreamProtocol(
+ stream_put, stream_modes
+ )
+ # enable concurrent streaming
+ get_waiter: Callable[[], asyncio.Task[None]] | None = None
+ _cleanup_waiter: Callable[[], Awaitable[None]] | None = None
+ if (
+ self.stream_eager
+ or subgraphs
+ or "messages" in stream_modes
+ or "custom" in stream_modes
+ ):
+ # Keep a single waiter task alive; ensure cleanup on exit.
+ waiter: asyncio.Task[None] | None = None
+
+ def get_waiter() -> asyncio.Task[None]:
+ nonlocal waiter
+ if waiter is None or waiter.done():
+ waiter = aioloop.create_task(stream.wait())
+
+ def _clear(t: asyncio.Task[None]) -> None:
+ nonlocal waiter
+ if waiter is t:
+ waiter = None
+
+ waiter.add_done_callback(_clear)
+ return waiter
+
+ async def _cleanup_waiter() -> None:
+ """Wake pending waiter and/or cancel+await to avoid pending tasks."""
+ nonlocal waiter
+ # Try to wake via semaphore like SyncPregelLoop
+ with contextlib.suppress(Exception):
+ if hasattr(stream, "_count"):
+ stream._count.release()
+ t = waiter
+ waiter = None
+ if t is not None and not t.done():
+ t.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await t
+
+ # Similarly to Bulk Synchronous Parallel / Pregel model
+ # computation proceeds in steps, while there are channel updates
+ # channel updates from step N are only visible in step N+1
+ # channels are guaranteed to be immutable for the duration of the step,
+ # with channel updates applied only at the transition between steps
+ try:
+ while loop.tick():
+ for task in await loop.amatch_cached_writes():
+ loop.output_writes(task.id, task.writes, cached=True)
+ async for _ in runner.atick(
+ [t for t in loop.tasks.values() if not t.writes],
+ timeout=self.step_timeout,
+ get_waiter=get_waiter,
+ schedule_task=loop.aaccept_push,
+ ):
+ # emit output
+ for o in _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get_nowait,
+ asyncio.QueueEmpty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ ):
+ yield o
+ loop.after_tick()
+ await aemit_graph_lifecycle_events(loop)
+ # wait for checkpoint
+ if durability_ == "sync":
+ await cast(asyncio.Future, loop._put_checkpoint_fut)
+ finally:
+ # ensure waiter doesn't remain pending on cancel/shutdown
+ if _cleanup_waiter is not None:
+ await _cleanup_waiter()
+
+ await aemit_graph_lifecycle_events(loop)
+
+ # emit output
+ for o in _output(
+ stream_mode,
+ print_mode,
+ subgraphs,
+ stream.get_nowait,
+ asyncio.QueueEmpty,
+ version,
+ _output_mapper,
+ _state_mapper,
+ ):
+ yield o
+ # handle exit
+ if loop.status == "out_of_steps":
+ msg = create_error_message(
+ message=(
+ f"Recursion limit of {config['recursion_limit']} reached "
+ "without hitting a stop condition. You can increase the "
+ "limit by setting the `recursion_limit` config key."
+ ),
+ error_code=ErrorCode.GRAPH_RECURSION_LIMIT,
+ )
+ raise GraphRecursionError(msg)
+ elif loop.status == "draining":
+ if loop.control is None:
+ raise RuntimeError("Draining status requires run control")
+ raise GraphDrained(loop.control.drain_reason or "shutdown")
+ # set final channel values as run output
+ await run_manager.on_chain_end(loop.output)
+ except BaseException as e:
+ if run_manager is not None:
+ await asyncio.shield(run_manager.on_chain_error(e))
+ raise
+
+ @beta(message="The v3 streaming protocol on Pregel is experimental.")
+ def _pregel_stream_v3(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Internal v3 sync streaming implementation. Public entry: stream_events(version='v3').
+
+ Extra keyword arguments are forwarded to the underlying ``stream(...)``
+ call. The dispatcher in ``stream_events`` rejects ``stream_mode`` and
+ ``subgraphs`` since v3 owns them (``stream_mode`` is derived from the
+ transformer mux; ``subgraphs`` is always True so nested namespaces
+ flow through scoped muxes).
+
+ !!! warning
+
+ The v3 streaming protocol is experimental and may change.
+ """
+ parent_ns = _resolve_parent_ns(self.config, config)
+ compiled_factories = _normalize_stream_transformer_factories(
+ self.stream_transformers
+ )
+ extra_factories = _normalize_stream_transformer_factories(transformers)
+ mux = StreamMux(
+ factories=[
+ ValuesTransformer,
+ MessagesTransformer,
+ LifecycleTransformer,
+ SubgraphTransformer,
+ *compiled_factories,
+ *extra_factories,
+ ],
+ scope=parent_ns,
+ is_async=False,
+ )
+ graph_iter = iter(
+ self.stream(
+ input,
+ patch_configurable(config, {CONFIG_KEY_STREAM_MESSAGES_V2: True}),
+ stream_mode=_collect_stream_modes(mux),
+ subgraphs=True,
+ version="v2",
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ **kwargs,
+ )
+ )
+ return GraphRunStream(graph_iter, mux)
+
+ @beta(message="The v3 streaming protocol on Pregel is experimental.")
+ async def _apregel_stream_v3(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Internal v3 async streaming implementation. Public entry: astream_events(version='v3').
+
+ Extra keyword arguments are forwarded to the underlying ``astream(...)``
+ call. The dispatcher in ``astream_events`` rejects ``stream_mode`` and
+ ``subgraphs`` since v3 owns them (``stream_mode`` is derived from the
+ transformer mux; ``subgraphs`` is always True so nested namespaces
+ flow through scoped muxes).
+
+ !!! warning
+
+ The v3 streaming protocol is experimental and may change.
+ """
+ parent_ns = _resolve_parent_ns(self.config, config)
+ compiled_factories = _normalize_stream_transformer_factories(
+ self.stream_transformers
+ )
+ extra_factories = _normalize_stream_transformer_factories(transformers)
+ mux = StreamMux(
+ factories=[
+ ValuesTransformer,
+ MessagesTransformer,
+ LifecycleTransformer,
+ SubgraphTransformer,
+ *compiled_factories,
+ *extra_factories,
+ ],
+ scope=parent_ns,
+ is_async=True,
+ )
+ graph_aiter = self.astream(
+ input,
+ patch_configurable(config, {CONFIG_KEY_STREAM_MESSAGES_V2: True}),
+ stream_mode=_collect_stream_modes(mux),
+ subgraphs=True,
+ version="v2",
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ **kwargs,
+ ).__aiter__()
+ return AsyncGraphRunStream(graph_aiter, mux)
+
+ @overload
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any: ...
+
+ def stream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Stream events from this graph.
+
+ For `version="v1"` / `"v2"`, yields `StreamEvent` dicts (see
+ `Runnable.stream_events`). For `version="v3"`, returns a
+ `GraphRunStream` whose typed projections the caller drives by
+ iterating — no background thread.
+
+ !!! warning
+
+ The `version="v3"` API is experimental and may change.
+
+ Builds a `StreamMux` from the built-in transformers, this
+ graph's compile-time `stream_transformers`, and any additional
+ `transformers=` supplied at the call site. `run.output`,
+ `run.interrupted`, and `run.interrupts` work regardless of
+ which transformers are registered.
+
+ Note:
+ Nesting v1 `stream(stream_mode="messages")` inside a node
+ of a `stream_events(version="v3")` run is not fully
+ supported. The outer v3 messages handler reroutes
+ `BaseChatModel.invoke` through the v2 event protocol, so
+ the inner v1 handler does not see `on_llm_new_token`
+ chunks. The inner stream still yields a finalized message
+ via `on_llm_end`. Use `stream_events(version="v3")` for the
+ inner graph as well, or call `chat_model.stream(...)`
+ explicitly, to get token-level streaming.
+
+ Args:
+ input: Graph input.
+ config: Optional runnable config.
+ version: Streaming-event schema version. `"v3"` selects the
+ content-block-centric streaming protocol.
+ interrupt_before: Nodes to interrupt before, if any. Only
+ used for `version="v3"`.
+ interrupt_after: Nodes to interrupt after, if any. Only
+ used for `version="v3"`.
+ control: Optional run control used to request cooperative
+ drain. Only used for `version="v3"`.
+ transformers: Extra transformer classes or configured
+ factories appended after compile-time
+ `stream_transformers`. Factories are called as
+ `factory(scope)` so they can propagate to subgraph
+ scopes. Only used for `version="v3"`.
+ **kwargs: For `version="v1"`/`"v2"`, forwarded to
+ `Runnable.stream_events`. For `version="v3"`, forwarded
+ to the underlying `stream(...)` call (e.g. `context`,
+ `durability`, `output_keys`, `print_mode`, `debug`).
+ `stream_mode` and `subgraphs` are not accepted under
+ `version="v3"` and raise `TypeError` if supplied; v3
+ owns them.
+
+ Returns:
+ For `version="v3"`, a `GraphRunStream` the caller iterates
+ to drive the run. Otherwise an `Iterator[StreamEvent]`.
+ """
+ if version == "v3":
+ _reject_v3_invariant_kwargs(kwargs)
+ return self._pregel_stream_v3(
+ input,
+ config,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ transformers=transformers,
+ **kwargs,
+ )
+ return super().stream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ def astream_events(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ control: RunControl | None = None,
+ transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Async variant of `stream_events`.
+
+ For `version="v3"`, returns an `AsyncGraphRunStream` whose
+ projections can be awaited concurrently; each subscribed cursor
+ drives the pump when its buffer is empty. The same nesting
+ limitation as the sync path applies — see `stream_events` for
+ details.
+
+ !!! warning
+
+ The `version="v3"` API is experimental and may change.
+
+ See `stream_events` for full argument and return documentation.
+ """
+ if version == "v3":
+ _reject_v3_invariant_kwargs(kwargs)
+ return self._apregel_stream_v3(
+ input,
+ config,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ control=control,
+ transformers=transformers,
+ **kwargs,
+ )
+ return super().astream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: Literal["values"] = ...,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> list[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Run the graph with a single input and config.
+
+ Args:
+ input: The input data for the graph. It can be a dictionary or any other type.
+ config: The configuration for the graph run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The stream mode for the graph run.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The output keys to retrieve from the graph run.
+ interrupt_before: The nodes to interrupt the graph run before.
+ interrupt_after: The nodes to interrupt the graph run after.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts when
+ `stream_mode` is not `"values"`.
+ **kwargs: Additional keyword arguments to pass to the graph run.
+
+ Returns:
+ The output of the graph run. If `stream_mode` is `"values"`, it returns the latest output.
+ If `stream_mode` is not `"values"`, it returns a list of output chunks.
+ """
+ output_keys = output_keys if output_keys is not None else self.output_channels
+
+ latest: dict[str, Any] | Any = None
+ chunks: list[dict[str, Any] | Any] = []
+ interrupts: list[Interrupt] = []
+
+ if version == "v2":
+ # v2: values stream parts carry interrupts directly
+ for chunk in self.stream(
+ input,
+ config,
+ context=context,
+ stream_mode="values" if stream_mode == "values" else stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ version=version,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ latest = chunk["data"]
+ if chunk_ints := chunk.get("interrupts", ()):
+ interrupts.extend(chunk_ints) # type: ignore[arg-type]
+ else:
+ chunks.append(chunk)
+ else:
+ # v1: collect interrupts from updates stream
+ for chunk in self.stream(
+ input,
+ config,
+ context=context,
+ stream_mode=(
+ ["updates", "values"] if stream_mode == "values" else stream_mode
+ ),
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ if len(chunk) == 2:
+ mode, payload = cast(tuple[StreamMode, Any], chunk)
+ else:
+ _, mode, payload = cast(
+ tuple[tuple[str, ...], StreamMode, Any], chunk
+ )
+ if (
+ mode == "updates"
+ and isinstance(payload, dict)
+ and (ints := payload.get(INTERRUPT)) is not None
+ ):
+ interrupts.extend(ints)
+ elif mode == "values":
+ latest = payload
+ else:
+ chunks.append(chunk)
+
+ if stream_mode == "values":
+ if version == "v2":
+ return GraphOutput(value=latest, interrupts=tuple(interrupts))
+ if interrupts:
+ return (
+ {**latest, INTERRUPT: interrupts}
+ if isinstance(latest, dict)
+ else {INTERRUPT: interrupts}
+ )
+ return latest
+ else:
+ return chunks
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: Literal["values"] = ...,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode,
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> list[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode = "values",
+ print_mode: StreamMode | Sequence[StreamMode] = (),
+ output_keys: str | Sequence[str] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ durability: Durability | None = None,
+ control: RunControl | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Asynchronously run the graph with a single input and config.
+
+ Args:
+ input: The input data for the graph. It can be a dictionary or any other type.
+ config: The configuration for the graph run.
+ context: The static context to use for the run.
+ !!! version-added "Added in version 0.6.0"
+ stream_mode: The stream mode for the graph run.
+ print_mode: Accepts the same values as `stream_mode`, but only prints the output to the console, for debugging purposes.
+
+ Does not affect the output of the graph in any way.
+ output_keys: The output keys to retrieve from the graph run.
+ interrupt_before: The nodes to interrupt the graph run before.
+ interrupt_after: The nodes to interrupt the graph run after.
+ durability: The durability mode for the graph execution, defaults to `"async"`.
+
+ Options are:
+
+ - `"sync"`: Changes are persisted synchronously before the next step starts.
+ - `"async"`: Changes are persisted asynchronously while the next step executes.
+ - `"exit"`: Changes are persisted only when the graph exits.
+ control: Optional run control used to request cooperative drain.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts when
+ `stream_mode` is not `"values"`.
+ **kwargs: Additional keyword arguments to pass to the graph run.
+
+ Returns:
+ The output of the graph run. If `stream_mode` is `"values"`, it returns the latest output.
+ If `stream_mode` is not `"values"`, it returns a list of output chunks.
+ """
+ output_keys = output_keys if output_keys is not None else self.output_channels
+
+ latest: dict[str, Any] | Any = None
+ chunks: list[dict[str, Any] | Any] = []
+ interrupts: list[Interrupt] = []
+
+ if version == "v2":
+ # v2: values stream parts carry interrupts directly
+ async for chunk in self.astream(
+ input,
+ config,
+ context=context,
+ stream_mode="values" if stream_mode == "values" else stream_mode,
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ version=version,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ latest = chunk["data"]
+ if chunk_ints := chunk.get("interrupts", ()):
+ interrupts.extend(chunk_ints) # type: ignore[arg-type]
+ else:
+ chunks.append(chunk)
+ else:
+ # v1: collect interrupts from updates stream
+ async for chunk in self.astream(
+ input,
+ config,
+ context=context,
+ stream_mode=(
+ ["updates", "values"] if stream_mode == "values" else stream_mode
+ ),
+ print_mode=print_mode,
+ output_keys=output_keys,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ durability=durability,
+ control=control,
+ **kwargs,
+ ):
+ if stream_mode == "values":
+ if len(chunk) == 2:
+ mode, payload = cast(tuple[StreamMode, Any], chunk)
+ else:
+ _, mode, payload = cast(
+ tuple[tuple[str, ...], StreamMode, Any], chunk
+ )
+ if (
+ mode == "updates"
+ and isinstance(payload, dict)
+ and (ints := payload.get(INTERRUPT)) is not None
+ ):
+ interrupts.extend(ints)
+ elif mode == "values":
+ latest = payload
+ else:
+ chunks.append(chunk)
+
+ if stream_mode == "values":
+ if version == "v2":
+ return GraphOutput(value=latest, interrupts=tuple(interrupts))
+ if interrupts:
+ return (
+ {**latest, INTERRUPT: interrupts}
+ if isinstance(latest, dict)
+ else {INTERRUPT: interrupts}
+ )
+ return latest
+ else:
+ return chunks
+
+ def clear_cache(self, nodes: Sequence[str] | None = None) -> None:
+ """Clear the cache for the given nodes."""
+ if not self.cache:
+ raise ValueError("No cache is set for this graph. Cannot clear cache.")
+ nodes = nodes or self.nodes.keys()
+ # collect namespaces to clear
+ namespaces: list[tuple[str, ...]] = []
+ for node in nodes:
+ if node in self.nodes:
+ namespaces.append(
+ (
+ CACHE_NS_WRITES,
+ (identifier(self.nodes[node]) or "__dynamic__"),
+ node,
+ ),
+ )
+ # clear cache
+ self.cache.clear(namespaces)
+
+ async def aclear_cache(self, nodes: Sequence[str] | None = None) -> None:
+ """Asynchronously clear the cache for the given nodes."""
+ if not self.cache:
+ raise ValueError("No cache is set for this graph. Cannot clear cache.")
+ nodes = nodes or self.nodes.keys()
+ # collect namespaces to clear
+ namespaces: list[tuple[str, ...]] = []
+ for node in nodes:
+ if node in self.nodes:
+ namespaces.append(
+ (
+ CACHE_NS_WRITES,
+ (identifier(self.nodes[node]) or "__dynamic__"),
+ node,
+ ),
+ )
+ # clear cache
+ await self.cache.aclear(namespaces)
+
+
+def _trigger_to_nodes(nodes: dict[str, PregelNode]) -> Mapping[str, Sequence[str]]:
+ """Index from a trigger to nodes that depend on it."""
+ trigger_to_nodes: defaultdict[str, list[str]] = defaultdict(list)
+ for name, node in nodes.items():
+ for trigger in node.triggers:
+ trigger_to_nodes[trigger].append(name)
+ return dict(trigger_to_nodes)
+
+
+def _output(
+ stream_mode: StreamMode | Sequence[StreamMode],
+ print_mode: StreamMode | Sequence[StreamMode],
+ stream_subgraphs: bool,
+ getter: Callable[[], tuple[tuple[str, ...], str, Any]],
+ empty_exc: type[Exception],
+ version: Literal["v1", "v2"] = "v1",
+ output_mapper: Callable[[Any], Any] | None = None,
+ state_mapper: Callable[[Any], Any] | None = None,
+) -> Iterator:
+ while True:
+ try:
+ ns, mode, payload = getter()
+ except empty_exc:
+ break
+ if mode in print_mode:
+ if stream_subgraphs and ns:
+ print(
+ " ".join(
+ (
+ get_bolded_text(f"[{mode}]"),
+ get_colored_text(f"[graph={ns}]", color="yellow"),
+ repr(payload),
+ )
+ )
+ )
+ else:
+ print(
+ " ".join(
+ (
+ get_bolded_text(f"[{mode}]"),
+ repr(payload),
+ )
+ )
+ )
+ if mode in stream_mode:
+ if version == "v2":
+ if mode == "values":
+ # pop __interrupt__ into typed field, coerce data
+ ints: tuple[Interrupt, ...] = ()
+ if isinstance(payload, dict):
+ ints = payload.pop(INTERRUPT, ())
+ if output_mapper:
+ payload = output_mapper(payload)
+ yield {"type": mode, "ns": ns, "data": payload, "interrupts": ints}
+ elif mode in ("checkpoints", "debug"):
+ # coerce state values in checkpoint/debug payloads
+ if state_mapper:
+ _coerce_checkpoint_values(payload, state_mapper)
+ yield {"type": mode, "ns": ns, "data": payload}
+ else:
+ yield {"type": mode, "ns": ns, "data": payload}
+ elif stream_subgraphs and isinstance(stream_mode, list):
+ yield (ns, mode, payload)
+ elif isinstance(stream_mode, list):
+ yield (mode, payload)
+ elif stream_subgraphs:
+ yield (ns, payload)
+ else:
+ yield payload
+
+
+def _coerce_checkpoint_values(payload: Any, mapper: Callable[[Any], Any]) -> None:
+ """Coerce `values` dicts inside checkpoint or debug payloads in-place.
+
+ Skips the initial checkpoint (where next contains ``__start__``) because
+ not all channels are populated yet and coercion would fail.
+ """
+ _START = "__start__"
+ # debug wrapper: {"type": "checkpoint", "payload": {"values": dict, ...}}
+ if (
+ isinstance(payload, dict)
+ and payload.get("type") == "checkpoint"
+ and isinstance(payload.get("payload"), dict)
+ and isinstance(payload["payload"].get("values"), dict)
+ and _START not in payload["payload"].get("next", ())
+ ):
+ payload["payload"]["values"] = mapper(payload["payload"]["values"])
+ # direct checkpoint payload: {"values": dict, ...}
+ elif (
+ isinstance(payload, dict)
+ and isinstance(payload.get("values"), dict)
+ and _START not in payload.get("next", ())
+ ):
+ payload["values"] = mapper(payload["values"])
+
+
+def _resolve_parent_ns(
+ graph_config: RunnableConfig | None, call_config: RunnableConfig | None
+) -> tuple[str, ...]:
+ """Return the checkpoint namespace the caller is running under.
+
+ `stream_events(version="v3")` uses this to scope its native projections
+ (`ValuesTransformer`, `MessagesTransformer`) to events emitted at
+ the run's own level. A root call resolves to `()`; a call made
+ from inside a node carries the outer graph's task namespace so the
+ projection still matches its own root-level events.
+ """
+ merged = ensure_config(graph_config, call_config)
+ ns = merged.get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS)
+ if not ns:
+ return ()
+ return tuple(ns.split(NS_SEP))
+
+
+def _build_server_info(
+ config: RunnableConfig, parent_runtime: Runtime[Any]
+) -> ServerInfo | None:
+ """Build ServerInfo from config configurable.
+
+ The server puts assistant_id/graph_id in config configurable and the
+ authenticated user dict in configurable["langgraph_auth_user"].
+ """
+ configurable = config.get(CONF) or {}
+ assistant_id = configurable.get("assistant_id")
+ graph_id = configurable.get("graph_id")
+
+ # Read authenticated user from configurable (set by LangGraph Server).
+ # We prefer isinstance(BaseUser) but fall back to hasattr("identity")
+ # because the server's ProxyUser provides `permissions` via __getattr__,
+ # which Python's runtime_checkable Protocol check doesn't see.
+ auth_user_data = configurable.get("langgraph_auth_user")
+ user: BaseUser | None = None
+ if auth_user_data is not None:
+ if isinstance(auth_user_data, BaseUser) or hasattr(auth_user_data, "identity"):
+ user = cast(BaseUser, auth_user_data)
+
+ if assistant_id is not None or graph_id is not None or user is not None:
+ return ServerInfo(
+ assistant_id=str(assistant_id) if assistant_id else "",
+ graph_id=str(graph_id) if graph_id else "",
+ user=user,
+ )
+ return None
+
+
+def _coerce_context(
+ context_schema: type[ContextT] | None, context: Any
+) -> ContextT | None:
+ """Coerce context input to the appropriate schema type.
+
+ If context is a dict and context_schema is a dataclass or pydantic model, we coerce.
+ Else, we return the context as-is.
+
+ Args:
+ context_schema: The schema type to coerce to (BaseModel, dataclass, or TypedDict)
+ context: The context value to coerce
+
+ Returns:
+ The coerced context value or None if context is None
+ """
+ if context is None:
+ return None
+
+ if context_schema is None:
+ return context
+
+ schema_is_class = issubclass(context_schema, BaseModel) or is_dataclass(
+ context_schema
+ )
+ if isinstance(context, dict) and schema_is_class:
+ return context_schema(**context) # type: ignore[misc]
+
+ return cast(ContextT, context)
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/protocol.py b/python/user_packages/Python313/site-packages/langgraph/pregel/protocol.py
new file mode 100644
index 0000000000000000000000000000000000000000..259554ddb0d6afaaeba1a40537486716792a8780
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/protocol.py
@@ -0,0 +1,288 @@
+from __future__ import annotations
+
+from abc import abstractmethod
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from typing import Any, Generic, Literal, cast, overload
+
+from langchain_core.runnables import Runnable, RunnableConfig
+from langchain_core.runnables.graph import Graph as DrawableGraph
+from typing_extensions import Self
+
+from langgraph.types import (
+ All,
+ Command,
+ GraphOutput,
+ StateSnapshot,
+ StateUpdate,
+ StreamMode,
+ StreamPart,
+)
+from langgraph.typing import ContextT, InputT, OutputT, StateT
+
+__all__ = ("PregelProtocol", "StreamProtocol")
+
+
+class PregelProtocol(Runnable[InputT, Any], Generic[StateT, ContextT, InputT, OutputT]):
+ @abstractmethod
+ def with_config(
+ self, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Self: ...
+
+ @abstractmethod
+ def get_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ ) -> DrawableGraph: ...
+
+ @abstractmethod
+ async def aget_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ ) -> DrawableGraph: ...
+
+ @abstractmethod
+ def get_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot: ...
+
+ @abstractmethod
+ async def aget_state(
+ self, config: RunnableConfig, *, subgraphs: bool = False
+ ) -> StateSnapshot: ...
+
+ @abstractmethod
+ def get_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> Iterator[StateSnapshot]: ...
+
+ @abstractmethod
+ def aget_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[StateSnapshot]: ...
+
+ @abstractmethod
+ def bulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig: ...
+
+ @abstractmethod
+ async def abulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: Sequence[Sequence[StateUpdate]],
+ ) -> RunnableConfig: ...
+
+ @abstractmethod
+ def update_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ ) -> RunnableConfig: ...
+
+ @abstractmethod
+ async def aupdate_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ ) -> RunnableConfig: ...
+
+ @overload
+ @abstractmethod
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v2"],
+ ) -> Iterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ @abstractmethod
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v1"] = ...,
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ @abstractmethod
+ def stream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v1", "v2"] = "v1",
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ @overload
+ @abstractmethod
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v2"],
+ ) -> AsyncIterator[StreamPart[StateT, OutputT]]: ...
+
+ @overload
+ @abstractmethod
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v1"] = ...,
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ @abstractmethod
+ def astream(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ version: Literal["v1", "v2"] = "v1",
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ @overload
+ @abstractmethod
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v2"],
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ @abstractmethod
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v1"] = ...,
+ ) -> dict[str, Any] | Any: ...
+
+ @abstractmethod
+ def invoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ ) -> dict[str, Any] | Any: ...
+
+ @overload
+ @abstractmethod
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v2"],
+ ) -> GraphOutput[OutputT]: ...
+
+ @overload
+ @abstractmethod
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v1"] = ...,
+ ) -> dict[str, Any] | Any: ...
+
+ @abstractmethod
+ async def ainvoke(
+ self,
+ input: InputT | Command | None,
+ config: RunnableConfig | None = None,
+ *,
+ context: ContextT | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ ) -> dict[str, Any] | Any: ...
+
+
+StreamChunk = tuple[tuple[str, ...], str, Any]
+
+
+class StreamProtocol:
+ __slots__ = ("modes", "__call__")
+
+ modes: set[StreamMode]
+
+ __call__: Callable[[Self, StreamChunk], None]
+
+ def __init__(
+ self,
+ __call__: Callable[[StreamChunk], None],
+ modes: set[StreamMode],
+ ) -> None:
+ self.__call__ = cast(Callable[[Self, StreamChunk], None], __call__)
+ self.modes = modes
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/remote.py b/python/user_packages/Python313/site-packages/langgraph/pregel/remote.py
new file mode 100644
index 0000000000000000000000000000000000000000..973768a4ad4444dbe3ba7b2275ac34c78bc13671
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/remote.py
@@ -0,0 +1,1191 @@
+from __future__ import annotations
+
+import logging
+from collections.abc import AsyncIterator, Iterator, Sequence
+from dataclasses import asdict
+from typing import (
+ Any,
+ Literal,
+ cast,
+ overload,
+)
+from uuid import UUID
+
+import langsmith as ls
+from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables.graph import (
+ Edge as DrawableEdge,
+)
+from langchain_core.runnables.graph import (
+ Graph as DrawableGraph,
+)
+from langchain_core.runnables.graph import (
+ Node as DrawableNode,
+)
+from langgraph.checkpoint.base import CheckpointMetadata
+from langgraph_sdk.client import (
+ LangGraphClient,
+ SyncLangGraphClient,
+ get_client,
+ get_sync_client,
+)
+from langgraph_sdk.schema import (
+ Checkpoint,
+ Context,
+ QueryParamTypes,
+ ThreadState,
+)
+from langgraph_sdk.schema import (
+ Command as CommandSDK,
+)
+from langgraph_sdk.schema import (
+ StreamMode as StreamModeSDK,
+)
+from typing_extensions import Self
+
+from langgraph._internal._config import merge_configs
+from langgraph._internal._constants import (
+ CONF,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_STREAM,
+ CONFIG_KEY_TASK_ID,
+ INTERRUPT,
+ NS_SEP,
+)
+from langgraph.errors import GraphInterrupt, ParentCommand
+from langgraph.pregel.protocol import PregelProtocol, StreamProtocol
+from langgraph.types import (
+ All,
+ Command,
+ GraphOutput,
+ Interrupt,
+ PregelTask,
+ StateSnapshot,
+ StreamMode,
+ StreamPart,
+)
+
+logger = logging.getLogger(__name__)
+
+__all__ = ("RemoteGraph", "RemoteException")
+
+_CONF_DROPLIST = frozenset(
+ (
+ CONFIG_KEY_CHECKPOINT_MAP,
+ CONFIG_KEY_CHECKPOINT_ID,
+ CONFIG_KEY_CHECKPOINT_NS,
+ CONFIG_KEY_TASK_ID,
+ ),
+)
+
+
+def _sanitize_config_value(v: Any) -> Any:
+ """Recursively sanitize a config value to ensure it contains only primitives."""
+ if isinstance(v, (str, int, float, bool, UUID)):
+ return v
+ elif isinstance(v, dict):
+ sanitized_dict = {}
+ for k, val in v.items():
+ if isinstance(k, str):
+ sanitized_value = _sanitize_config_value(val)
+ if sanitized_value is not None:
+ sanitized_dict[k] = sanitized_value
+ return sanitized_dict
+ elif isinstance(v, (list, tuple)):
+ sanitized_list = []
+ for item in v:
+ sanitized_item = _sanitize_config_value(item)
+ if sanitized_item is not None:
+ sanitized_list.append(sanitized_item)
+ return sanitized_list
+ return None
+
+
+class RemoteException(Exception):
+ """Exception raised when an error occurs in the remote graph."""
+
+ pass
+
+
+class RemoteGraph(PregelProtocol):
+ """The `RemoteGraph` class is a client implementation for calling remote
+ APIs that implement the LangGraph Server API specification.
+
+ For example, the `RemoteGraph` class can be used to call APIs from deployments
+ on LangSmith Deployment.
+
+ `RemoteGraph` behaves the same way as a `Graph` and can be used directly as
+ a node in another `Graph`.
+ """
+
+ assistant_id: str
+ name: str | None
+
+ def __init__(
+ self,
+ assistant_id: str, # graph_id
+ /,
+ *,
+ url: str | None = None,
+ api_key: str | None = None,
+ headers: dict[str, str] | None = None,
+ client: LangGraphClient | None = None,
+ sync_client: SyncLangGraphClient | None = None,
+ config: RunnableConfig | None = None,
+ name: str | None = None,
+ distributed_tracing: bool = False,
+ ):
+ """Specify `url`, `api_key`, and/or `headers` to create default sync and async clients.
+
+ If `client` or `sync_client` are provided, they will be used instead of the default clients.
+ See `LangGraphClient` and `SyncLangGraphClient` for details on the default clients. At least
+ one of `url`, `client`, or `sync_client` must be provided.
+
+ Args:
+ assistant_id: The assistant ID or graph name of the remote graph to use.
+ url: The URL of the remote API.
+ api_key: The API key to use for authentication. If not provided, it will be read from the environment (`LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, or `LANGCHAIN_API_KEY`).
+ headers: Additional headers to include in the requests.
+ client: A `LangGraphClient` instance to use instead of creating a default client.
+ sync_client: A `SyncLangGraphClient` instance to use instead of creating a default client.
+ config: An optional `RunnableConfig` instance with additional configuration.
+ name: Human-readable name to attach to the RemoteGraph instance.
+ This is useful for adding `RemoteGraph` as a subgraph via `graph.add_node(remote_graph)`.
+ If not provided, defaults to the assistant ID.
+ distributed_tracing: Whether to enable sending LangSmith distributed tracing headers.
+ """
+ self.assistant_id = assistant_id
+ if name is None:
+ self.name = assistant_id
+ else:
+ self.name = name
+ self.config = config
+ self.distributed_tracing = distributed_tracing
+
+ if client is None and url is not None:
+ client = get_client(url=url, api_key=api_key, headers=headers)
+ self.client = client
+
+ if sync_client is None and url is not None:
+ sync_client = get_sync_client(url=url, api_key=api_key, headers=headers)
+ self.sync_client = sync_client
+
+ def _validate_client(self) -> LangGraphClient:
+ if self.client is None:
+ raise ValueError(
+ "Async client is not initialized: please provide `url` or `client` when initializing `RemoteGraph`."
+ )
+ return self.client
+
+ def _validate_sync_client(self) -> SyncLangGraphClient:
+ if self.sync_client is None:
+ raise ValueError(
+ "Sync client is not initialized: please provide `url` or `sync_client` when initializing `RemoteGraph`."
+ )
+ return self.sync_client
+
+ def copy(self, update: dict[str, Any]) -> Self:
+ attrs = {**self.__dict__, **update}
+ return self.__class__(attrs.pop("assistant_id"), **attrs)
+
+ def with_config(self, config: RunnableConfig | None = None, **kwargs: Any) -> Self:
+ return self.copy(
+ {"config": merge_configs(self.config, config, cast(RunnableConfig, kwargs))}
+ )
+
+ def _get_drawable_nodes(
+ self, graph: dict[str, list[dict[str, Any]]]
+ ) -> dict[str, DrawableNode]:
+ nodes = {}
+ for node in graph["nodes"]:
+ node_id = str(node["id"])
+ node_data = node.get("data", {})
+
+ # Get node name from node_data if available. If not, use node_id.
+ node_name = node.get("name")
+ if node_name is None:
+ if isinstance(node_data, dict):
+ node_name = node_data.get("name", node_id)
+ else:
+ node_name = node_id
+
+ nodes[node_id] = DrawableNode(
+ id=node_id,
+ name=node_name,
+ data=node_data,
+ metadata=node.get("metadata"),
+ )
+ return nodes
+
+ def get_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> DrawableGraph:
+ """Get graph by graph name.
+
+ This method calls `GET /assistants/{assistant_id}/graph`.
+
+ Args:
+ config: This parameter is not used.
+ xray: Include graph representation of subgraphs. If an integer
+ value is provided, only subgraphs with a depth less than or
+ equal to the value will be included.
+
+ Returns:
+ The graph information for the assistant in JSON format.
+ """
+ sync_client = self._validate_sync_client()
+ graph = sync_client.assistants.get_graph(
+ assistant_id=self.assistant_id,
+ xray=xray,
+ headers=headers,
+ params=params,
+ )
+ return DrawableGraph(
+ nodes=self._get_drawable_nodes(graph),
+ edges=[DrawableEdge(**edge) for edge in graph["edges"]],
+ )
+
+ async def aget_graph(
+ self,
+ config: RunnableConfig | None = None,
+ *,
+ xray: int | bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> DrawableGraph:
+ """Get graph by graph name.
+
+ This method calls `GET /assistants/{assistant_id}/graph`.
+
+ Args:
+ config: This parameter is not used.
+ xray: Include graph representation of subgraphs. If an integer
+ value is provided, only subgraphs with a depth less than or
+ equal to the value will be included.
+
+ Returns:
+ The graph information for the assistant in JSON format.
+ """
+ client = self._validate_client()
+ graph = await client.assistants.get_graph(
+ assistant_id=self.assistant_id,
+ xray=xray,
+ headers=headers,
+ params=params,
+ )
+ return DrawableGraph(
+ nodes=self._get_drawable_nodes(graph),
+ edges=[DrawableEdge(**edge) for edge in graph["edges"]],
+ )
+
+ def _create_state_snapshot(self, state: ThreadState) -> StateSnapshot:
+ tasks: list[PregelTask] = []
+ for task in state["tasks"]:
+ interrupts = tuple(
+ Interrupt(**interrupt) for interrupt in task["interrupts"]
+ )
+
+ tasks.append(
+ PregelTask(
+ id=task["id"],
+ name=task["name"],
+ path=tuple(),
+ error=Exception(task["error"]) if task["error"] else None,
+ interrupts=interrupts,
+ state=(
+ self._create_state_snapshot(task["state"])
+ if task["state"]
+ else (
+ cast(RunnableConfig, {"configurable": task["checkpoint"]})
+ if task["checkpoint"]
+ else None
+ )
+ ),
+ result=task.get("result"),
+ )
+ )
+
+ return StateSnapshot(
+ values=state["values"],
+ next=tuple(state["next"]) if state["next"] else tuple(),
+ config={
+ "configurable": {
+ "thread_id": state["checkpoint"]["thread_id"],
+ "checkpoint_ns": state["checkpoint"]["checkpoint_ns"],
+ "checkpoint_id": state["checkpoint"]["checkpoint_id"],
+ "checkpoint_map": state["checkpoint"].get("checkpoint_map", {}),
+ }
+ },
+ metadata=CheckpointMetadata(**state["metadata"]),
+ created_at=state["created_at"],
+ parent_config=(
+ {
+ "configurable": {
+ "thread_id": state["parent_checkpoint"]["thread_id"],
+ "checkpoint_ns": state["parent_checkpoint"]["checkpoint_ns"],
+ "checkpoint_id": state["parent_checkpoint"]["checkpoint_id"],
+ "checkpoint_map": state["parent_checkpoint"].get(
+ "checkpoint_map", {}
+ ),
+ }
+ }
+ if state["parent_checkpoint"]
+ else None
+ ),
+ tasks=tuple(tasks),
+ interrupts=tuple([i for task in tasks for i in task.interrupts]),
+ )
+
+ def _get_checkpoint(self, config: RunnableConfig | None) -> Checkpoint | None:
+ if config is None:
+ return None
+
+ checkpoint = {}
+
+ if "thread_id" in config["configurable"]:
+ checkpoint["thread_id"] = config["configurable"]["thread_id"]
+ if "checkpoint_ns" in config["configurable"]:
+ checkpoint["checkpoint_ns"] = config["configurable"]["checkpoint_ns"]
+ if "checkpoint_id" in config["configurable"]:
+ checkpoint["checkpoint_id"] = config["configurable"]["checkpoint_id"]
+ if "checkpoint_map" in config["configurable"]:
+ checkpoint["checkpoint_map"] = config["configurable"]["checkpoint_map"]
+
+ return checkpoint if checkpoint else None
+
+ def _get_config(self, checkpoint: Checkpoint) -> RunnableConfig:
+ return {
+ "configurable": {
+ "thread_id": checkpoint["thread_id"],
+ "checkpoint_ns": checkpoint["checkpoint_ns"],
+ "checkpoint_id": checkpoint["checkpoint_id"],
+ "checkpoint_map": checkpoint.get("checkpoint_map", {}),
+ }
+ }
+
+ def _sanitize_config(self, config: RunnableConfig) -> RunnableConfig:
+ """Sanitize the config to remove non-serializable fields."""
+ sanitized: RunnableConfig = {}
+ if "recursion_limit" in config:
+ sanitized["recursion_limit"] = config["recursion_limit"]
+ if "tags" in config:
+ sanitized["tags"] = [tag for tag in config["tags"] if isinstance(tag, str)]
+
+ if "metadata" in config:
+ sanitized["metadata"] = {}
+ for k, v in config["metadata"].items():
+ if (
+ isinstance(k, str)
+ and (sanitized_value := _sanitize_config_value(v)) is not None
+ ):
+ sanitized["metadata"][k] = sanitized_value
+
+ if "configurable" in config:
+ sanitized["configurable"] = {}
+ for k, v in config["configurable"].items():
+ if (
+ isinstance(k, str)
+ and k not in _CONF_DROPLIST
+ and (sanitized_value := _sanitize_config_value(v)) is not None
+ ):
+ sanitized["configurable"][k] = sanitized_value
+
+ return sanitized
+
+ def get_state(
+ self,
+ config: RunnableConfig,
+ *,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> StateSnapshot:
+ """Get the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state/checkpoint` if a
+ checkpoint is specified in the config or `GET /threads/{thread_id}/state`
+ if no checkpoint is specified.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ subgraphs: Include subgraphs in the state.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The latest state of the thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ state = sync_client.threads.get_state(
+ thread_id=merged_config["configurable"]["thread_id"],
+ checkpoint=self._get_checkpoint(merged_config),
+ subgraphs=subgraphs,
+ headers=headers,
+ params=params,
+ )
+ return self._create_state_snapshot(state)
+
+ async def aget_state(
+ self,
+ config: RunnableConfig,
+ *,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> StateSnapshot:
+ """Get the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state/checkpoint` if a
+ checkpoint is specified in the config or `GET /threads/{thread_id}/state`
+ if no checkpoint is specified.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ subgraphs: Include subgraphs in the state.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The latest state of the thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ state = await client.threads.get_state(
+ thread_id=merged_config["configurable"]["thread_id"],
+ checkpoint=self._get_checkpoint(merged_config),
+ subgraphs=subgraphs,
+ headers=headers,
+ params=params,
+ )
+ return self._create_state_snapshot(state)
+
+ def get_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Iterator[StateSnapshot]:
+ """Get the state history of a thread.
+
+ This method calls `POST /threads/{thread_id}/history`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ filter: Metadata to filter on.
+ before: A `RunnableConfig` that includes checkpoint metadata.
+ limit: Max number of states to return.
+
+ Returns:
+ States of the thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ states = sync_client.threads.get_history(
+ thread_id=merged_config["configurable"]["thread_id"],
+ limit=limit if limit else 10,
+ before=self._get_checkpoint(before),
+ metadata=filter,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ for state in states:
+ yield self._create_state_snapshot(state)
+
+ async def aget_state_history(
+ self,
+ config: RunnableConfig,
+ *,
+ filter: dict[str, Any] | None = None,
+ before: RunnableConfig | None = None,
+ limit: int | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AsyncIterator[StateSnapshot]:
+ """Get the state history of a thread.
+
+ This method calls `POST /threads/{thread_id}/history`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ filter: Metadata to filter on.
+ before: A `RunnableConfig` that includes checkpoint metadata.
+ limit: Max number of states to return.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ States of the thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ states = await client.threads.get_history(
+ thread_id=merged_config["configurable"]["thread_id"],
+ limit=limit if limit else 10,
+ before=self._get_checkpoint(before),
+ metadata=filter,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ for state in states:
+ yield self._create_state_snapshot(state)
+
+ def bulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: list[tuple[dict[str, Any] | None, str | None]],
+ ) -> RunnableConfig:
+ raise NotImplementedError
+
+ async def abulk_update_state(
+ self,
+ config: RunnableConfig,
+ updates: list[tuple[dict[str, Any] | None, str | None]],
+ ) -> RunnableConfig:
+ raise NotImplementedError
+
+ def update_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ *,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> RunnableConfig:
+ """Update the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ values: Values to update to the state.
+ as_node: Update the state as if this node had just executed.
+
+ Returns:
+ `RunnableConfig` for the updated thread.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+
+ response: dict = sync_client.threads.update_state( # type: ignore
+ thread_id=merged_config["configurable"]["thread_id"],
+ values=values,
+ as_node=as_node,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ return self._get_config(response["checkpoint"])
+
+ async def aupdate_state(
+ self,
+ config: RunnableConfig,
+ values: dict[str, Any] | Any | None,
+ as_node: str | None = None,
+ *,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> RunnableConfig:
+ """Update the state of a thread.
+
+ This method calls `POST /threads/{thread_id}/state`.
+
+ Args:
+ config: A `RunnableConfig` that includes `thread_id` in the
+ `configurable` field.
+ values: Values to update to the state.
+ as_node: Update the state as if this node had just executed.
+
+ Returns:
+ `RunnableConfig` for the updated thread.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+
+ response: dict = await client.threads.update_state( # type: ignore
+ thread_id=merged_config["configurable"]["thread_id"],
+ values=values,
+ as_node=as_node,
+ checkpoint=self._get_checkpoint(merged_config),
+ headers=headers,
+ params=params,
+ )
+ return self._get_config(response["checkpoint"])
+
+ def _get_stream_modes(
+ self,
+ stream_mode: StreamMode | list[StreamMode] | None,
+ config: RunnableConfig | None,
+ default: StreamMode = "updates",
+ ) -> tuple[list[StreamModeSDK], list[StreamModeSDK], bool, StreamProtocol | None]:
+ """Return a tuple of the final list of stream modes sent to the
+ remote graph and a boolean flag indicating if stream mode 'updates'
+ was present in the original list of stream modes.
+
+ 'updates' mode is added to the list of stream modes so that interrupts
+ can be detected in the remote graph.
+ """
+ updated_stream_modes: list[StreamModeSDK] = []
+ req_single = True
+ # coerce to list, or add default stream mode
+ if stream_mode:
+ if isinstance(stream_mode, str):
+ updated_stream_modes.append(stream_mode)
+ else:
+ req_single = False
+ updated_stream_modes.extend(stream_mode)
+ else:
+ updated_stream_modes.append(default)
+ requested_stream_modes = updated_stream_modes.copy()
+ # add any from parent graph
+ stream: StreamProtocol | None = (
+ (config or {}).get(CONF, {}).get(CONFIG_KEY_STREAM)
+ )
+ if stream:
+ updated_stream_modes.extend(stream.modes)
+ # map "messages" to "messages-tuple"
+ if "messages" in updated_stream_modes:
+ updated_stream_modes.remove("messages")
+ updated_stream_modes.append("messages-tuple")
+
+ # if requested "messages-tuple",
+ # map to "messages" in requested_stream_modes
+ if "messages-tuple" in requested_stream_modes:
+ requested_stream_modes.remove("messages-tuple")
+ requested_stream_modes.append("messages")
+
+ # add 'updates' mode if not present
+ if "updates" not in updated_stream_modes:
+ updated_stream_modes.append("updates")
+
+ # remove 'events', as it's not supported in Pregel
+ if "events" in updated_stream_modes:
+ updated_stream_modes.remove("events")
+ return (updated_stream_modes, requested_stream_modes, req_single, stream)
+
+ @overload
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any] | Any]: ...
+
+ def stream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any] | Any]:
+ """Create a run and stream the results.
+
+ This method calls `POST /threads/{thread_id}/runs/stream` if a `thread_id`
+ is specified in the `configurable` field of the config or
+ `POST /runs/stream` otherwise.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ stream_mode: Stream mode(s) to use.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ subgraphs: Stream from subgraphs.
+ headers: Additional headers to pass to the request.
+ **kwargs: Additional params to pass to client.runs.stream.
+
+ Yields:
+ The output of the graph.
+ """
+ sync_client = self._validate_sync_client()
+ merged_config = merge_configs(self.config, config)
+ sanitized_config = self._sanitize_config(merged_config)
+ stream_modes, requested, req_single, stream = self._get_stream_modes(
+ stream_mode, config
+ )
+ if isinstance(input, Command):
+ command: CommandSDK | None = cast(CommandSDK, asdict(input))
+ input = None
+ else:
+ command = None
+ thread_id = sanitized_config.get("configurable", {}).pop("thread_id", None)
+
+ for chunk in sync_client.runs.stream(
+ thread_id=thread_id,
+ assistant_id=self.assistant_id,
+ input=input,
+ command=command,
+ config=sanitized_config,
+ context=context,
+ stream_mode=stream_modes,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ stream_subgraphs=subgraphs or stream is not None,
+ if_not_exists="create",
+ headers=(
+ _merge_tracing_headers(headers) if self.distributed_tracing else headers
+ ),
+ params=params,
+ **kwargs,
+ ):
+ # split mode and ns
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ # raise ParentCommand exception for command events
+ if mode == "command" and chunk.data.get("graph") == Command.PARENT:
+ raise ParentCommand(Command(**chunk.data))
+ # prepend caller ns (as it is not passed to remote graph)
+ if caller_ns := (config or {}).get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS):
+ caller_ns = tuple(caller_ns.split(NS_SEP))
+ ns = caller_ns + ns
+ # stream to parent stream
+ if stream is not None and mode in stream.modes:
+ stream((ns, mode, chunk.data))
+ # raise interrupt or errors
+ if chunk.event.startswith("updates"):
+ if isinstance(chunk.data, dict) and INTERRUPT in chunk.data:
+ if caller_ns:
+ raise GraphInterrupt(
+ [Interrupt(**i) for i in chunk.data[INTERRUPT]]
+ )
+ elif chunk.event.startswith("error"):
+ raise RemoteException(chunk.data)
+ # filter for what was actually requested
+ if mode not in requested:
+ continue
+
+ if chunk.event.startswith("messages"):
+ chunk = chunk._replace(data=tuple(chunk.data))
+
+ # emit chunk
+ if version == "v2":
+ ints: tuple[Interrupt, ...] = ()
+ if mode == "values" and isinstance(chunk.data, dict):
+ ints = tuple(
+ Interrupt(**i) if isinstance(i, dict) else i
+ for i in chunk.data.pop(INTERRUPT, ())
+ )
+ yield {"type": mode, "ns": ns, "data": chunk.data, "interrupts": ints}
+ elif subgraphs:
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ if req_single:
+ yield ns, chunk.data
+ else:
+ yield ns, mode, chunk.data
+ elif req_single:
+ yield chunk.data
+ else:
+ yield chunk
+
+ @overload
+ def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamPart]: ...
+
+ @overload
+ def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any] | Any]: ...
+
+ async def astream(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ stream_mode: StreamMode | list[StreamMode] | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ subgraphs: bool = False,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any] | Any]:
+ """Create a run and stream the results.
+
+ This method calls `POST /threads/{thread_id}/runs/stream` if a `thread_id`
+ is specified in the `configurable` field of the config or
+ `POST /runs/stream` otherwise.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ stream_mode: Stream mode(s) to use.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ subgraphs: Stream from subgraphs.
+ headers: Additional headers to pass to the request.
+ **kwargs: Additional params to pass to client.runs.stream.
+
+ Yields:
+ The output of the graph.
+ """
+ client = self._validate_client()
+ merged_config = merge_configs(self.config, config)
+ sanitized_config = self._sanitize_config(merged_config)
+ stream_modes, requested, req_single, stream = self._get_stream_modes(
+ stream_mode, config
+ )
+ if isinstance(input, Command):
+ command: CommandSDK | None = cast(CommandSDK, asdict(input))
+ input = None
+ else:
+ command = None
+ thread_id = sanitized_config.get("configurable", {}).pop("thread_id", None)
+
+ async for chunk in client.runs.stream(
+ thread_id=thread_id,
+ assistant_id=self.assistant_id,
+ input=input,
+ command=command,
+ config=sanitized_config,
+ context=context,
+ stream_mode=stream_modes,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ stream_subgraphs=subgraphs or stream is not None,
+ if_not_exists="create",
+ headers=(
+ _merge_tracing_headers(headers) if self.distributed_tracing else headers
+ ),
+ params=params,
+ **kwargs,
+ ):
+ # split mode and ns
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ # raise ParentCommand exception for command events
+ if mode == "command" and chunk.data.get("graph") == Command.PARENT:
+ raise ParentCommand(Command(**chunk.data))
+ # prepend caller ns (as it is not passed to remote graph)
+ if caller_ns := (config or {}).get(CONF, {}).get(CONFIG_KEY_CHECKPOINT_NS):
+ caller_ns = tuple(caller_ns.split(NS_SEP))
+ ns = caller_ns + ns
+ # stream to parent stream
+ if stream is not None and mode in stream.modes:
+ stream((ns, mode, chunk.data))
+ # raise interrupt or errors
+ if chunk.event.startswith("updates"):
+ if isinstance(chunk.data, dict) and INTERRUPT in chunk.data:
+ if caller_ns:
+ raise GraphInterrupt(
+ [Interrupt(**i) for i in chunk.data[INTERRUPT]]
+ )
+ elif chunk.event.startswith("error"):
+ raise RemoteException(chunk.data)
+ # filter for what was actually requested
+ if mode not in requested:
+ continue
+
+ if chunk.event.startswith("messages"):
+ chunk = chunk._replace(data=tuple(chunk.data))
+
+ # emit chunk
+ if version == "v2":
+ ints: tuple[Interrupt, ...] = ()
+ if mode == "values" and isinstance(chunk.data, dict):
+ ints = tuple(
+ Interrupt(**i) if isinstance(i, dict) else i
+ for i in chunk.data.pop(INTERRUPT, ())
+ )
+ yield {"type": mode, "ns": ns, "data": chunk.data, "interrupts": ints}
+ elif subgraphs:
+ if NS_SEP in chunk.event:
+ mode, ns_ = chunk.event.split(NS_SEP, 1)
+ ns = tuple(ns_.split(NS_SEP))
+ else:
+ mode, ns = chunk.event, ()
+ if req_single:
+ yield ns, chunk.data
+ else:
+ yield ns, mode, chunk.data
+ elif req_single:
+ yield chunk.data
+ else:
+ yield chunk
+
+ async def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"],
+ include_names: Sequence[All] | None = None,
+ include_types: Sequence[All] | None = None,
+ include_tags: Sequence[All] | None = None,
+ exclude_names: Sequence[All] | None = None,
+ exclude_types: Sequence[All] | None = None,
+ exclude_tags: Sequence[All] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ raise NotImplementedError
+
+ @overload
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[dict[str, Any]]: ...
+
+ @overload
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ def invoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ headers: Additional headers to pass to the request.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts.
+ **kwargs: Additional params to pass to RemoteGraph.stream.
+
+ Returns:
+ The output of the graph.
+ """
+ for chunk in self.stream( # type: ignore[misc, call-overload]
+ input,
+ config=config,
+ context=context,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ headers=headers,
+ stream_mode="values",
+ params=params,
+ version=version,
+ **kwargs,
+ ):
+ pass
+ try:
+ if version == "v2":
+ return GraphOutput(
+ value=chunk["data"],
+ interrupts=tuple(chunk.get("interrupts", ())),
+ )
+ return chunk
+ except UnboundLocalError:
+ logger.warning("No events received from remote graph")
+ return None
+
+ @overload
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v2"],
+ **kwargs: Any,
+ ) -> GraphOutput[dict[str, Any]]: ...
+
+ @overload
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1"] = ...,
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any: ...
+
+ async def ainvoke(
+ self,
+ input: dict[str, Any] | Any,
+ config: RunnableConfig | None = None,
+ *,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ headers: dict[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ version: Literal["v1", "v2"] = "v1",
+ **kwargs: Any,
+ ) -> dict[str, Any] | Any:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ input: Input to the graph.
+ config: A `RunnableConfig` for graph invocation.
+ interrupt_before: Interrupt the graph before these nodes.
+ interrupt_after: Interrupt the graph after these nodes.
+ headers: Additional headers to pass to the request.
+ version: The streaming format version. `"v1"` (default) returns the
+ traditional format, `"v2"` returns `StreamPart` typed dicts.
+ **kwargs: Additional params to pass to RemoteGraph.astream.
+
+ Returns:
+ The output of the graph.
+ """
+ async for chunk in self.astream( # type: ignore[misc, call-overload]
+ input,
+ config=config,
+ context=context,
+ interrupt_before=interrupt_before,
+ interrupt_after=interrupt_after,
+ headers=headers,
+ stream_mode="values",
+ params=params,
+ version=version,
+ **kwargs,
+ ):
+ pass
+ try:
+ if version == "v2":
+ return GraphOutput(
+ value=chunk["data"],
+ interrupts=tuple(chunk.get("interrupts", ())),
+ )
+ return chunk
+ except UnboundLocalError:
+ logger.warning("No events received from remote graph")
+ return None
+
+
+def _merge_tracing_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
+ if rt := ls.get_current_run_tree():
+ tracing_headers = rt.to_headers()
+ if headers:
+ if "baggage" in headers:
+ tracing_headers["baggage"] = (
+ f"{headers['baggage']},{tracing_headers['baggage']}"
+ )
+ headers.update(tracing_headers)
+ else:
+ headers = tracing_headers
+ return headers
diff --git a/python/user_packages/Python313/site-packages/langgraph/pregel/types.py b/python/user_packages/Python313/site-packages/langgraph/pregel/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..39a36df68787da3cf33bbfd8a9ca8ab8b14874a2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/pregel/types.py
@@ -0,0 +1,38 @@
+"""Re-export types moved to langgraph.types"""
+
+from langgraph.types import (
+ All,
+ CachePolicy,
+ PregelExecutableTask,
+ PregelTask,
+ RetryPolicy,
+ StateSnapshot,
+ StateUpdate,
+ StreamMode,
+ StreamWriter,
+ default_retry_on,
+)
+
+__all__ = [
+ "All",
+ "StateUpdate",
+ "CachePolicy",
+ "PregelExecutableTask",
+ "PregelTask",
+ "RetryPolicy",
+ "StateSnapshot",
+ "StreamMode",
+ "StreamWriter",
+ "default_retry_on",
+]
+
+from warnings import warn
+
+from langgraph.warnings import LangGraphDeprecatedSinceV10
+
+warn(
+ "Importing from langgraph.pregel.types is deprecated. "
+ "Please use 'from langgraph.types import ...' instead.",
+ LangGraphDeprecatedSinceV10,
+ stacklevel=2,
+)
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/__init__.py b/python/user_packages/Python313/site-packages/langgraph/store/base/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b04fb51dcbb3a651769413b45f3d7652d249f95
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/store/base/__init__.py
@@ -0,0 +1,1314 @@
+"""Base classes and types for persistent key-value stores.
+
+Stores provide long-term memory that persists across threads and conversations.
+Supports hierarchical namespaces, key-value storage, and optional vector search.
+
+Core types:
+ - `BaseStore`: Store interface with sync/async operations
+ - `Item`: Stored key-value pairs with metadata
+ - `Op`: Get/Put/Search/List operations
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Iterable
+from datetime import datetime
+from typing import (
+ Any,
+ Literal,
+ NamedTuple,
+ TypedDict,
+ cast,
+)
+
+from langchain_core.embeddings import Embeddings
+from typing_extensions import override
+
+from langgraph.store.base.embed import (
+ AEmbeddingsFunc,
+ EmbeddingsFunc,
+ ensure_embeddings,
+ get_text_at_path,
+ tokenize_path,
+)
+
+
+class NotProvided:
+ """Sentinel singleton."""
+
+ def __bool__(self) -> Literal[False]:
+ return False
+
+ @override
+ def __repr__(self) -> str:
+ return "NOT_GIVEN"
+
+
+NOT_PROVIDED = NotProvided()
+
+
+class Item:
+ """Represents a stored item with metadata.
+
+ Args:
+ value: The stored data as a dictionary. Keys are filterable.
+ key: Unique identifier within the namespace.
+ namespace: Hierarchical path defining the collection in which this document resides.
+ Represented as a tuple of strings, allowing for nested categorization.
+ For example: `("documents", 'user123')`
+ created_at: Timestamp of item creation.
+ updated_at: Timestamp of last update.
+ """
+
+ __slots__ = ("value", "key", "namespace", "created_at", "updated_at")
+
+ def __init__(
+ self,
+ *,
+ value: dict[str, Any],
+ key: str,
+ namespace: tuple[str, ...],
+ created_at: datetime,
+ updated_at: datetime,
+ ):
+ self.value = value
+ self.key = key
+ # The casting from json-like types is for if this object is
+ # deserialized.
+ self.namespace = tuple(namespace)
+ self.created_at = (
+ datetime.fromisoformat(cast(str, created_at))
+ if isinstance(created_at, str)
+ else created_at
+ )
+ self.updated_at = (
+ datetime.fromisoformat(cast(str, updated_at))
+ if isinstance(updated_at, str)
+ else updated_at
+ )
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Item):
+ return False
+ return (
+ self.value == other.value
+ and self.key == other.key
+ and self.namespace == other.namespace
+ and self.created_at == other.created_at
+ and self.updated_at == other.updated_at
+ )
+
+ def __hash__(self) -> int:
+ return hash((self.namespace, self.key))
+
+ def dict(self) -> dict:
+ return {
+ "namespace": list(self.namespace),
+ "key": self.key,
+ "value": self.value,
+ "created_at": self.created_at.isoformat(),
+ "updated_at": self.updated_at.isoformat(),
+ }
+
+ def __repr__(self) -> str:
+ return f"Item({', '.join(f'{k}={v!r}' for k, v in self.dict().items())})"
+
+
+class SearchItem(Item):
+ """Represents an item returned from a search operation with additional metadata."""
+
+ __slots__ = ("score",)
+
+ def __init__(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ created_at: datetime,
+ updated_at: datetime,
+ score: float | None = None,
+ ) -> None:
+ """Initialize a result item.
+
+ Args:
+ namespace: Hierarchical path to the item.
+ key: Unique identifier within the namespace.
+ value: The stored value.
+ created_at: When the item was first created.
+ updated_at: When the item was last updated.
+ score: Relevance/similarity score if from a ranked operation.
+ """
+ super().__init__(
+ value=value,
+ key=key,
+ namespace=namespace,
+ created_at=created_at,
+ updated_at=updated_at,
+ )
+ self.score = score
+
+ def dict(self) -> dict:
+ result = super().dict()
+ result["score"] = self.score
+ return result
+
+
+class GetOp(NamedTuple):
+ """Operation to retrieve a specific item by its namespace and key.
+
+ This operation allows precise retrieval of stored items using their full path
+ (namespace) and unique identifier (key) combination.
+
+ ???+ example "Examples"
+
+ Basic item retrieval:
+
+ ```python
+ GetOp(namespace=("users", "profiles"), key="user123")
+ GetOp(namespace=("cache", "embeddings"), key="doc456")
+ ```
+ """
+
+ namespace: tuple[str, ...]
+ """Hierarchical path that uniquely identifies the item's location.
+
+ ???+ example "Examples"
+
+ ```python
+ ("users",) # Root level users namespace
+ ("users", "profiles") # Profiles within users namespace
+ ```
+ """
+
+ key: str
+ """Unique identifier for the item within its specific namespace.
+
+ ???+ example "Examples"
+
+ ```python
+ "user123" # For a user profile
+ "doc456" # For a document
+ ```
+ """
+ refresh_ttl: bool = True
+ """Whether to refresh TTLs for the returned item.
+
+ If no TTL was specified for the original item(s),
+ or if TTL support is not enabled for your adapter,
+ this argument is ignored.
+ """
+
+
+class SearchOp(NamedTuple):
+ """Operation to search for items within a specified namespace hierarchy.
+
+ This operation supports both structured filtering and natural language search
+ within a given namespace prefix. It provides pagination through limit and offset
+ parameters.
+
+ !!! note
+
+ Natural language search support depends on your store implementation.
+
+ ???+ example "Examples"
+
+ Search with filters and pagination:
+
+ ```python
+ SearchOp(
+ namespace_prefix=("documents",),
+ filter={"type": "report", "status": "active"},
+ limit=5,
+ offset=10
+ )
+ ```
+
+ Natural language search:
+
+ ```python
+ SearchOp(
+ namespace_prefix=("users", "content"),
+ query="technical documentation about APIs",
+ limit=20
+ )
+ ```
+ """
+
+ namespace_prefix: tuple[str, ...]
+ """Hierarchical path prefix defining the search scope.
+
+ ???+ example "Examples"
+
+ ```python
+ () # Search entire store
+ ("documents",) # Search all documents
+ ("users", "content") # Search within user content
+ ```
+ """
+
+ filter: dict[str, Any] | None = None
+ """Key-value pairs for filtering results based on exact matches or comparison operators.
+
+ The filter supports both exact matches and operator-based comparisons.
+
+ Supported Operators:
+ - `$eq`: Equal to (same as direct value comparison)
+ - `$ne`: Not equal to
+ - `$gt`: Greater than
+ - `$gte`: Greater than or equal to
+ - `$lt`: Less than
+ - `$lte`: Less than or equal to
+
+ ???+ example "Examples"
+
+ Simple exact match:
+
+ ```python
+ {"status": "active"}
+ ```
+
+ Comparison operators:
+
+ ```python
+ {"score": {"$gt": 4.99}} # Score greater than 4.99
+ ```
+
+ Multiple conditions:
+
+ ```python
+ {
+ "score": {"$gte": 3.0},
+ "color": "red"
+ }
+ ```
+ """
+
+ limit: int = 10
+ """Maximum number of items to return in the search results."""
+
+ offset: int = 0
+ """Number of matching items to skip for pagination."""
+
+ query: str | None = None
+ """Natural language search query for semantic search capabilities.
+
+ ???+ example "Examples"
+
+ - "technical documentation about REST APIs"
+ - "machine learning papers from 2023"
+ """
+ refresh_ttl: bool = True
+ """Whether to refresh TTLs for the returned item.
+
+ If no TTL was specified for the original item(s),
+ or if TTL support is not enabled for your adapter,
+ this argument is ignored.
+ """
+
+
+# Type representing a namespace path that can include wildcards
+NamespacePath = tuple[str | Literal["*"], ...]
+"""A tuple representing a namespace path that can include wildcards.
+
+???+ example "Examples"
+
+ ```python
+ ("users",) # Exact users namespace
+ ("documents", "*") # Any sub-namespace under documents
+ ("cache", "*", "v1") # Any cache category with v1 version
+ ```
+"""
+
+# Type for specifying how to match namespaces
+NamespaceMatchType = Literal["prefix", "suffix"]
+"""Specifies how to match namespace paths.
+
+Values:
+ "prefix": Match from the start of the namespace
+ "suffix": Match from the end of the namespace
+"""
+
+
+class MatchCondition(NamedTuple):
+ """Represents a pattern for matching namespaces in the store.
+
+ This class combines a match type (prefix or suffix) with a namespace path
+ pattern that can include wildcards to flexibly match different namespace
+ hierarchies.
+
+ ???+ example "Examples"
+
+ Prefix matching:
+
+ ```python
+ MatchCondition(match_type="prefix", path=("users", "profiles"))
+ ```
+
+ Suffix matching with wildcard:
+
+ ```python
+ MatchCondition(match_type="suffix", path=("cache", "*"))
+ ```
+
+ Simple suffix matching:
+
+ ```python
+ MatchCondition(match_type="suffix", path=("v1",))
+ ```
+ """
+
+ match_type: NamespaceMatchType
+ """Type of namespace matching to perform."""
+
+ path: NamespacePath
+ """Namespace path pattern that can include wildcards."""
+
+
+class ListNamespacesOp(NamedTuple):
+ """Operation to list and filter namespaces in the store.
+
+ This operation allows exploring the organization of data, finding specific
+ collections, and navigating the namespace hierarchy.
+
+ ???+ example "Examples"
+
+ List all namespaces under the `"documents"` path:
+
+ ```python
+ ListNamespacesOp(
+ match_conditions=(MatchCondition(match_type="prefix", path=("documents",)),),
+ max_depth=2
+ )
+ ```
+
+ List all namespaces that end with `"v1"`:
+
+ ```python
+ ListNamespacesOp(
+ match_conditions=(MatchCondition(match_type="suffix", path=("v1",)),),
+ limit=50
+ )
+ ```
+
+ """
+
+ match_conditions: tuple[MatchCondition, ...] | None = None
+ """Optional conditions for filtering namespaces.
+
+ ???+ example "Examples"
+
+ All user namespaces:
+
+ ```python
+ (MatchCondition(match_type="prefix", path=("users",)),)
+ ```
+
+ All namespaces that start with `"docs"` and end with `"draft"`:
+
+ ```python
+ (
+ MatchCondition(match_type="prefix", path=("docs",)),
+ MatchCondition(match_type="suffix", path=("draft",))
+ )
+ ```
+ """
+
+ max_depth: int | None = None
+ """Maximum depth of namespace hierarchy to return.
+
+ Note:
+ Namespaces deeper than this level will be truncated.
+ """
+
+ limit: int = 100
+ """Maximum number of namespaces to return."""
+
+ offset: int = 0
+ """Number of namespaces to skip for pagination."""
+
+
+class PutOp(NamedTuple):
+ """Operation to store, update, or delete an item in the store.
+
+ This class represents a single operation to modify the store's contents,
+ whether adding new items, updating existing ones, or removing them.
+ """
+
+ namespace: tuple[str, ...]
+ """Hierarchical path that identifies the location of the item.
+
+ The namespace acts as a folder-like structure to organize items.
+ Each element in the tuple represents one level in the hierarchy.
+
+ ???+ example "Examples"
+
+ Root level documents:
+
+ ```python
+ ("documents",)
+ ```
+
+ User-specific documents:
+
+ ```python
+ ("documents", "user123")
+ ```
+
+ Nested cache structure:
+
+ ```python
+ ("cache", "embeddings", "v1")
+ ```
+ """
+
+ key: str
+ """Unique identifier for the item within its namespace.
+
+ The key must be unique within the specific namespace to avoid conflicts.
+ Together with the namespace, it forms a complete path to the item.
+
+ Example:
+ If namespace is `("documents", "user123")` and key is `"report1"`,
+ the full path would effectively be `"documents/user123/report1"`
+ """
+
+ value: dict[str, Any] | None
+ """The data to store, or `None` to mark the item for deletion.
+
+ The value must be a dictionary with string keys and JSON-serializable values.
+ Setting this to `None` signals that the item should be deleted.
+
+ Example:
+ {
+ "field1": "string value",
+ "field2": 123,
+ "nested": {"can": "contain", "any": "serializable data"}
+ }
+ """
+
+ index: Literal[False] | list[str] | None = None # type: ignore[assignment]
+ """Controls how the item's fields are indexed for search operations.
+
+ Indexing configuration determines how the item can be found through search:
+ - `None` (default): Uses the store's default indexing configuration (if provided)
+ - `False`: Disables indexing for this item
+ - `list[str]`: Specifies which json path fields to index for search
+
+ The item remains accessible through direct get() operations regardless of indexing.
+ When indexed, fields can be searched using natural language queries through
+ vector similarity search (if supported by the store implementation).
+
+ Path Syntax:
+ - Simple field access: `"field"`
+ - Nested fields: `"parent.child.grandchild"`
+ - Array indexing:
+ - Specific index: `"array[0]"`
+ - Last element: `"array[-1]"`
+ - All elements (each individually): `"array[*]"`
+
+ ???+ example "Examples"
+
+ - `None` - Use store defaults (whole item)
+ - `list[str]` - List of fields to index
+
+ ```python
+ [
+ "metadata.title", # Nested field access
+ "context[*].content", # Index content from all context as separate vectors
+ "authors[0].name", # First author's name
+ "revisions[-1].changes", # Most recent revision's changes
+ "sections[*].paragraphs[*].text", # All text from all paragraphs in all sections
+ "metadata.tags[*]", # All tags in metadata
+ ]
+ ```
+ """
+ ttl: float | None = None
+ """Controls the TTL (time-to-live) for the item in minutes.
+
+ If provided, and if the store you are using supports this feature, the item
+ will expire this many minutes after it was last accessed. The expiration timer
+ refreshes on both read operations (get/search) and write operations (put/update).
+ When the TTL expires, the item will be scheduled for deletion on a best-effort basis.
+ Defaults to `None` (no expiration).
+ """
+
+
+Op = GetOp | SearchOp | PutOp | ListNamespacesOp
+Result = Item | list[Item] | list[SearchItem] | list[tuple[str, ...]] | None
+
+
+class InvalidNamespaceError(ValueError):
+ """Provided namespace is invalid."""
+
+
+class TTLConfig(TypedDict, total=False):
+ """Configuration for TTL (time-to-live) behavior in the store."""
+
+ refresh_on_read: bool
+ """Default behavior for refreshing TTLs on read operations (`GET` and `SEARCH`).
+
+ If `True`, TTLs will be refreshed on read operations (get/search) by default.
+ This can be overridden per-operation by explicitly setting `refresh_ttl`.
+ Defaults to `True` if not configured.
+ """
+ default_ttl: float | None
+ """Default TTL (time-to-live) in minutes for new items.
+
+ If provided, new items will expire after this many minutes after their last access.
+ The expiration timer refreshes on both read and write operations.
+ Defaults to `None` (no expiration).
+ """
+ sweep_interval_minutes: int | None
+ """Interval in minutes between TTL sweep operations.
+
+ If provided, the store will periodically delete expired items based on TTL.
+ Defaults to None (no sweeping).
+ """
+
+
+class IndexConfig(TypedDict, total=False):
+ """Configuration for indexing documents for semantic search in the store.
+
+ If not provided to the store, the store will not support vector search.
+ In that case, all `index` arguments to `put()` and `aput()` operations will be ignored.
+ """
+
+ dims: int
+ """Number of dimensions in the embedding vectors.
+
+ Common embedding models have the following dimensions:
+ - `openai:text-embedding-3-large`: `3072`
+ - `openai:text-embedding-3-small`: `1536`
+ - `openai:text-embedding-ada-002`: `1536`
+ - `cohere:embed-english-v3.0`: `1024`
+ - `cohere:embed-english-light-v3.0`: `384`
+ - `cohere:embed-multilingual-v3.0`: `1024`
+ - `cohere:embed-multilingual-light-v3.0`: `384`
+ """
+
+ embed: Embeddings | EmbeddingsFunc | AEmbeddingsFunc | str
+ """Optional function to generate embeddings from text.
+
+ Can be specified in three ways:
+ 1. A LangChain `Embeddings` instance
+ 2. A synchronous embedding function (`EmbeddingsFunc`)
+ 3. An asynchronous embedding function (`AEmbeddingsFunc`)
+ 4. A provider string (e.g., `"openai:text-embedding-3-small"`)
+
+ ???+ example "Examples"
+
+ Using LangChain's initialization with `InMemoryStore`:
+
+ ```python
+ from langchain.embeddings import init_embeddings
+ from langgraph.store.memory import InMemoryStore
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": init_embeddings("openai:text-embedding-3-small")
+ }
+ )
+ ```
+
+ Using a custom embedding function with `InMemoryStore`:
+
+ ```python
+ from openai import OpenAI
+ from langgraph.store.memory import InMemoryStore
+
+ client = OpenAI()
+
+ def embed_texts(texts: list[str]) -> list[list[float]]:
+ response = client.embeddings.create(
+ model="text-embedding-3-small",
+ input=texts
+ )
+ return [e.embedding for e in response.data]
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": embed_texts
+ }
+ )
+ ```
+
+ Using an asynchronous embedding function with `InMemoryStore`:
+
+ ```python
+ from openai import AsyncOpenAI
+ from langgraph.store.memory import InMemoryStore
+
+ client = AsyncOpenAI()
+
+ async def aembed_texts(texts: list[str]) -> list[list[float]]:
+ response = await client.embeddings.create(
+ model="text-embedding-3-small",
+ input=texts
+ )
+ return [e.embedding for e in response.data]
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": aembed_texts
+ }
+ )
+ ```
+ """
+
+ fields: list[str] | None
+ """Fields to extract text from for embedding generation.
+
+ Controls which parts of stored items are embedded for semantic search. Follows JSON path syntax:
+
+ - `["$"]`: Embeds the entire JSON object as one vector (default)
+ - `["field1", "field2"]`: Embeds specific top-level fields
+ - `["parent.child"]`: Embeds nested fields using dot notation
+ - `["array[*].field"]`: Embeds field from each array element separately
+
+ Note:
+ You can always override this behavior when storing an item using the
+ `index` parameter in the `put` or `aput` operations.
+
+ ???+ example "Examples"
+
+ ```python
+ # Embed entire document (default)
+ fields=["$"]
+
+ # Embed specific fields
+ fields=["text", "summary"]
+
+ # Embed nested fields
+ fields=["metadata.title", "content.body"]
+
+ # Embed from arrays
+ fields=["messages[*].content"] # Each message content separately
+ fields=["context[0].text"] # First context item's text
+ ```
+
+ Note:
+ - Fields missing from a document are skipped
+ - Array notation creates separate embeddings for each element
+ - Complex nested paths are supported (e.g., `"a.b[*].c.d"`)
+ """
+
+
+class BaseStore(ABC):
+ """Abstract base class for persistent key-value stores.
+
+ Stores enable persistence and memory that can be shared across threads,
+ scoped to user IDs, assistant IDs, or other arbitrary namespaces.
+ Some implementations may support semantic search capabilities through
+ an optional `index` configuration.
+
+ Note:
+ Semantic search capabilities vary by implementation and are typically
+ disabled by default. Stores that support this feature can be configured
+ by providing an `index` configuration at creation time. Without this
+ configuration, semantic search is disabled and any `index` arguments
+ to storage operations will have no effect.
+
+ Similarly, TTL (time-to-live) support is disabled by default.
+ Subclasses must explicitly set `supports_ttl = True` to enable this feature.
+ """
+
+ supports_ttl: bool = False
+ ttl_config: TTLConfig | None = None
+
+ __slots__ = ("__weakref__",)
+
+ @abstractmethod
+ def batch(self, ops: Iterable[Op]) -> list[Result]:
+ """Execute multiple operations synchronously in a single batch.
+
+ Args:
+ ops: An iterable of operations to execute.
+
+ Returns:
+ A list of results, where each result corresponds to an operation in the input.
+ The order of results matches the order of input operations.
+ """
+
+ @abstractmethod
+ async def abatch(self, ops: Iterable[Op]) -> list[Result]:
+ """Execute multiple operations asynchronously in a single batch.
+
+ Args:
+ ops: An iterable of operations to execute.
+
+ Returns:
+ A list of results, where each result corresponds to an operation in the input.
+ The order of results matches the order of input operations.
+ """
+
+ def get(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ ) -> Item | None:
+ """Retrieve a single item.
+
+ Args:
+ namespace: Hierarchical path for the item.
+ key: Unique identifier within the namespace.
+ refresh_ttl: Whether to refresh TTLs for the returned item.
+ If `None`, uses the store's default `refresh_ttl` setting.
+ If no TTL is specified, this argument is ignored.
+
+ Returns:
+ The retrieved item or `None` if not found.
+ """
+ return self.batch(
+ [GetOp(namespace, str(key), _ensure_refresh(self.ttl_config, refresh_ttl))]
+ )[0]
+
+ def search(
+ self,
+ namespace_prefix: tuple[str, ...],
+ /,
+ *,
+ query: str | None = None,
+ filter: dict[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ refresh_ttl: bool | None = None,
+ ) -> list[SearchItem]:
+ """Search for items within a namespace prefix.
+
+ Args:
+ namespace_prefix: Hierarchical path prefix to search within.
+ query: Optional query for natural language search.
+ filter: Key-value pairs to filter results.
+ limit: Maximum number of items to return.
+ offset: Number of items to skip before returning results.
+ refresh_ttl: Whether to refresh TTLs for the returned items.
+ If no TTL is specified, this argument is ignored.
+
+ Returns:
+ List of items matching the search criteria.
+
+ ???+ example "Examples"
+
+ Basic filtering:
+
+ ```python
+ # Search for documents with specific metadata
+ results = store.search(
+ ("docs",),
+ filter={"type": "article", "status": "published"}
+ )
+ ```
+
+ Natural language search (requires vector store implementation):
+
+ ```python
+ # Initialize store with embedding configuration
+ store = YourStore( # e.g., InMemoryStore, AsyncPostgresStore
+ index={
+ "dims": 1536, # embedding dimensions
+ "embed": your_embedding_function, # function to create embeddings
+ "fields": ["text"] # fields to embed. Defaults to ["$"]
+ }
+ )
+
+ # Search for semantically similar documents
+
+ results = store.search(
+ ("docs",),
+ query="machine learning applications in healthcare",
+ filter={"type": "research_paper"},
+ limit=5
+ )
+ ```
+
+ !!! note
+
+ Natural language search support depends on your store implementation
+ and requires proper embedding configuration.
+ """
+ return self.batch(
+ [
+ SearchOp(
+ namespace_prefix,
+ filter,
+ limit,
+ offset,
+ query,
+ _ensure_refresh(self.ttl_config, refresh_ttl),
+ )
+ ]
+ )[0]
+
+ def put(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ *,
+ ttl: float | None | NotProvided = NOT_PROVIDED,
+ ) -> None:
+ """Store or update an item in the store.
+
+ Args:
+ namespace: Hierarchical path for the item, represented as a tuple of strings.
+ Example: `("documents", "user123")`
+ key: Unique identifier within the namespace. Together with namespace forms
+ the complete path to the item.
+ value: Dictionary containing the item's data. Must contain string keys
+ and JSON-serializable values.
+ index: Controls how the item's fields are indexed for search:
+
+ - None (default): Use `fields` you configured when creating the store (if any)
+ If you do not initialize the store with indexing capabilities,
+ the `index` parameter will be ignored
+ - False: Disable indexing for this item
+ - `list[str]`: List of field paths to index, supporting:
+ - Nested fields: `"metadata.title"`
+ - Array access: `"chapters[*].content"` (each indexed separately)
+ - Specific indices: `"authors[0].name"`
+ ttl: Time to live in minutes. Support for this argument depends on your store adapter.
+ If specified, the item will expire after this many minutes from when it was last accessed.
+ None means no expiration. Expired runs will be deleted opportunistically.
+ By default, the expiration timer refreshes on both read operations (get/search)
+ and write operations (put/update), whenever the item is included in the operation.
+
+ Note:
+ Indexing support depends on your store implementation.
+ If you do not initialize the store with indexing capabilities,
+ the `index` parameter will be ignored.
+
+ Similarly, TTL support depends on the specific store implementation.
+ Some implementations may not support expiration of items.
+
+ ???+ example "Examples"
+
+ Store item. Indexing depends on how you configure the store:
+
+ ```python
+ store.put(("docs",), "report", {"memory": "Will likes ai"})
+ ```
+
+ Do not index item for semantic search. Still accessible through `get()`
+ and `search()` operations but won't have a vector representation.
+
+ ```python
+ store.put(("docs",), "report", {"memory": "Will likes ai"}, index=False)
+ ```
+
+ Index specific fields for search:
+
+ ```python
+ store.put(("docs",), "report", {"memory": "Will likes ai"}, index=["memory"])
+ ```
+ """
+ _validate_namespace(namespace)
+ if ttl not in (NOT_PROVIDED, None) and not self.supports_ttl:
+ raise NotImplementedError(
+ f"TTL is not supported by {self.__class__.__name__}. "
+ f"Use a store implementation that supports TTL or set ttl=None."
+ )
+ self.batch(
+ [
+ PutOp(
+ namespace,
+ str(key),
+ value,
+ index=index,
+ ttl=_ensure_ttl(self.ttl_config, ttl),
+ )
+ ]
+ )
+
+ def delete(self, namespace: tuple[str, ...], key: str) -> None:
+ """Delete an item.
+
+ Args:
+ namespace: Hierarchical path for the item.
+ key: Unique identifier within the namespace.
+ """
+ self.batch([PutOp(namespace, str(key), None, ttl=None)])
+
+ def list_namespaces(
+ self,
+ *,
+ prefix: NamespacePath | None = None,
+ suffix: NamespacePath | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[tuple[str, ...]]:
+ """List and filter namespaces in the store.
+
+ Used to explore the organization of data,
+ find specific collections, or navigate the namespace hierarchy.
+
+ Args:
+ prefix: Filter namespaces that start with this path.
+ suffix: Filter namespaces that end with this path.
+ max_depth: Return namespaces up to this depth in the hierarchy.
+ Namespaces deeper than this level will be truncated.
+ limit: Maximum number of namespaces to return.
+ offset: Number of namespaces to skip for pagination.
+
+ Returns:
+ A list of namespace tuples that match the criteria. Each tuple represents a
+ full namespace path up to `max_depth`.
+
+ ???+ example "Examples":
+
+ Setting `max_depth=3`. Given the namespaces:
+
+ ```python
+ # Example if you have the following namespaces:
+ # ("a", "b", "c")
+ # ("a", "b", "d", "e")
+ # ("a", "b", "d", "i")
+ # ("a", "b", "f")
+ # ("a", "c", "f")
+ store.list_namespaces(prefix=("a", "b"), max_depth=3)
+ # [("a", "b", "c"), ("a", "b", "d"), ("a", "b", "f")]
+ ```
+ """
+ match_conditions = []
+ if prefix:
+ match_conditions.append(MatchCondition(match_type="prefix", path=prefix))
+ if suffix:
+ match_conditions.append(MatchCondition(match_type="suffix", path=suffix))
+
+ op = ListNamespacesOp(
+ match_conditions=tuple(match_conditions),
+ max_depth=max_depth,
+ limit=limit,
+ offset=offset,
+ )
+ return self.batch([op])[0]
+
+ async def aget(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ ) -> Item | None:
+ """Asynchronously retrieve a single item.
+
+ Args:
+ namespace: Hierarchical path for the item.
+ key: Unique identifier within the namespace.
+
+ Returns:
+ The retrieved item or `None` if not found.
+ """
+ return (
+ await self.abatch(
+ [
+ GetOp(
+ namespace,
+ str(key),
+ _ensure_refresh(self.ttl_config, refresh_ttl),
+ )
+ ]
+ )
+ )[0]
+
+ async def asearch(
+ self,
+ namespace_prefix: tuple[str, ...],
+ /,
+ *,
+ query: str | None = None,
+ filter: dict[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ refresh_ttl: bool | None = None,
+ ) -> list[SearchItem]:
+ """Asynchronously search for items within a namespace prefix.
+
+ Args:
+ namespace_prefix: Hierarchical path prefix to search within.
+ query: Optional query for natural language search.
+ filter: Key-value pairs to filter results.
+ limit: Maximum number of items to return.
+ offset: Number of items to skip before returning results.
+ refresh_ttl: Whether to refresh TTLs for the returned items.
+ If `None`, uses the store's `TTLConfig.refresh_default` setting.
+ If `TTLConfig` is not provided or no TTL is specified, this argument is ignored.
+
+ Returns:
+ List of items matching the search criteria.
+
+ ???+ example "Examples"
+
+ Basic filtering:
+
+ ```python
+ # Search for documents with specific metadata
+ results = await store.asearch(
+ ("docs",),
+ filter={"type": "article", "status": "published"}
+ )
+ ```
+
+ Natural language search (requires vector store implementation):
+
+ ```python
+ # Initialize store with embedding configuration
+ store = YourStore( # e.g., InMemoryStore, AsyncPostgresStore
+ index={
+ "dims": 1536, # embedding dimensions
+ "embed": your_embedding_function, # function to create embeddings
+ "fields": ["text"] # fields to embed
+ }
+ )
+
+ # Search for semantically similar documents
+
+ results = await store.asearch(
+ ("docs",),
+ query="machine learning applications in healthcare",
+ filter={"type": "research_paper"},
+ limit=5
+ )
+ ```
+
+ !!! note
+
+ Natural language search support depends on your store implementation
+ and requires proper embedding configuration.
+ """
+ return (
+ await self.abatch(
+ [
+ SearchOp(
+ namespace_prefix,
+ filter,
+ limit,
+ offset,
+ query,
+ _ensure_refresh(self.ttl_config, refresh_ttl),
+ )
+ ]
+ )
+ )[0]
+
+ async def aput(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ *,
+ ttl: float | None | NotProvided = NOT_PROVIDED,
+ ) -> None:
+ """Asynchronously store or update an item in the store.
+
+ Args:
+ namespace: Hierarchical path for the item, represented as a tuple of strings.
+ Example: `("documents", "user123")`
+ key: Unique identifier within the namespace. Together with namespace forms
+ the complete path to the item.
+ value: Dictionary containing the item's data. Must contain string keys
+ and JSON-serializable values.
+ index: Controls how the item's fields are indexed for search:
+
+ - None (default): Use `fields` you configured when creating the store (if any)
+ If you do not initialize the store with indexing capabilities,
+ the `index` parameter will be ignored
+ - False: Disable indexing for this item
+ - `list[str]`: List of field paths to index, supporting:
+ - Nested fields: `"metadata.title"`
+ - Array access: `"chapters[*].content"` (each indexed separately)
+ - Specific indices: `"authors[0].name"`
+ ttl: Time to live in minutes. Support for this argument depends on your store adapter.
+ If specified, the item will expire after this many minutes from when it was last accessed.
+ None means no expiration. Expired runs will be deleted opportunistically.
+ By default, the expiration timer refreshes on both read operations (get/search)
+ and write operations (put/update), whenever the item is included in the operation.
+
+ Note:
+ Indexing support depends on your store implementation.
+ If you do not initialize the store with indexing capabilities,
+ the `index` parameter will be ignored.
+
+ Similarly, TTL support depends on the specific store implementation.
+ Some implementations may not support expiration of items.
+
+ ???+ example "Examples"
+
+ Store item. Indexing depends on how you configure the store:
+
+ ```python
+ await store.aput(("docs",), "report", {"memory": "Will likes ai"})
+ ```
+
+ Do not index item for semantic search. Still accessible through `get()`
+ and `search()` operations but won't have a vector representation.
+
+ ```python
+ await store.aput(("docs",), "report", {"memory": "Will likes ai"}, index=False)
+ ```
+
+ Index specific fields for search (if store configured to index items):
+
+ ```python
+ await store.aput(
+ ("docs",),
+ "report",
+ {
+ "memory": "Will likes ai",
+ "context": [{"content": "..."}, {"content": "..."}]
+ },
+ index=["memory", "context[*].content"]
+ )
+ ```
+ """
+ _validate_namespace(namespace)
+ if ttl not in (NOT_PROVIDED, None) and not self.supports_ttl:
+ raise NotImplementedError(
+ f"TTL is not supported by {self.__class__.__name__}. "
+ f"Use a store implementation that supports TTL or set ttl=None."
+ )
+ await self.abatch(
+ [
+ PutOp(
+ namespace,
+ str(key),
+ value,
+ index=index,
+ ttl=_ensure_ttl(self.ttl_config, ttl),
+ )
+ ]
+ )
+
+ async def adelete(self, namespace: tuple[str, ...], key: str) -> None:
+ """Asynchronously delete an item.
+
+ Args:
+ namespace: Hierarchical path for the item.
+ key: Unique identifier within the namespace.
+ """
+ await self.abatch([PutOp(namespace, str(key), None)])
+
+ async def alist_namespaces(
+ self,
+ *,
+ prefix: NamespacePath | None = None,
+ suffix: NamespacePath | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[tuple[str, ...]]:
+ """List and filter namespaces in the store asynchronously.
+
+ Used to explore the organization of data,
+ find specific collections, or navigate the namespace hierarchy.
+
+ Args:
+ prefix: Filter namespaces that start with this path.
+ suffix: Filter namespaces that end with this path.
+ max_depth: Return namespaces up to this depth in the hierarchy.
+ Namespaces deeper than this level will be truncated to this depth.
+ limit: Maximum number of namespaces to return.
+ offset: Number of namespaces to skip for pagination.
+
+ Returns:
+ A list of namespace tuples that match the criteria. Each tuple represents a
+ full namespace path up to `max_depth`.
+
+ ???+ example "Examples"
+
+ Setting `max_depth=3` with existing namespaces:
+ ```python
+ # Given the following namespaces:
+ # ("a", "b", "c")
+ # ("a", "b", "d", "e")
+ # ("a", "b", "d", "i")
+ # ("a", "b", "f")
+ # ("a", "c", "f")
+
+ await store.alist_namespaces(prefix=("a", "b"), max_depth=3)
+ # Returns: [("a", "b", "c"), ("a", "b", "d"), ("a", "b", "f")]
+ ```
+ """
+ match_conditions = []
+ if prefix:
+ match_conditions.append(MatchCondition(match_type="prefix", path=prefix))
+ if suffix:
+ match_conditions.append(MatchCondition(match_type="suffix", path=suffix))
+
+ op = ListNamespacesOp(
+ match_conditions=tuple(match_conditions),
+ max_depth=max_depth,
+ limit=limit,
+ offset=offset,
+ )
+ return (await self.abatch([op]))[0]
+
+
+def _validate_namespace(namespace: tuple[str, ...]) -> None:
+ if not namespace:
+ raise InvalidNamespaceError("Namespace cannot be empty.")
+ for label in namespace:
+ if not isinstance(label, str):
+ raise InvalidNamespaceError(
+ f"Invalid namespace label '{label}' found in {namespace}. Namespace labels"
+ f" must be strings, but got {type(label).__name__}."
+ )
+ if "." in label:
+ raise InvalidNamespaceError(
+ f"Invalid namespace label '{label}' found in {namespace}. Namespace labels cannot contain periods ('.')."
+ )
+ elif not label:
+ raise InvalidNamespaceError(
+ f"Namespace labels cannot be empty strings. Got {label} in {namespace}"
+ )
+ if namespace[0] == "langgraph":
+ raise InvalidNamespaceError(
+ f'Root label for namespace cannot be "langgraph". Got: {namespace}'
+ )
+
+
+def _ensure_refresh(
+ ttl_config: TTLConfig | None, refresh_ttl: bool | None = None
+) -> bool:
+ if refresh_ttl is not None:
+ return refresh_ttl
+ if ttl_config is not None:
+ return ttl_config.get("refresh_on_read", True)
+ return True
+
+
+def _ensure_ttl(
+ ttl_config: TTLConfig | None,
+ ttl: float | None | NotProvided = NOT_PROVIDED,
+) -> float | None:
+ if ttl is NOT_PROVIDED:
+ if ttl_config:
+ return ttl_config.get("default_ttl")
+ return None
+ return ttl
+
+
+__all__ = [
+ "BaseStore",
+ "Item",
+ "Op",
+ "PutOp",
+ "GetOp",
+ "SearchOp",
+ "ListNamespacesOp",
+ "MatchCondition",
+ "NamespacePath",
+ "NamespaceMatchType",
+ "Embeddings",
+ "ensure_embeddings",
+ "tokenize_path",
+ "get_text_at_path",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56b3ec54a68c2d51893f6c74a2a71a1938783bc5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/batch.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/batch.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9673dea44cbdebbcbd8dd3714918e88f2dacbd91
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/batch.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/embed.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/embed.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9216c6884be781986bddb15d4b09e73102ff91fe
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/store/base/__pycache__/embed.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/batch.py b/python/user_packages/Python313/site-packages/langgraph/store/base/batch.py
new file mode 100644
index 0000000000000000000000000000000000000000..64019d68fc04e30e523e0ff00f934674263411c2
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/store/base/batch.py
@@ -0,0 +1,371 @@
+"""Utilities for batching operations in a background task."""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import weakref
+from collections.abc import Callable, Iterable
+from typing import Any, Literal, TypeVar
+
+from langgraph.store.base import (
+ NOT_PROVIDED,
+ BaseStore,
+ GetOp,
+ Item,
+ ListNamespacesOp,
+ MatchCondition,
+ NamespacePath,
+ NotProvided,
+ Op,
+ PutOp,
+ Result,
+ SearchItem,
+ SearchOp,
+ _ensure_refresh,
+ _ensure_ttl,
+ _validate_namespace,
+)
+
+F = TypeVar("F", bound=Callable)
+
+
+def _check_loop(func: F) -> F:
+ @functools.wraps(func)
+ def wrapper(store: AsyncBatchedBaseStore, *args: Any, **kwargs: Any) -> Any:
+ method_name: str = func.__name__
+ try:
+ current_loop = asyncio.get_running_loop()
+ if current_loop is store._loop:
+ replacement_str = (
+ f"Specifically, replace `store.{method_name}(...)` with `await store.a{method_name}(...)"
+ if method_name
+ else "For example, replace `store.get(...)` with `await store.aget(...)`"
+ )
+ raise asyncio.InvalidStateError(
+ f"Synchronous calls to {store.__class__.__name__} detected in the main event loop. "
+ "This can lead to deadlocks or performance issues. "
+ "Please use the asynchronous interface for main thread operations. "
+ f"{replacement_str} "
+ )
+ except RuntimeError:
+ pass
+ return func(store, *args, **kwargs)
+
+ return wrapper
+
+
+class AsyncBatchedBaseStore(BaseStore):
+ """Efficiently batch operations in a background task."""
+
+ __slots__ = ("_loop", "_aqueue", "_task")
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._loop = asyncio.get_running_loop()
+ self._aqueue: asyncio.Queue[tuple[asyncio.Future, Op]] = asyncio.Queue()
+ self._task: asyncio.Task | None = None
+ self._ensure_task()
+
+ def __del__(self) -> None:
+ try:
+ if self._task:
+ self._task.cancel()
+ except RuntimeError:
+ pass
+
+ def _ensure_task(self) -> None:
+ """Ensure the background processing loop is running."""
+ if self._task is None or self._task.done():
+ self._task = self._loop.create_task(_run(self._aqueue, weakref.ref(self)))
+
+ async def aget(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ ) -> Item | None:
+ self._ensure_task()
+ fut = self._loop.create_future()
+ self._aqueue.put_nowait(
+ (
+ fut,
+ GetOp(
+ namespace,
+ key,
+ refresh_ttl=_ensure_refresh(self.ttl_config, refresh_ttl),
+ ),
+ )
+ )
+ return await fut
+
+ async def asearch(
+ self,
+ namespace_prefix: tuple[str, ...],
+ /,
+ *,
+ query: str | None = None,
+ filter: dict[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ refresh_ttl: bool | None = None,
+ ) -> list[SearchItem]:
+ self._ensure_task()
+ fut = self._loop.create_future()
+ self._aqueue.put_nowait(
+ (
+ fut,
+ SearchOp(
+ namespace_prefix,
+ filter,
+ limit,
+ offset,
+ query,
+ refresh_ttl=_ensure_refresh(self.ttl_config, refresh_ttl),
+ ),
+ )
+ )
+ return await fut
+
+ async def aput(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ *,
+ ttl: float | None | NotProvided = NOT_PROVIDED,
+ ) -> None:
+ self._ensure_task()
+ _validate_namespace(namespace)
+ fut = self._loop.create_future()
+ self._aqueue.put_nowait(
+ (
+ fut,
+ PutOp(
+ namespace, key, value, index, ttl=_ensure_ttl(self.ttl_config, ttl)
+ ),
+ )
+ )
+ return await fut
+
+ async def adelete(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ ) -> None:
+ self._ensure_task()
+ fut = self._loop.create_future()
+ self._aqueue.put_nowait((fut, PutOp(namespace, key, None)))
+ return await fut
+
+ async def alist_namespaces(
+ self,
+ *,
+ prefix: NamespacePath | None = None,
+ suffix: NamespacePath | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[tuple[str, ...]]:
+ self._ensure_task()
+ fut = self._loop.create_future()
+ match_conditions = []
+ if prefix:
+ match_conditions.append(MatchCondition(match_type="prefix", path=prefix))
+ if suffix:
+ match_conditions.append(MatchCondition(match_type="suffix", path=suffix))
+
+ op = ListNamespacesOp(
+ match_conditions=tuple(match_conditions),
+ max_depth=max_depth,
+ limit=limit,
+ offset=offset,
+ )
+ self._aqueue.put_nowait((fut, op))
+ return await fut
+
+ @_check_loop
+ def batch(self, ops: Iterable[Op]) -> list[Result]:
+ return asyncio.run_coroutine_threadsafe(self.abatch(ops), self._loop).result()
+
+ @_check_loop
+ def get(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ ) -> Item | None:
+ return asyncio.run_coroutine_threadsafe(
+ self.aget(namespace, key=key, refresh_ttl=refresh_ttl), self._loop
+ ).result()
+
+ @_check_loop
+ def search(
+ self,
+ namespace_prefix: tuple[str, ...],
+ /,
+ *,
+ query: str | None = None,
+ filter: dict[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ refresh_ttl: bool | None = None,
+ ) -> list[SearchItem]:
+ return asyncio.run_coroutine_threadsafe(
+ self.asearch(
+ namespace_prefix,
+ query=query,
+ filter=filter,
+ limit=limit,
+ offset=offset,
+ refresh_ttl=refresh_ttl,
+ ),
+ self._loop,
+ ).result()
+
+ @_check_loop
+ def put(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ *,
+ ttl: float | None | NotProvided = NOT_PROVIDED,
+ ) -> None:
+ _validate_namespace(namespace)
+ asyncio.run_coroutine_threadsafe(
+ self.aput(
+ namespace,
+ key=key,
+ value=value,
+ index=index,
+ ttl=_ensure_ttl(self.ttl_config, ttl),
+ ),
+ self._loop,
+ ).result()
+
+ @_check_loop
+ def delete(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ ) -> None:
+ asyncio.run_coroutine_threadsafe(
+ self.adelete(namespace, key=key), self._loop
+ ).result()
+
+ @_check_loop
+ def list_namespaces(
+ self,
+ *,
+ prefix: NamespacePath | None = None,
+ suffix: NamespacePath | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[tuple[str, ...]]:
+ return asyncio.run_coroutine_threadsafe(
+ self.alist_namespaces(
+ prefix=prefix,
+ suffix=suffix,
+ max_depth=max_depth,
+ limit=limit,
+ offset=offset,
+ ),
+ self._loop,
+ ).result()
+
+
+def _dedupe_ops(values: list[Op]) -> tuple[list[int] | None, list[Op]]:
+ """Dedupe operations while preserving order for results.
+
+ Args:
+ values: List of operations to dedupe
+
+ Returns:
+ Tuple of (listen indices, deduped operations)
+ where listen indices map deduped operation results back to original positions
+ """
+ if len(values) <= 1:
+ return None, list(values)
+
+ dedupped: list[Op] = []
+ listen: list[int] = []
+ puts: dict[tuple[tuple[str, ...], str], int] = {}
+
+ for op in values:
+ if isinstance(op, (GetOp, SearchOp, ListNamespacesOp)):
+ try:
+ listen.append(dedupped.index(op))
+ except ValueError:
+ listen.append(len(dedupped))
+ dedupped.append(op)
+ elif isinstance(op, PutOp):
+ putkey = (op.namespace, op.key)
+ if putkey in puts:
+ # Overwrite previous put
+ ix = puts[putkey]
+ dedupped[ix] = op
+ listen.append(ix)
+ else:
+ puts[putkey] = len(dedupped)
+ listen.append(len(dedupped))
+ dedupped.append(op)
+
+ else: # Any new ops will be treated regularly
+ listen.append(len(dedupped))
+ dedupped.append(op)
+
+ return listen, dedupped
+
+
+async def _run(
+ aqueue: asyncio.Queue[tuple[asyncio.Future, Op]],
+ store: weakref.ReferenceType[BaseStore],
+) -> None:
+ while item := await aqueue.get():
+ # don't run batch if the future is done (e.g. cancelled)
+ if item[0].done():
+ continue
+ # check if store is still alive
+ if s := store():
+ try:
+ # accumulate operations scheduled in same tick
+ items = [item]
+ try:
+ while item := aqueue.get_nowait():
+ # don't insert if the future is done (e.g. cancelled)
+ if item[0].done():
+ continue
+ items.append(item)
+ except asyncio.QueueEmpty:
+ pass
+ # get the operations to run
+ futs = [item[0] for item in items]
+ values = [item[1] for item in items]
+ # action each operation
+ try:
+ listen, dedupped = _dedupe_ops(values)
+ results = await s.abatch(dedupped)
+ if listen is not None:
+ results = [results[ix] for ix in listen]
+
+ # set the results of each operation
+ for fut, result in zip(futs, results, strict=False):
+ # guard against future being done (e.g. cancelled)
+ if not fut.done():
+ fut.set_result(result)
+ except Exception as e:
+ for fut in futs:
+ # guard against future being done (e.g. cancelled)
+ if not fut.done():
+ fut.set_exception(e)
+ finally:
+ # remove strong ref to store
+ del s
+ else:
+ break
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/embed.py b/python/user_packages/Python313/site-packages/langgraph/store/base/embed.py
new file mode 100644
index 0000000000000000000000000000000000000000..4255886e2b30b511d41e35f6df420f5f6de18a70
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/store/base/embed.py
@@ -0,0 +1,433 @@
+"""Utilities for working with embedding functions and LangChain's Embeddings interface.
+
+This module provides tools to wrap arbitrary embedding functions (both sync and async)
+into LangChain's Embeddings interface. This enables using custom embedding functions
+with LangChain-compatible tools while maintaining support for both synchronous and
+asynchronous operations.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import json
+from collections.abc import Awaitable, Callable, Sequence
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+
+EmbeddingsFunc = Callable[[Sequence[str]], list[list[float]]]
+"""Type for synchronous embedding functions.
+
+The function should take a sequence of strings and return a list of embeddings,
+where each embedding is a list of floats. The dimensionality of the embeddings
+should be consistent for all inputs.
+"""
+
+AEmbeddingsFunc = Callable[[Sequence[str]], Awaitable[list[list[float]]]]
+"""Type for asynchronous embedding functions.
+
+Similar to EmbeddingsFunc, but returns an awaitable that resolves to the embeddings.
+"""
+
+
+def ensure_embeddings(
+ embed: Embeddings | EmbeddingsFunc | AEmbeddingsFunc | str | None,
+) -> Embeddings:
+ """Ensure that an embedding function conforms to LangChain's Embeddings interface.
+
+ This function wraps arbitrary embedding functions to make them compatible with
+ LangChain's Embeddings interface. It handles both synchronous and asynchronous
+ functions.
+
+ Args:
+ embed: Either an existing Embeddings instance, or a function that converts
+ text to embeddings. If the function is async, it will be used for both
+ sync and async operations.
+
+ Returns:
+ An Embeddings instance that wraps the provided function(s).
+
+ ??? example "Examples"
+
+ Wrap a synchronous embedding function:
+
+ ```python
+ def my_embed_fn(texts):
+ return [[0.1, 0.2] for _ in texts]
+
+ embeddings = ensure_embeddings(my_embed_fn)
+ result = embeddings.embed_query("hello") # Returns [0.1, 0.2]
+ ```
+
+ Wrap an asynchronous embedding function:
+
+ ```python
+ async def my_async_fn(texts):
+ return [[0.1, 0.2] for _ in texts]
+
+ embeddings = ensure_embeddings(my_async_fn)
+ result = await embeddings.aembed_query("hello") # Returns [0.1, 0.2]
+ ```
+
+ Initialize embeddings using a provider string:
+
+ ```python
+ # Requires langchain>=0.3.9 and langgraph-checkpoint>=2.0.11
+ embeddings = ensure_embeddings("openai:text-embedding-3-small")
+ result = embeddings.embed_query("hello")
+ ```
+ """
+ if embed is None:
+ raise ValueError("embed must be provided")
+ if isinstance(embed, str):
+ init_embeddings = _get_init_embeddings()
+ if init_embeddings is None:
+ from importlib.metadata import PackageNotFoundError, version
+
+ try:
+ lc_version = version("langchain")
+ version_info = f"Found langchain version {lc_version}, but"
+ except PackageNotFoundError:
+ version_info = "langchain is not installed;"
+
+ raise ValueError(
+ f"Could not load embeddings from string '{embed}'. {version_info} "
+ "loading embeddings by provider:identifier string requires langchain>=0.3.9 "
+ "as well as the provider-specific package. "
+ "Install LangChain with: pip install 'langchain>=0.3.9' "
+ "and the provider-specific package (e.g., 'langchain-openai>=0.3.0'). "
+ "Alternatively, specify 'embed' as a compatible Embeddings object or python function."
+ )
+ return init_embeddings(embed)
+
+ if isinstance(embed, Embeddings):
+ return embed
+ return EmbeddingsLambda(embed)
+
+
+class EmbeddingsLambda(Embeddings):
+ """Wrapper to convert embedding functions into LangChain's Embeddings interface.
+
+ This class allows arbitrary embedding functions to be used with LangChain-compatible
+ tools. It supports both synchronous and asynchronous operations, and can handle:
+ 1. A synchronous function for sync operations (async operations will use sync function)
+ 2. An async function for both sync/async operations (sync operations will raise an error)
+
+ The embedding functions should convert text into fixed-dimensional vectors that
+ capture the semantic meaning of the text.
+
+ Args:
+ func: Function that converts text to embeddings. Can be sync or async.
+ If async, it will be used for async operations, but sync operations
+ will raise an error. If sync, it will be used for both sync and async operations.
+
+ ??? example "Examples"
+
+ With a sync function:
+
+ ```python
+ def my_embed_fn(texts):
+ # Return 2D embeddings for each text
+ return [[0.1, 0.2] for _ in texts]
+
+ embeddings = EmbeddingsLambda(my_embed_fn)
+ result = embeddings.embed_query("hello") # Returns [0.1, 0.2]
+ await embeddings.aembed_query("hello") # Also returns [0.1, 0.2]
+ ```
+
+ With an async function:
+
+ ```python
+ async def my_async_fn(texts):
+ return [[0.1, 0.2] for _ in texts]
+
+ embeddings = EmbeddingsLambda(my_async_fn)
+ await embeddings.aembed_query("hello") # Returns [0.1, 0.2]
+ # Note: embed_query() would raise an error
+ ```
+ """
+
+ def __init__(
+ self,
+ func: EmbeddingsFunc | AEmbeddingsFunc,
+ ) -> None:
+ if func is None:
+ raise ValueError("func must be provided")
+ if _is_async_callable(func):
+ self.afunc = func
+ else:
+ self.func = func
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Embed a list of texts into vectors.
+
+ Args:
+ texts: list of texts to convert to embeddings.
+
+ Returns:
+ list of embeddings, one per input text. Each embedding is a list of floats.
+
+ Raises:
+ ValueError: If the instance was initialized with only an async function.
+ """
+ func = getattr(self, "func", None)
+ if func is None:
+ raise ValueError(
+ "EmbeddingsLambda was initialized with an async function but no sync function. "
+ "Use aembed_documents for async operation or provide a sync function."
+ )
+ return func(texts)
+
+ def embed_query(self, text: str) -> list[float]:
+ """Embed a single piece of text.
+
+ Args:
+ text: Text to convert to an embedding.
+
+ Returns:
+ Embedding vector as a list of floats.
+
+ Note:
+ This is equivalent to calling embed_documents with a single text
+ and taking the first result.
+ """
+ return self.embed_documents([text])[0]
+
+ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Asynchronously embed a list of texts into vectors.
+
+ Args:
+ texts: list of texts to convert to embeddings.
+
+ Returns:
+ list of embeddings, one per input text. Each embedding is a list of floats.
+
+ Note:
+ If no async function was provided, this falls back to the sync implementation.
+ """
+ afunc = getattr(self, "afunc", None)
+ if afunc is None:
+ return await super().aembed_documents(texts)
+ return await afunc(texts)
+
+ async def aembed_query(self, text: str) -> list[float]:
+ """Asynchronously embed a single piece of text.
+
+ Args:
+ text: Text to convert to an embedding.
+
+ Returns:
+ Embedding vector as a list of floats.
+
+ Note:
+ This is equivalent to calling aembed_documents with a single text
+ and taking the first result.
+ """
+ afunc = getattr(self, "afunc", None)
+ if afunc is None:
+ return await super().aembed_query(text)
+ return (await afunc([text]))[0]
+
+
+def get_text_at_path(obj: Any, path: str | list[str]) -> list[str]:
+ """Extract text from an object using a path expression or pre-tokenized path.
+
+ Args:
+ obj: The object to extract text from
+ path: Either a path string or pre-tokenized path list.
+
+ !!! info "Path types handled"
+ - Simple paths: "field1.field2"
+ - Array indexing: "[0]", "[*]", "[-1]"
+ - Wildcards: "*"
+ - Multi-field selection: "{field1,field2}"
+ - Nested paths in multi-field: "{field1,nested.field2}"
+ """
+ if not path or path == "$":
+ return [json.dumps(obj, sort_keys=True, ensure_ascii=False)]
+
+ tokens = tokenize_path(path) if isinstance(path, str) else path
+
+ def _extract_from_obj(obj: Any, tokens: list[str], pos: int) -> list[str]:
+ if pos >= len(tokens):
+ if isinstance(obj, (str, int, float, bool)):
+ return [str(obj)]
+ elif obj is None:
+ return []
+ elif isinstance(obj, (list, dict)):
+ return [json.dumps(obj, sort_keys=True, ensure_ascii=False)]
+ return []
+
+ token = tokens[pos]
+ results = []
+
+ if token.startswith("[") and token.endswith("]"):
+ if not isinstance(obj, list):
+ return []
+
+ index = token[1:-1]
+ if index == "*":
+ for item in obj:
+ results.extend(_extract_from_obj(item, tokens, pos + 1))
+ else:
+ try:
+ idx = int(index)
+ if idx < 0:
+ idx = len(obj) + idx
+ if 0 <= idx < len(obj):
+ results.extend(_extract_from_obj(obj[idx], tokens, pos + 1))
+ except (ValueError, IndexError):
+ return []
+
+ elif token.startswith("{") and token.endswith("}"):
+ if not isinstance(obj, dict):
+ return []
+
+ fields = [f.strip() for f in token[1:-1].split(",")]
+ for field in fields:
+ nested_tokens = tokenize_path(field)
+ if nested_tokens:
+ current_obj: dict | None = obj
+ for nested_token in nested_tokens:
+ if (
+ isinstance(current_obj, dict)
+ and nested_token in current_obj
+ ):
+ current_obj = current_obj[nested_token]
+ else:
+ current_obj = None
+ break
+ if current_obj is not None:
+ if isinstance(current_obj, (str, int, float, bool)):
+ results.append(str(current_obj))
+ elif isinstance(current_obj, (list, dict)):
+ results.append(
+ json.dumps(
+ current_obj, sort_keys=True, ensure_ascii=False
+ )
+ )
+
+ # Handle wildcard
+ elif token == "*":
+ if isinstance(obj, dict):
+ for value in obj.values():
+ results.extend(_extract_from_obj(value, tokens, pos + 1))
+ elif isinstance(obj, list):
+ for item in obj:
+ results.extend(_extract_from_obj(item, tokens, pos + 1))
+
+ # Handle regular field
+ else:
+ if isinstance(obj, dict) and token in obj:
+ results.extend(_extract_from_obj(obj[token], tokens, pos + 1))
+
+ return results
+
+ return _extract_from_obj(obj, tokens, 0)
+
+
+# Private utility functions
+
+
+def tokenize_path(path: str) -> list[str]:
+ """Tokenize a path into components.
+
+ !!! info "Types handled"
+ - Simple paths: "field1.field2"
+ - Array indexing: "[0]", "[*]", "[-1]"
+ - Wildcards: "*"
+ - Multi-field selection: "{field1,field2}"
+ """
+ if not path:
+ return []
+
+ tokens = []
+ current: list[str] = []
+ i = 0
+ while i < len(path):
+ char = path[i]
+
+ if char == "[": # Handle array index
+ if current:
+ tokens.append("".join(current))
+ current = []
+ bracket_count = 1
+ index_chars = ["["]
+ i += 1
+ while i < len(path) and bracket_count > 0:
+ if path[i] == "[":
+ bracket_count += 1
+ elif path[i] == "]":
+ bracket_count -= 1
+ index_chars.append(path[i])
+ i += 1
+ tokens.append("".join(index_chars))
+ continue
+
+ elif char == "{": # Handle multi-field selection
+ if current:
+ tokens.append("".join(current))
+ current = []
+ brace_count = 1
+ field_chars = ["{"]
+ i += 1
+ while i < len(path) and brace_count > 0:
+ if path[i] == "{":
+ brace_count += 1
+ elif path[i] == "}":
+ brace_count -= 1
+ field_chars.append(path[i])
+ i += 1
+ tokens.append("".join(field_chars))
+ continue
+
+ elif char == ".": # Handle regular field
+ if current:
+ tokens.append("".join(current))
+ current = []
+ else:
+ current.append(char)
+ i += 1
+
+ if current:
+ tokens.append("".join(current))
+
+ return tokens
+
+
+def _is_async_callable(
+ func: Any,
+) -> bool:
+ """Check if a function is async.
+
+ This includes both async def functions and classes with async __call__ methods.
+
+ Args:
+ func: Function or callable object to check.
+
+ Returns:
+ True if the function is async, False otherwise.
+ """
+ return (
+ asyncio.iscoroutinefunction(func)
+ or hasattr(func, "__call__") # noqa: B004
+ and asyncio.iscoroutinefunction(func.__call__)
+ )
+
+
+@functools.lru_cache
+def _get_init_embeddings() -> Callable[[str], Embeddings] | None:
+ try:
+ from langchain.embeddings import init_embeddings # type: ignore
+
+ return init_embeddings
+ except ImportError:
+ return None
+
+
+__all__ = [
+ "ensure_embeddings",
+ "EmbeddingsFunc",
+ "AEmbeddingsFunc",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/base/py.typed b/python/user_packages/Python313/site-packages/langgraph/store/base/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/memory/__init__.py b/python/user_packages/Python313/site-packages/langgraph/store/memory/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b156c457df67ca021e090d90c1373e2d713a2123
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/store/memory/__init__.py
@@ -0,0 +1,592 @@
+"""In-memory dictionary-backed store with optional vector search.
+
+!!! example "Examples"
+ Basic key-value storage:
+ ```python
+ from langgraph.store.memory import InMemoryStore
+
+ store = InMemoryStore()
+ store.put(("users", "123"), "prefs", {"theme": "dark"})
+ item = store.get(("users", "123"), "prefs")
+ ```
+
+ Vector search using LangChain embeddings:
+ ```python
+ from langchain.embeddings import init_embeddings
+ from langgraph.store.memory import InMemoryStore
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": init_embeddings("openai:text-embedding-3-small")
+ }
+ )
+
+ # Store documents
+ store.put(("docs",), "doc1", {"text": "Python tutorial"})
+ store.put(("docs",), "doc2", {"text": "TypeScript guide"})
+
+ # Search by similarity
+ results = store.search(("docs",), query="python programming")
+ ```
+
+ Vector search using OpenAI SDK directly:
+ ```python
+ from openai import OpenAI
+ from langgraph.store.memory import InMemoryStore
+
+ client = OpenAI()
+
+ def embed_texts(texts: list[str]) -> list[list[float]]:
+ response = client.embeddings.create(
+ model="text-embedding-3-small",
+ input=texts
+ )
+ return [e.embedding for e in response.data]
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": embed_texts
+ }
+ )
+
+ # Store documents
+ store.put(("docs",), "doc1", {"text": "Python tutorial"})
+ store.put(("docs",), "doc2", {"text": "TypeScript guide"})
+
+ # Search by similarity
+ results = store.search(("docs",), query="python programming")
+ ```
+
+ Async vector search using OpenAI SDK:
+ ```python
+ from openai import AsyncOpenAI
+ from langgraph.store.memory import InMemoryStore
+
+ client = AsyncOpenAI()
+
+ async def aembed_texts(texts: list[str]) -> list[list[float]]:
+ response = await client.embeddings.create(
+ model="text-embedding-3-small",
+ input=texts
+ )
+ return [e.embedding for e in response.data]
+
+ store = InMemoryStore(
+ index={
+ "dims": 1536,
+ "embed": aembed_texts
+ }
+ )
+
+ # Store documents
+ await store.aput(("docs",), "doc1", {"text": "Python tutorial"})
+ await store.aput(("docs",), "doc2", {"text": "TypeScript guide"})
+
+ # Search by similarity
+ results = await store.asearch(("docs",), query="python programming")
+ ```
+
+Warning:
+ This store keeps all data in memory. Data is lost when the process exits.
+ For persistence, use a database-backed store like PostgresStore.
+
+Tip:
+ For vector search, install numpy for better performance:
+ ```bash
+ pip install numpy
+ ```
+"""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures as cf
+import functools
+import logging
+from collections import defaultdict
+from collections.abc import Iterable
+from datetime import datetime, timezone
+from importlib import util
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+
+from langgraph.store.base import (
+ BaseStore,
+ GetOp,
+ IndexConfig,
+ Item,
+ ListNamespacesOp,
+ MatchCondition,
+ Op,
+ PutOp,
+ Result,
+ SearchItem,
+ SearchOp,
+ ensure_embeddings,
+ get_text_at_path,
+ tokenize_path,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class InMemoryStore(BaseStore):
+ """In-memory dictionary-backed store with optional vector search.
+
+ !!! example "Examples"
+ Basic key-value storage:
+ store = InMemoryStore()
+ store.put(("users", "123"), "prefs", {"theme": "dark"})
+ item = store.get(("users", "123"), "prefs")
+
+ Vector search with embeddings:
+ from langchain.embeddings import init_embeddings
+ store = InMemoryStore(index={
+ "dims": 1536,
+ "embed": init_embeddings("openai:text-embedding-3-small"),
+ "fields": ["text"],
+ })
+
+ # Store documents
+ store.put(("docs",), "doc1", {"text": "Python tutorial"})
+ store.put(("docs",), "doc2", {"text": "TypeScript guide"})
+
+ # Search by similarity
+ results = store.search(("docs",), query="python programming")
+
+ Note:
+ Semantic search is disabled by default. You can enable it by providing an `index` configuration
+ when creating the store. Without this configuration, all `index` arguments passed to
+ `put` or `aput`will have no effect.
+
+ Warning:
+ This store keeps all data in memory. Data is lost when the process exits.
+ For persistence, use a database-backed store like PostgresStore.
+
+ Tip:
+ For vector search, install numpy for better performance:
+ ```bash
+ pip install numpy
+ ```
+ """
+
+ __slots__ = (
+ "_data",
+ "_vectors",
+ "index_config",
+ "embeddings",
+ )
+
+ def __init__(self, *, index: IndexConfig | None = None) -> None:
+ # Both _data and _vectors are wrapped in the In-memory API
+ # Do not change their names
+ self._data: dict[tuple[str, ...], dict[str, Item]] = defaultdict(dict)
+ # [ns][key][path]
+ self._vectors: dict[tuple[str, ...], dict[str, dict[str, list[float]]]] = (
+ defaultdict(lambda: defaultdict(dict))
+ )
+ self.index_config = index
+ if self.index_config:
+ self.index_config = self.index_config.copy()
+ self.embeddings: Embeddings | None = ensure_embeddings(
+ self.index_config.get("embed"),
+ )
+ self.index_config["__tokenized_fields"] = [
+ (p, tokenize_path(p)) if p != "$" else (p, p)
+ for p in (self.index_config.get("fields") or ["$"])
+ ]
+
+ else:
+ self.index_config = None
+ self.embeddings = None
+
+ def batch(self, ops: Iterable[Op]) -> list[Result]:
+ # The batch/abatch methods are treated as internal.
+ # Users should access via put/search/get/list_namespaces/etc.
+ results, put_ops, search_ops = self._prepare_ops(ops)
+ if search_ops:
+ queryinmem_store = self._embed_search_queries(search_ops)
+ self._batch_search(search_ops, queryinmem_store, results)
+
+ to_embed = self._extract_texts(put_ops)
+ if to_embed and self.index_config and self.embeddings:
+ embeddings = self.embeddings.embed_documents(list(to_embed))
+ self._insertinmem_store(to_embed, embeddings)
+ self._apply_put_ops(put_ops)
+ return results
+
+ async def abatch(self, ops: Iterable[Op]) -> list[Result]:
+ # The batch/abatch methods are treated as internal.
+ # Users should access via put/search/get/list_namespaces/etc.
+ results, put_ops, search_ops = self._prepare_ops(ops)
+ if search_ops:
+ queryinmem_store = await self._aembed_search_queries(search_ops)
+ self._batch_search(search_ops, queryinmem_store, results)
+
+ to_embed = self._extract_texts(put_ops)
+ if to_embed and self.index_config and self.embeddings:
+ embeddings = await self.embeddings.aembed_documents(list(to_embed))
+ self._insertinmem_store(to_embed, embeddings)
+ self._apply_put_ops(put_ops)
+ return results
+
+ # Helpers
+
+ def _filter_items(self, op: SearchOp) -> list[tuple[Item, list[list[float]]]]:
+ """Filter items by namespace and filter function, return items with their embeddings."""
+ namespace_prefix = op.namespace_prefix
+
+ def filter_func(item: Item) -> bool:
+ if not op.filter:
+ return True
+
+ return all(
+ _compare_values(item.value.get(key), filter_value)
+ for key, filter_value in op.filter.items()
+ )
+
+ filtered = []
+ for namespace in self._data:
+ if not (
+ namespace[: len(namespace_prefix)] == namespace_prefix
+ if len(namespace) >= len(namespace_prefix)
+ else False
+ ):
+ continue
+
+ for key, item in self._data[namespace].items():
+ if filter_func(item):
+ if op.query and (embeddings := self._vectors[namespace].get(key)):
+ filtered.append((item, list(embeddings.values())))
+ else:
+ filtered.append((item, []))
+ return filtered
+
+ def _embed_search_queries(
+ self,
+ search_ops: dict[int, tuple[SearchOp, list[tuple[Item, list[list[float]]]]]],
+ ) -> dict[str, list[float]]:
+ queryinmem_store = {}
+ if self.index_config and self.embeddings and search_ops:
+ queries = {op.query for (op, _) in search_ops.values() if op.query}
+
+ if queries:
+ with cf.ThreadPoolExecutor() as executor:
+ futures = {
+ q: executor.submit(self.embeddings.embed_query, q)
+ for q in list(queries)
+ }
+ for query, future in futures.items():
+ queryinmem_store[query] = future.result()
+
+ return queryinmem_store
+
+ async def _aembed_search_queries(
+ self,
+ search_ops: dict[int, tuple[SearchOp, list[tuple[Item, list[list[float]]]]]],
+ ) -> dict[str, list[float]]:
+ queryinmem_store = {}
+ if self.index_config and self.embeddings and search_ops:
+ queries = {op.query for (op, _) in search_ops.values() if op.query}
+
+ if queries:
+ coros = [self.embeddings.aembed_query(q) for q in list(queries)]
+ results = await asyncio.gather(*coros)
+ queryinmem_store = dict(zip(queries, results, strict=False))
+
+ return queryinmem_store
+
+ def _batch_search(
+ self,
+ ops: dict[int, tuple[SearchOp, list[tuple[Item, list[list[float]]]]]],
+ queryinmem_store: dict[str, list[float]],
+ results: list[Result],
+ ) -> None:
+ """Perform batch similarity search for multiple queries."""
+ for i, (op, candidates) in ops.items():
+ if not candidates:
+ results[i] = []
+ continue
+ if op.query and queryinmem_store:
+ query_embedding = queryinmem_store[op.query]
+ flat_items, flat_vectors = [], []
+ scoreless = []
+ for item, vectors in candidates:
+ for vector in vectors:
+ flat_items.append(item)
+ flat_vectors.append(vector)
+ if not vectors:
+ scoreless.append(item)
+
+ scores = _cosine_similarity(query_embedding, flat_vectors)
+ sorted_results = sorted(
+ zip(scores, flat_items, strict=False),
+ key=lambda x: x[0],
+ reverse=True,
+ )
+ # max pooling
+ seen: set[tuple[tuple[str, ...], str]] = set()
+ kept: list[tuple[float | None, Item]] = []
+ for score, item in sorted_results:
+ key = (item.namespace, item.key)
+ if key in seen:
+ continue
+ ix = len(seen)
+ seen.add(key)
+ if ix >= op.offset + op.limit:
+ break
+ if ix < op.offset:
+ continue
+
+ kept.append((score, item))
+ if scoreless and len(kept) < op.limit:
+ # Corner case: if we request more items than what we have embedded,
+ # fill the rest with non-scored items
+ kept.extend(
+ (None, item) for item in scoreless[: op.limit - len(kept)]
+ )
+
+ results[i] = [
+ SearchItem(
+ namespace=item.namespace,
+ key=item.key,
+ value=item.value,
+ created_at=item.created_at,
+ updated_at=item.updated_at,
+ score=float(score) if score is not None else None,
+ )
+ for score, item in kept
+ ]
+ else:
+ results[i] = [
+ SearchItem(
+ namespace=item.namespace,
+ key=item.key,
+ value=item.value,
+ created_at=item.created_at,
+ updated_at=item.updated_at,
+ )
+ for (item, _) in candidates[op.offset : op.offset + op.limit]
+ ]
+
+ def _prepare_ops(
+ self, ops: Iterable[Op]
+ ) -> tuple[
+ list[Result],
+ dict[tuple[tuple[str, ...], str], PutOp],
+ dict[int, tuple[SearchOp, list[tuple[Item, list[list[float]]]]]],
+ ]:
+ results: list[Result] = []
+ put_ops: dict[tuple[tuple[str, ...], str], PutOp] = {}
+ search_ops: dict[
+ int, tuple[SearchOp, list[tuple[Item, list[list[float]]]]]
+ ] = {}
+ for i, op in enumerate(ops):
+ if isinstance(op, GetOp):
+ item = self._data[op.namespace].get(op.key)
+ results.append(item)
+ elif isinstance(op, SearchOp):
+ search_ops[i] = (op, self._filter_items(op))
+ results.append(None)
+ elif isinstance(op, ListNamespacesOp):
+ results.append(self._handle_list_namespaces(op))
+ elif isinstance(op, PutOp):
+ put_ops[(op.namespace, op.key)] = op
+ results.append(None)
+ else:
+ raise ValueError(f"Unknown operation type: {type(op)}")
+
+ return results, put_ops, search_ops
+
+ def _apply_put_ops(self, put_ops: dict[tuple[tuple[str, ...], str], PutOp]) -> None:
+ for (namespace, key), op in put_ops.items():
+ if op.value is None:
+ self._data[namespace].pop(key, None)
+ self._vectors[namespace].pop(key, None)
+ else:
+ self._data[namespace][key] = Item(
+ value=op.value,
+ key=key,
+ namespace=namespace,
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ )
+
+ def _extract_texts(
+ self, put_ops: dict[tuple[tuple[str, ...], str], PutOp]
+ ) -> dict[str, list[tuple[tuple[str, ...], str, str]]]:
+ if put_ops and self.index_config and self.embeddings:
+ to_embed = defaultdict(list)
+
+ for op in put_ops.values():
+ if op.value is not None and op.index is not False:
+ if op.index is None:
+ paths = self.index_config["__tokenized_fields"]
+ else:
+ paths = [(ix, tokenize_path(ix)) for ix in op.index]
+ for path, field in paths:
+ texts = get_text_at_path(op.value, field)
+ if texts:
+ if len(texts) > 1:
+ for i, text in enumerate(texts):
+ to_embed[text].append(
+ (op.namespace, op.key, f"{path}.{i}")
+ )
+
+ else:
+ to_embed[texts[0]].append((op.namespace, op.key, path))
+
+ return to_embed
+
+ return {}
+
+ def _insertinmem_store(
+ self,
+ to_embed: dict[str, list[tuple[tuple[str, ...], str, str]]],
+ embeddings: list[list[float]],
+ ) -> None:
+ indices = [index for indices in to_embed.values() for index in indices]
+ if len(indices) != len(embeddings):
+ raise ValueError(
+ f"Number of embeddings ({len(embeddings)}) does not"
+ f" match number of indices ({len(indices)})"
+ )
+ for embedding, (ns, key, path) in zip(embeddings, indices, strict=False):
+ self._vectors[ns][key][path] = embedding
+
+ def _handle_list_namespaces(self, op: ListNamespacesOp) -> list[tuple[str, ...]]:
+ all_namespaces = list(
+ self._data.keys()
+ ) # Avoid collection size changing while iterating
+ namespaces = all_namespaces
+ if op.match_conditions:
+ namespaces = [
+ ns
+ for ns in namespaces
+ if all(_does_match(condition, ns) for condition in op.match_conditions)
+ ]
+
+ if op.max_depth is not None:
+ namespaces = sorted({ns[: op.max_depth] for ns in namespaces})
+ else:
+ namespaces = sorted(namespaces)
+ return namespaces[op.offset : op.offset + op.limit]
+
+
+@functools.lru_cache(maxsize=1)
+def _check_numpy() -> bool:
+ if bool(util.find_spec("numpy")):
+ return True
+ logger.warning(
+ "NumPy not found in the current Python environment. "
+ "The InMemoryStore will use a pure Python implementation for vector operations, "
+ "which may significantly impact performance, especially for large datasets or frequent searches. "
+ "For optimal speed and efficiency, consider installing NumPy: "
+ "pip install numpy"
+ )
+ return False
+
+
+def _cosine_similarity(X: list[float], Y: list[list[float]]) -> list[float]:
+ """
+ Compute cosine similarity between a vector X and a matrix Y.
+ Lazy import numpy for efficiency.
+ """
+ if not Y:
+ return []
+ if _check_numpy():
+ import numpy as np
+
+ X_arr = np.array(X) if not isinstance(X, np.ndarray) else X
+ Y_arr = np.array(Y) if not isinstance(Y, np.ndarray) else Y
+ X_norm = np.linalg.norm(X_arr)
+ Y_norm = np.linalg.norm(Y_arr, axis=1)
+
+ # Avoid division by zero
+ mask = Y_norm != 0
+ similarities = np.zeros_like(Y_norm)
+ similarities[mask] = np.dot(Y_arr[mask], X_arr) / (Y_norm[mask] * X_norm)
+ return similarities.tolist()
+
+ similarities = []
+ for y in Y:
+ dot_product = sum(a * b for a, b in zip(X, y, strict=False))
+ norm1 = sum(a * a for a in X) ** 0.5
+ norm2 = sum(a * a for a in y) ** 0.5
+ similarity = dot_product / (norm1 * norm2) if norm1 > 0 and norm2 > 0 else 0.0
+ similarities.append(similarity)
+
+ return similarities
+
+
+def _does_match(match_condition: MatchCondition, key: tuple[str, ...]) -> bool:
+ """Whether a namespace key matches a match condition."""
+ match_type = match_condition.match_type
+ path = match_condition.path
+
+ if len(key) < len(path):
+ return False
+
+ if match_type == "prefix":
+ for k_elem, p_elem in zip(key, path, strict=False):
+ if p_elem == "*":
+ continue # Wildcard matches any element
+ if k_elem != p_elem:
+ return False
+ return True
+ elif match_type == "suffix":
+ for k_elem, p_elem in zip(reversed(key), reversed(path), strict=False):
+ if p_elem == "*":
+ continue # Wildcard matches any element
+ if k_elem != p_elem:
+ return False
+ return True
+ else:
+ raise ValueError(f"Unsupported match type: {match_type}")
+
+
+def _compare_values(item_value: Any, filter_value: Any) -> bool:
+ """Compare values in a JSONB-like way, handling nested objects."""
+ if isinstance(filter_value, dict):
+ if any(k.startswith("$") for k in filter_value):
+ return all(
+ _apply_operator(item_value, op_key, op_value)
+ for op_key, op_value in filter_value.items()
+ )
+ if not isinstance(item_value, dict):
+ return False
+ return all(
+ _compare_values(item_value.get(k), v) for k, v in filter_value.items()
+ )
+ elif isinstance(filter_value, (list, tuple)):
+ return (
+ isinstance(item_value, (list, tuple))
+ and len(item_value) == len(filter_value)
+ and all(
+ _compare_values(iv, fv)
+ for iv, fv in zip(item_value, filter_value, strict=False)
+ )
+ )
+ else:
+ return item_value == filter_value
+
+
+def _apply_operator(value: Any, operator: str, op_value: Any) -> bool:
+ """Apply a comparison operator, matching PostgreSQL's JSONB behavior."""
+ if operator == "$eq":
+ return value == op_value
+ elif operator == "$gt":
+ return float(value) > float(op_value)
+ elif operator == "$gte":
+ return float(value) >= float(op_value)
+ elif operator == "$lt":
+ return float(value) < float(op_value)
+ elif operator == "$lte":
+ return float(value) <= float(op_value)
+ elif operator == "$ne":
+ return value != op_value
+ else:
+ raise ValueError(f"Unsupported operator: {operator}")
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/memory/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/store/memory/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..511e1f8961c11cfa4560b8c5815fb235e19a1e8a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/store/memory/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/store/memory/py.typed b/python/user_packages/Python313/site-packages/langgraph/store/memory/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__init__.py b/python/user_packages/Python313/site-packages/langgraph/stream/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e67b5131ab76912e440f5386c866dd761ba5c120
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/__init__.py
@@ -0,0 +1,45 @@
+"""Streaming infrastructure for LangGraph.
+
+Compile a graph with `transformers=[...]` and call `graph.stream_events(version="v3")` /
+`graph.astream_events(version="v3")` to drive a transformer pipeline that projects the
+graph's raw events into ergonomic per-channel streams.
+"""
+
+from langgraph.stream._types import ProtocolEvent, StreamTransformer
+from langgraph.stream.run_stream import (
+ AsyncGraphRunStream,
+ AsyncSubgraphRunStream,
+ GraphRunStream,
+ SubgraphRunStream,
+)
+from langgraph.stream.stream_channel import StreamChannel
+from langgraph.stream.transformers import (
+ CheckpointsTransformer,
+ CustomTransformer,
+ DebugTransformer,
+ LifecyclePayload,
+ LifecycleTransformer,
+ SubgraphStatus,
+ SubgraphTransformer,
+ TasksTransformer,
+ UpdatesTransformer,
+)
+
+__all__ = [
+ "AsyncGraphRunStream",
+ "AsyncSubgraphRunStream",
+ "CheckpointsTransformer",
+ "CustomTransformer",
+ "DebugTransformer",
+ "GraphRunStream",
+ "LifecyclePayload",
+ "LifecycleTransformer",
+ "ProtocolEvent",
+ "StreamChannel",
+ "StreamTransformer",
+ "SubgraphRunStream",
+ "SubgraphStatus",
+ "SubgraphTransformer",
+ "TasksTransformer",
+ "UpdatesTransformer",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62e50ed9c7a90ba83679fcb130af2ad2253493ba
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_convert.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_convert.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5238bc1f56ac464137361fed66cbc61f11ee717
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_convert.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_mux.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_mux.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5b026b0aba9fdeb0b9480ea8032d02cb06a0061
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_mux.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee60e0d874af3371ee47c9efd1cd56b2521d142f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/_types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/run_stream.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/run_stream.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afedf9ed37b2b733767190340e280de70b664de1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/run_stream.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/stream_channel.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/stream_channel.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1108889a6781c07e0d144d2c25f2ccd644fd2c3d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/stream_channel.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/transformers.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/transformers.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..905efdacaa3565d64955fa2de484f70ff4d88f4e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/stream/__pycache__/transformers.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/_convert.py b/python/user_packages/Python313/site-packages/langgraph/stream/_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1a14b5b0d9e95d0b8e40b112e65f239ff4c4265
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/_convert.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+import time
+from typing import Any, cast
+
+from langgraph.stream._types import ProtocolEvent, _ProtocolEventParams
+from langgraph.types import StreamPart
+
+
+def convert_to_protocol_event(part: StreamPart) -> ProtocolEvent:
+ """Convert a v2 StreamPart to a ProtocolEvent.
+
+ Args:
+ part: A stream part with keys `type`, `ns`, `data`, and
+ optionally `interrupts` (present on values events).
+
+ Returns:
+ The equivalent ProtocolEvent.
+ """
+ part_dict = cast(dict[str, Any], part)
+ params: _ProtocolEventParams = {
+ "namespace": list(part_dict["ns"]),
+ "timestamp": int(time.time() * 1000),
+ "data": part_dict["data"],
+ }
+ if "interrupts" in part_dict:
+ params["interrupts"] = part_dict["interrupts"]
+ return {
+ "type": "event",
+ "method": part_dict["type"],
+ "params": params,
+ }
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/_mux.py b/python/user_packages/Python313/site-packages/langgraph/stream/_mux.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb09154e4a6418ab998f2011cc54cee33ec6c80a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/_mux.py
@@ -0,0 +1,498 @@
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from langgraph.stream._types import (
+ ProtocolEvent,
+ StreamTransformer,
+ transformer_requires_async,
+)
+from langgraph.stream.stream_channel import StreamChannel
+
+TransformerFactory = Callable[["tuple[str, ...]"], StreamTransformer]
+"""Factory that builds a scoped transformer for a mux.
+
+Called once per `StreamMux` with the mux's scope (typically `()` for
+the root). Standard transformer classes accept a single positional
+scope argument, so the class itself is a valid factory. User
+transformers can close over their config:
+`lambda scope: MyTransformer(scope, foo=...)`.
+"""
+
+
+class StreamMux:
+ """Central event dispatcher for the streaming infrastructure.
+
+ Owns the main event log and routes events through a transformer
+ pipeline. StreamChannels with a name discovered in transformer
+ projections are auto-wired so that every `push()` also injects a
+ `ProtocolEvent` into the main log. StreamChannels without a name
+ are local-only.
+
+ Pass `is_async=True` when the mux will be consumed via async
+ iteration (`handler.astream()`). All StreamChannel instances
+ discovered during registration are automatically bound to the
+ matching mode.
+
+ Attributes:
+ extensions: Merged projection dict across all registered
+ transformers. Treat as read-only — mutations won't be
+ reflected back in individual transformers' state.
+ native_keys: Projection keys contributed by transformers with
+ `_native = True`.
+ """
+
+ def __init__(
+ self,
+ transformers: list[StreamTransformer] | None = None,
+ *,
+ is_async: bool = False,
+ factories: list[TransformerFactory] | None = None,
+ scope: tuple[str, ...] = (),
+ _assign_seq: bool = True,
+ ) -> None:
+ """Initialize the mux and register transformers in order.
+
+ Callers pass either `transformers` (pre-built instances) or
+ `factories` (callables producing fresh instances per mux). Each
+ transformer's `init()` is called, projections are merged into
+ `extensions`, `_native` keys are recorded in `native_keys`, and
+ any StreamChannel instances are bound and (if named) wired.
+
+ Args:
+ transformers: Already-built transformer instances. Registered
+ only on this mux — they are NOT cloned into child
+ mini-muxes built by `_make_child`. Use `factories` for
+ transformers that should propagate to nested scopes.
+ is_async: True for async dispatch (`apush` / `aclose` /
+ `afail`), False for the sync path.
+ factories: One-argument callables `(scope) -> StreamTransformer`.
+ Called once with this mux's `scope` here, and cloned
+ again per child scope by `_make_child` so each
+ sub-mux gets fresh instances.
+ scope: The namespace the mux operates within. The root mux
+ is `()`.
+ _assign_seq: Internal flag for child muxes. Root muxes assign
+ monotonic `seq` numbers when appending to their main event
+ log; child muxes share forwarded event objects and must not
+ mutate their envelopes.
+
+ Raises:
+ RuntimeError: If any transformer requires an async run but
+ the mux is in sync mode.
+ TypeError: If a transformer's `init()` doesn't return a dict.
+ ValueError: If transformers' projection keys collide.
+ """
+ self.is_async = is_async
+ self.scope: tuple[str, ...] = scope
+ self._assign_seq = _assign_seq
+ self._events: StreamChannel[ProtocolEvent] = StreamChannel()
+ self._events._bind(is_async=is_async)
+ self._events._bind_mux(self)
+ self._transformers: list[StreamTransformer] = []
+ self._channels: list[StreamChannel[Any]] = []
+ self._seq = 0
+ self._push_seq = 0
+
+ self.extensions: dict[str, Any] = {}
+ self.native_keys: set[str] = set()
+ self._projection_owners: dict[str, str] = {}
+ self._transformer_by_key: dict[str, StreamTransformer] = {}
+
+ # Stored only when constructed from factories — used by
+ # `_make_child` to clone the transformer pipeline at a deeper
+ # scope. Pre-built transformers can't be cloned, so a mux
+ # built with `transformers=` rejects child construction.
+ self._factories: list[TransformerFactory] | None = (
+ list(factories) if factories is not None else None
+ )
+ self._pump_fn: Callable[[], bool] | None = None
+ self._apump_fn: Callable[[], Awaitable[bool]] | None = None
+
+ # Factories run first (they propagate to child mini-muxes
+ # via `_make_child`), then any pre-built `transformers=`
+ # instances are registered as root-only — they aren't cloned
+ # for child scopes.
+ if factories is not None:
+ for factory in factories:
+ self._register(factory(scope))
+ for transformer in transformers or ():
+ self._register(transformer)
+
+ def transformer_by_key(self, key: str) -> StreamTransformer | None:
+ """Return the transformer that contributed `key` to the projection."""
+ return self._transformer_by_key.get(key)
+
+ def _next_push_seq(self) -> int:
+ self._push_seq += 1
+ return self._push_seq
+
+ # ------------------------------------------------------------------
+ # Pump wiring + mini-mux nesting
+ # ------------------------------------------------------------------
+
+ def bind_pump(self, fn: Callable[[], bool]) -> None:
+ """Wire the sync pull callback onto every projection in this mux.
+
+ Records the pump on the mux so child mini-muxes built by
+ `_make_child` can inherit it. Propagates to:
+ - the main event log (`self._events`)
+ - every projection StreamChannel in `extensions`
+ - any registered transformer that exposes `_bind_pump` (e.g.
+ `MessagesTransformer` so `ChatModelStream` instances drive the
+ shared pump from their cursors)
+ """
+ self._pump_fn = fn
+ self._events._request_more = fn
+ for ch in self._channels:
+ ch._request_more = fn
+ for transformer in self._transformers:
+ bind = getattr(transformer, "_bind_pump", None)
+ if bind is not None:
+ bind(fn)
+
+ def bind_apump(self, fn: Callable[[], Awaitable[bool]]) -> None:
+ """Async counterpart to `bind_pump`."""
+ self._apump_fn = fn
+ self._events._arequest_more = fn
+ for ch in self._channels:
+ ch._arequest_more = fn
+ for transformer in self._transformers:
+ abind = getattr(transformer, "_bind_apump", None)
+ if abind is not None:
+ abind(fn)
+
+ def _make_child(self, scope: tuple[str, ...]) -> StreamMux:
+ """Build a mini-mux with the same factories scoped to `scope`.
+
+ Used by `SubgraphTransformer` to attach a fresh transformer
+ pipeline to each discovered subgraph handle. The child mux
+ inherits the current pump bindings (so cursors on its
+ projection logs drive the root pump), carries the same factory
+ list forward to any grandchild subgraphs, and does not assign
+ `seq` numbers so forwarded events can be shared without
+ mutating their envelope.
+
+ Raises:
+ RuntimeError: If the mux was not constructed with
+ `factories=`. Mini-muxes require factories so each scope
+ gets its own fresh transformer instances.
+ """
+ if self._factories is None:
+ raise RuntimeError(
+ "StreamMux._make_child requires the mux to be constructed "
+ "with `factories=`; pre-built transformers can't be "
+ "cloned to a new scope."
+ )
+ child = StreamMux(
+ factories=self._factories,
+ is_async=self.is_async,
+ scope=scope,
+ _assign_seq=False,
+ )
+ if self._pump_fn is not None:
+ child.bind_pump(self._pump_fn)
+ if self._apump_fn is not None:
+ child.bind_apump(self._apump_fn)
+ return child
+
+ def _register(self, transformer: StreamTransformer) -> None:
+ """Register a single transformer.
+
+ Calls `transformer.init()`, stores the transformer for event
+ processing, binds any StreamChannel instances in the projection,
+ and merges the projection into `extensions`.
+ """
+ if transformer_requires_async(transformer) and not self.is_async:
+ raise RuntimeError(
+ f"{type(transformer).__name__} requires an async run — "
+ "it overrides aprocess/afinalize/afail or sets "
+ "requires_async=True. Use astream(), not stream()."
+ )
+ projection = transformer.init()
+ if not isinstance(projection, dict):
+ raise TypeError(
+ f"StreamTransformer.init() must return a dict, "
+ f"got {type(projection).__name__}"
+ )
+ conflicts = set(projection) & set(self.extensions)
+ if conflicts:
+ attributions = ", ".join(
+ f"{key!r} (owned by {self._projection_owners[key]})"
+ for key in sorted(conflicts)
+ )
+ raise ValueError(
+ f"Transformer {type(transformer).__name__} returned "
+ f"projection keys that conflict with already-registered "
+ f"keys: {attributions}"
+ )
+ is_native = bool(getattr(transformer, "_native", False))
+ self._transformers.append(transformer)
+ self._bind_and_wire(projection, native=is_native)
+ self.extensions.update(projection)
+ owner_name = type(transformer).__name__
+ for key in projection:
+ self._projection_owners[key] = owner_name
+ self._transformer_by_key[key] = transformer
+ if is_native:
+ self.native_keys.update(projection.keys())
+ transformer._on_register(self)
+
+ def push(self, event: ProtocolEvent) -> None:
+ """Route an event through all transformers, then append to the main log.
+
+ Each transformer's `process()` is called in registration order.
+ If any transformer returns False, the event is suppressed from
+ the main log, but transformers that already saw it keep their
+ side effects.
+
+ On the root mux, `seq` is assigned right before an event enters
+ the main log, not before the transformer pipeline runs. This
+ ensures that events auto-forwarded from StreamChannels during
+ `process()` get earlier seq numbers than the original event,
+ preserving monotonic ordering in the root log. Child muxes do
+ not assign `seq`, so subgraph forwarding can share event objects
+ without mutating their envelopes.
+
+ Args:
+ event: The protocol event to dispatch.
+ """
+ keep = True
+ for transformer in self._transformers:
+ if not transformer.process(event):
+ keep = False
+ if keep:
+ if self._assign_seq:
+ self._seq += 1
+ event["seq"] = self._seq
+ self._events.push(event)
+
+ def close(self) -> None:
+ """Finalize all transformers, close all projections and the main log.
+
+ StreamChannels discovered in transformer projections are
+ auto-closed after `finalize()` runs — transformers don't need
+ to close them manually. If any transformer's `finalize()` raises,
+ the remaining transformers, projections, and the main log are
+ still closed; the first error is re-raised after cleanup
+ completes.
+
+ Raises:
+ BaseException: The first error raised by a transformer's
+ `finalize()`, re-raised after cleanup finishes.
+ """
+ first_error: BaseException | None = None
+ for transformer in self._transformers:
+ try:
+ transformer.finalize()
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ for ch in self._channels:
+ if not ch._closed:
+ ch.close()
+ self._events.close()
+ if first_error is not None:
+ raise first_error
+
+ def fail(self, err: BaseException) -> None:
+ """Fail all transformers, projections, and the main log.
+
+ StreamChannels discovered in transformer projections are
+ auto-failed — transformers don't need to fail them manually.
+ If any transformer's `fail()` raises, the remaining
+ transformers, projections, and the main log are still failed.
+
+ Args:
+ err: The exception that ended the run.
+ """
+ for transformer in self._transformers:
+ try:
+ transformer.fail(err)
+ except BaseException:
+ pass
+ for ch in self._channels:
+ if not ch._closed:
+ ch.fail(err)
+ self._events.fail(err)
+
+ # ------------------------------------------------------------------
+ # Async dispatch
+ # ------------------------------------------------------------------
+
+ async def apush(self, event: ProtocolEvent) -> None:
+ """Dispatch an event on the async lane.
+
+ Awaits each transformer's `aprocess` in registration order
+ before appending to the main log. A slow `aprocess` serializes
+ the pipeline by design — that's the guarantee that lets a later
+ transformer (or a synchronous consumer) see the result of the
+ async work. For decoupled work, use `schedule()` from inside
+ `process` / `aprocess` instead.
+
+ The main log append is a non-blocking `push` — matching v1's
+ `put_nowait` shape. The root mux assigns `seq`; child muxes do
+ not, so forwarded subgraph events can be shared without copying.
+ Memory is bounded by caller pace via the caller-driven pump; see
+ `StreamChannel` for the full tradeoff story.
+
+ Args:
+ event: The protocol event to dispatch.
+ """
+ keep = True
+ for transformer in self._transformers:
+ if not await transformer.aprocess(event):
+ keep = False
+ if keep:
+ if self._assign_seq:
+ self._seq += 1
+ event["seq"] = self._seq
+ self._events.push(event)
+
+ async def aclose(self) -> None:
+ """Finalize on the async lane.
+
+ Awaits every task started via `StreamTransformer.schedule()`
+ across all transformers, then calls `afinalize()` on each,
+ then auto-closes channels and the main event log.
+
+ If any scheduled task raised under `on_error="raise"`, or any
+ transformer's `afinalize` raises, the exception propagates.
+ The caller (the pump) handles it by routing into `afail`.
+
+ Raises:
+ BaseException: The first scheduled-task or `afinalize`
+ error, re-raised after cleanup.
+ """
+ pending = self._collect_scheduled_tasks()
+ if pending:
+ results = await asyncio.gather(*pending, return_exceptions=True)
+ first_err = next(
+ (
+ r
+ for r in results
+ if isinstance(r, BaseException)
+ and not isinstance(r, asyncio.CancelledError)
+ ),
+ None,
+ )
+ if first_err is not None:
+ raise first_err
+
+ first_error: BaseException | None = None
+ for transformer in self._transformers:
+ try:
+ await transformer.afinalize()
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ for ch in self._channels:
+ if not ch._closed:
+ ch.close()
+ self._events.close()
+ if first_error is not None:
+ raise first_error
+
+ async def afail(self, err: BaseException) -> None:
+ """Fail on the async lane.
+
+ Cancels every scheduled task across all transformers, awaits
+ them to completion, then runs each transformer's `afail` hook
+ and auto-fails channels and the main event log.
+
+ Args:
+ err: The exception that ended the run.
+ """
+ pending = self._collect_scheduled_tasks()
+ for task in pending:
+ task.cancel()
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
+
+ for transformer in self._transformers:
+ try:
+ await transformer.afail(err)
+ except BaseException:
+ pass
+ for ch in self._channels:
+ if not ch._closed:
+ ch.fail(err)
+ if not self._events._closed:
+ self._events.fail(err)
+
+ def _collect_scheduled_tasks(self) -> list[asyncio.Task[Any]]:
+ """Return a snapshot of in-flight tasks scheduled via transformers."""
+ return [
+ task
+ for transformer in self._transformers
+ for task in getattr(transformer, "_stream_scheduled_tasks", ())
+ if not task.done()
+ ]
+
+ # ------------------------------------------------------------------
+ # Binding and StreamChannel auto-wiring
+ # ------------------------------------------------------------------
+
+ def _bind_and_wire(
+ self, projection: dict[str, Any], *, native: bool = False
+ ) -> None:
+ """Bind and optionally wire StreamChannel instances in a projection.
+
+ All StreamChannels are bound and tracked. Channels with a name
+ are additionally wired for protocol auto-forwarding.
+
+ Args:
+ projection: The projection dict returned by a transformer's
+ `init()`.
+ native: True when the owning transformer is `_native`.
+ Named channels owned by a native transformer use the
+ channel name directly as the protocol method;
+ user-defined channels are prefixed with `custom:`.
+ """
+ for value in projection.values():
+ if isinstance(value, StreamChannel):
+ value._bind(is_async=self.is_async)
+ value._bind_mux(self)
+ self._channels.append(value)
+ if value.name is not None:
+ method = value.name if native else f"custom:{value.name}"
+
+ def _make_forward(method_name: str) -> Callable[[Any], None]:
+ def _forward(item: Any) -> None:
+ self._forward(method_name, item)
+
+ return _forward
+
+ value._wire(_make_forward(method))
+
+ def _forward(self, method: str, item: Any) -> None:
+ """Inject a ProtocolEvent for a StreamChannel push.
+
+ Forwarded events bypass the transformer pipeline to avoid
+ infinite recursion (a transformer that pushes to a channel
+ during `process()` would re-trigger itself). These events are
+ visible in this mux's main event log but are not passed through
+ transformers' `process()` methods. Only the root mux assigns
+ `seq` to forwarded channel events.
+
+ Args:
+ method: The full protocol method (already with or without
+ the `custom:` prefix; resolved by `_bind_and_wire`).
+ item: The payload pushed onto the channel.
+ """
+ event: ProtocolEvent = {
+ "type": "event",
+ "method": method,
+ "params": {
+ "namespace": [],
+ "timestamp": int(time.time() * 1000),
+ "data": item,
+ },
+ }
+ if self._assign_seq:
+ self._seq += 1
+ event["seq"] = self._seq
+ self._events.push(event)
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/_types.py b/python/user_packages/Python313/site-packages/langgraph/stream/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..38a4e78adc0b2c2ec55b6a74adce65f513940691
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/_types.py
@@ -0,0 +1,313 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+from abc import ABC, abstractmethod
+from collections.abc import Coroutine
+from typing import Any, ClassVar, Literal
+
+from typing_extensions import NotRequired, TypedDict
+
+_logger = logging.getLogger(__name__)
+
+
+class _ProtocolEventParams(TypedDict):
+ """Parameters for a protocol event.
+
+ `timestamp` is wall-clock milliseconds since the epoch and can go
+ backwards across NTP adjustments — use `ProtocolEvent.seq` for
+ ordering.
+ """
+
+ namespace: list[str]
+ timestamp: int
+ data: Any
+ interrupts: NotRequired[tuple[Any, ...]]
+
+
+class ProtocolEvent(TypedDict):
+ """A protocol event emitted by the streaming infrastructure.
+
+ Wraps a raw stream part (values, messages, custom, etc.) in a uniform
+ envelope with a monotonic sequence number assigned by the root StreamMux.
+ Consumers that need a total order across root events should use `seq`, not
+ `params.timestamp` (which is wall-clock and not monotonic).
+ """
+
+ type: Literal["event"]
+ eventId: NotRequired[str]
+ seq: NotRequired[int]
+ method: str # StreamMode value: "values", "messages", "custom", etc.
+ params: _ProtocolEventParams
+
+
+class StreamTransformer(ABC):
+ """Extension point for custom stream projections.
+
+ Transformers observe protocol events flowing through the StreamMux and
+ build typed derived projections (StreamChannels, promises, etc.).
+
+ Set `_native = True` on a transformer to have its projection keys
+ exposed as direct attributes on the run stream (in addition to
+ appearing in `run.extensions`).
+
+ Subclasses must implement `init` and override at least one of
+ `process` / `aprocess`. The `finalize` / `afinalize` and `fail` /
+ `afail` hooks are optional — the default implementations are no-ops.
+ StreamChannel instances in the projection dict are auto-closed /
+ auto-failed by the mux, so most transformers don't need `finalize`
+ or `fail` at all.
+
+ Transformers that need async work pick the async lane by:
+
+ 1. Overriding `aprocess` (and optionally `afinalize` / `afail`), or
+ 2. Calling `self.schedule(coro)` from inside a sync `process`, or
+ 3. Setting `requires_async = True` explicitly.
+
+ The mux detects these cases at registration and raises if they're
+ used under sync `stream()` — they only work under `astream()`.
+
+ Use `aprocess` when the pump must wait for async work before the
+ next transformer sees the event (e.g. PII redaction that mutates
+ `event` in place). Use `schedule()` for decoupled async work whose
+ result lands on an independent projection (e.g. async moderation
+ scoring, cost lookup, external tracing).
+
+ Attributes:
+ scope: Namespace the transformer operates within — `()` for the
+ root mux. Set at construction from the mux's scope (each
+ factory is called as `factory(scope)`).
+ requires_async: Explicit opt-in for transformers that need a
+ running event loop but don't override any async method (for
+ example, transformers that call `schedule()` from a sync
+ `process`). The mux also auto-detects the async lane when
+ `aprocess`, `afinalize`, or `afail` is overridden.
+ supports_sync: Set True only for transformers that override
+ async-lane hooks while still fully supporting the sync lane.
+ Such transformers may be registered under `stream()`.
+ required_stream_modes: Stream modes the graph must emit for
+ this transformer to have anything to process. Computed as
+ the union across all registered transformers to determine
+ which modes a `stream_events(version="v3")` run requests from the graph.
+ Empty tuple means the transformer consumes only synthetic
+ events (or is purely passive).
+ """
+
+ requires_async: ClassVar[bool] = False
+ supports_sync: ClassVar[bool] = False
+ required_stream_modes: ClassVar[tuple[str, ...]] = ()
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ """Initialize the transformer with its mux's scope.
+
+ Args:
+ scope: The namespace tuple the owning mux is scoped to.
+ `()` for the root. Factories receive this at
+ construction time (`factory(scope)` in `StreamMux`).
+ """
+ self.scope: tuple[str, ...] = scope
+
+ @abstractmethod
+ def init(self) -> dict[str, Any]:
+ """Return the projection dict.
+
+ Keys become entries in `run.extensions`. If the transformer has
+ `_native = True`, keys are also set as direct attributes on the
+ run stream.
+
+ StreamChannel instances in the return value are automatically
+ wired by the StreamMux for protocol event auto-forwarding.
+ """
+ ...
+
+ def _on_register(self, mux: Any) -> None:
+ """Called by `StreamMux._register` after this transformer is wired in.
+
+ Default is a no-op. Override to capture a reference to the
+ owning mux — needed for transformers that build mini-muxes
+ via `mux._make_child(...)` (e.g. `SubgraphTransformer`).
+ """
+
+ def process(self, event: ProtocolEvent) -> bool:
+ """Handle an event on the sync lane.
+
+ Called for every event before it is appended to the main event
+ log. Subclasses must override either `process` or `aprocess`.
+ The default raises so a missing override fails loudly rather
+ than silently passing every event through.
+
+ Args:
+ event: The protocol event to observe.
+
+ Returns:
+ True to keep the event in the main log, False to suppress it.
+ """
+ raise NotImplementedError(
+ f"{type(self).__name__} must override process() or aprocess()"
+ )
+
+ async def aprocess(self, event: ProtocolEvent) -> bool:
+ """Handle an event on the async lane.
+
+ The mux awaits this before dispatching to the next transformer,
+ so a slow `aprocess` serializes the pipeline. Use it only when
+ a later transformer — or a consumer reading the event
+ synchronously — must see the result of the async work (e.g.
+ PII redaction that mutates `event` in place).
+
+ The default delegates to `process`, so purely-sync transformers
+ run unchanged under `astream()`.
+
+ Args:
+ event: The protocol event to observe.
+
+ Returns:
+ True to keep the event in the main log, False to suppress it.
+ """
+ return self.process(event)
+
+ def finalize(self) -> None:
+ """Called when the run ends normally (sync lane).
+
+ Override to close StreamChannels, resolve promises, or perform
+ other teardown. StreamChannel instances in the projection dict
+ are auto-closed by the mux.
+ """
+
+ async def afinalize(self) -> None:
+ """Called when the run ends normally (async lane).
+
+ By the time this runs, the mux has already awaited every task
+ started via `schedule()`, so StreamChannels can be closed here
+ without a last-task-wins race.
+
+ The default delegates to `finalize`.
+ """
+ self.finalize()
+
+ def fail(self, err: BaseException) -> None:
+ """Called when the run ends with an error (sync lane).
+
+ Override to fail StreamChannels, reject promises, or perform
+ other teardown. StreamChannel instances in the projection dict
+ are auto-failed by the mux.
+
+ Args:
+ err: The exception that ended the run.
+ """
+
+ async def afail(self, err: BaseException) -> None:
+ """Called when the run ends with an error (async lane).
+
+ The mux cancels and awaits every task started via `schedule()`
+ before calling this, so cleanup doesn't race with in-flight work.
+
+ The default delegates to `fail`.
+
+ Args:
+ err: The exception that ended the run.
+ """
+ self.fail(err)
+
+ # ------------------------------------------------------------------
+ # Scheduled async work
+ # ------------------------------------------------------------------
+
+ def schedule(
+ self,
+ coro: Coroutine[Any, Any, Any],
+ *,
+ on_error: Literal["log", "raise"] = "log",
+ ) -> asyncio.Task[Any]:
+ """Schedule a coroutine tied to this transformer's lifecycle.
+
+ The mux holds the task reference, awaits all scheduled tasks
+ during `aclose()` before calling `afinalize()`, and cancels
+ them on `afail()`. Authors don't need to track tasks or
+ implement the last-task-closes-the-log dance.
+
+ Requires a running event loop — call only under `astream()`.
+ Set `requires_async = True` on the class so registration under
+ sync `stream()` fails fast with a clear message.
+
+ Args:
+ coro: The coroutine to run. Its lifecycle is owned by the
+ mux from this point on.
+ on_error: `"log"` (default) catches and logs any exception
+ the coroutine raises, so a single failure doesn't tear
+ down the run. `"raise"` lets the exception propagate
+ when the mux joins pendings, converting the close path
+ into the fail path.
+
+ Returns:
+ The asyncio Task. Authors rarely need to await it directly
+ — consumers read results from whatever projection the
+ coroutine pushes into.
+
+ Raises:
+ RuntimeError: If called without a running event loop (i.e.
+ under sync `stream()` rather than `astream()`).
+ """
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ raise RuntimeError(
+ f"{type(self).__name__}.schedule() requires a running "
+ "event loop; this transformer must run under astream(), "
+ "not stream(). Set requires_async=True on the class so "
+ "this fails at registration rather than at first event."
+ ) from None
+
+ wrapped = self._wrap_scheduled(coro) if on_error == "log" else coro
+ task = asyncio.create_task(wrapped)
+ tasks = self._scheduled_task_set()
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+ return task
+
+ @staticmethod
+ async def _wrap_scheduled(coro: Coroutine[Any, Any, Any]) -> Any:
+ try:
+ return await coro
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
+ _logger.exception("Scheduled StreamTransformer task failed")
+
+ def _scheduled_task_set(self) -> set[asyncio.Task[Any]]:
+ """Return the lazily-allocated task set.
+
+ Avoids requiring subclasses to call `super().__init__()`.
+ """
+ tasks: set[asyncio.Task[Any]] | None = getattr(
+ self, "_stream_scheduled_tasks", None
+ )
+ if tasks is None:
+ tasks = set()
+ self._stream_scheduled_tasks = tasks
+ return tasks
+
+
+def transformer_requires_async(transformer: StreamTransformer) -> bool:
+ """Return True if the transformer needs a running event loop.
+
+ A transformer requires async if it explicitly opts in
+ (`requires_async = True`) or overrides any of the async-lane methods
+ (`aprocess`, `afinalize`, `afail`) without also declaring that it
+ supports the sync lane.
+
+ Args:
+ transformer: The transformer to inspect.
+
+ Returns:
+ True if the transformer cannot run under sync `stream()`.
+ """
+ if transformer.requires_async:
+ return True
+ if transformer.supports_sync:
+ return False
+ cls = type(transformer)
+ for name in ("aprocess", "afinalize", "afail"):
+ if getattr(cls, name) is not getattr(StreamTransformer, name):
+ return True
+ return False
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/run_stream.py b/python/user_packages/Python313/site-packages/langgraph/stream/run_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..2072125d1af00aeb0a3cca26763c49e855c40dcb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/run_stream.py
@@ -0,0 +1,608 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
+from types import MappingProxyType, TracebackType
+from typing import TYPE_CHECKING, Any
+
+from langchain_core._api import beta
+
+from langgraph.stream._convert import convert_to_protocol_event
+from langgraph.stream._mux import StreamMux
+from langgraph.stream._types import ProtocolEvent
+
+if TYPE_CHECKING:
+ from langgraph.stream.transformers import SubgraphStatus
+
+
+def _drive_until_done(pump: Callable[[], bool]) -> None:
+ """Call the sync pump until it returns False."""
+ while pump():
+ pass
+
+
+async def _adrive_until_done(pump: Callable[[], Awaitable[bool]]) -> None:
+ """Call the async pump until it returns False."""
+ while await pump():
+ pass
+
+
+@beta(message="The v3 streaming protocol on Pregel is experimental.")
+class GraphRunStream:
+ """Sync run stream with caller-driven pumping.
+
+ The caller's iteration on any projection (`values`, `messages`,
+ raw events, or `output`) drives the graph forward. No background
+ thread is used — the caller's `for` loop is the pump.
+
+ Projections are single-consumer — iterating `run.values` twice
+ raises. Use `projection.tee(n)` if you genuinely need fan-out.
+
+ All transformer projections live in `extensions`. Native transformer
+ projections (those with `_native = True`) are also set as direct
+ attributes on this instance (e.g. `run.values`, `run.messages`).
+
+ !!! warning
+
+ Returned by `Pregel.stream_events(version="v3")`, which is
+ experimental and may change.
+ """
+
+ def __init__(
+ self,
+ graph_iter: Iterator[Any] | None,
+ mux: StreamMux,
+ *,
+ wire_pump: bool = True,
+ ) -> None:
+ """Initialize the run stream.
+
+ Args:
+ graph_iter: Pull-based iterator over the graph's stream,
+ or `None` for nested run streams whose pump is driven
+ by an outer run (e.g. `SubgraphRunStream`).
+ mux: The StreamMux owning projections and the main log.
+ wire_pump: When True (default), bind `_pump_next` as the
+ mux's pump callable. Subclasses that inherit a parent
+ pump via `StreamMux._make_child` should pass False to
+ preserve the parent binding.
+ """
+ self._graph_iter = graph_iter
+ self._mux = mux
+ self.extensions: Mapping[str, Any] = MappingProxyType(mux.extensions)
+ self._exhausted = False
+ self._latest: dict[str, Any] | None = None
+ self._interrupted = False
+ self._interrupts: list[Any] = []
+ self._scope_list: list[str] = list(mux.scope)
+ for key in mux.native_keys:
+ setattr(self, key, mux.extensions[key])
+ if wire_pump:
+ self._wire_request_more(mux)
+
+ def _wire_request_more(self, mux: StreamMux) -> None:
+ """Wire the sync pull callback through the mux.
+
+ Routing through `mux.bind_pump` (rather than walking
+ projections directly here) lets child mini-muxes built by
+ `mux._make_child(...)` inherit the same pump callable, so
+ cursors on a subgraph handle's projections drive the root
+ pump just like cursors on `run.values` do.
+ """
+ mux.bind_pump(self._pump_next)
+
+ def _observe_event(self, event: ProtocolEvent) -> None:
+ """Track values-event state for output/interrupted/interrupts."""
+ if event["method"] != "values":
+ return
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return
+ self._latest = params["data"]
+ interrupts = params.get("interrupts", ())
+ if interrupts:
+ self._interrupted = True
+ self._interrupts.extend(interrupts)
+
+ def _pump_next(self) -> bool:
+ """Pull one event from the graph and push it through the mux.
+
+ Returns:
+ True if an event was pulled, False if the graph is exhausted
+ or has raised. Always False when constructed with
+ `graph_iter=None` (the run is driven by an outer pump).
+ """
+ if self._exhausted or self._graph_iter is None:
+ return False
+ try:
+ part = next(self._graph_iter)
+ event = convert_to_protocol_event(part)
+ self._observe_event(event)
+ self._mux.push(event)
+ return True
+ except StopIteration:
+ self._mux.close()
+ self._exhausted = True
+ return False
+ except Exception as e:
+ self._mux.fail(e)
+ self._exhausted = True
+ return False
+
+ def abort(self) -> None:
+ """Stop the run early.
+
+ Closes the mux and marks the stream exhausted. The graph
+ iterator is dropped; any in-flight nodes see the closure on
+ their next yield point. Idempotent.
+ """
+ if self._exhausted:
+ return
+ self._exhausted = True
+ try:
+ self._mux.close()
+ except Exception:
+ pass
+
+ def __enter__(self) -> GraphRunStream:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.abort()
+
+ @property
+ def output(self) -> dict[str, Any] | None:
+ """Drive the run to completion and return the final state."""
+ _drive_until_done(self._pump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._latest
+
+ @property
+ def interrupted(self) -> bool:
+ """Drive the run to completion, then return whether it was
+ interrupted.
+
+ Raises:
+ BaseException: If the run ended with an error.
+ """
+ _drive_until_done(self._pump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._interrupted
+
+ @property
+ def interrupts(self) -> list[Any]:
+ """Drive the run to completion, then return interrupt payloads.
+
+ Raises:
+ BaseException: If the run ended with an error.
+ """
+ _drive_until_done(self._pump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._interrupts
+
+ def __iter__(self) -> Iterator[ProtocolEvent]:
+ """Subscribe to the main event log and iterate protocol events."""
+ return iter(self._mux._events)
+
+ def interleave(self, *names: str) -> Iterator[tuple[str, Any]]:
+ """Iterate multiple projections in arrival order, yielding ``(name, item)``.
+
+ Items are ordered by a monotonic push stamp assigned when each
+ transformer pushes into its `StreamChannel`. This gives strict
+ arrival ordering across projections, unlike round-robin.
+
+ Args:
+ *names: Projection keys to interleave. Must match keys in
+ ``extensions``.
+
+ Yields:
+ ``(name, item)`` tuples in arrival order across the named
+ projections.
+
+ Each named channel is locked for the duration of iteration and
+ released when the generator completes, is closed, or raises.
+ Channels cannot be subscribed concurrently — use `.tee(n)` if
+ you need fan-out.
+
+ Raises:
+ KeyError: If a name doesn't match a registered projection.
+
+ Example:
+ ```python
+ for name, item in run.interleave("messages", "values"):
+ if name == "messages":
+ print("msg:", item)
+ else:
+ print("val:", item)
+ ```
+ """
+ from langgraph.stream.stream_channel import StreamChannel
+
+ channels: dict[str, StreamChannel[Any]] = {}
+ try:
+ for name in names:
+ ch = self.extensions[name]
+ if not isinstance(ch, StreamChannel):
+ raise TypeError(
+ f"interleave() requires StreamChannel projections, "
+ f"got {type(ch).__name__} for {name!r}"
+ )
+ if ch._is_async is None:
+ raise TypeError(
+ f"StreamChannel {name!r} has not been bound yet. "
+ "Register the transformer with a StreamMux first."
+ )
+ if ch._is_async:
+ raise TypeError(
+ f"StreamChannel {name!r} is bound to async mode — "
+ "sync interleave() cannot consume async channels."
+ )
+ if ch._subscribed:
+ raise RuntimeError(
+ f"StreamChannel {name!r} already has a subscriber; "
+ "use .tee(n) for fan-out."
+ )
+ ch._subscribed = True
+ channels[name] = ch
+
+ done: set[str] = set()
+
+ while len(done) < len(channels):
+ best: tuple[int, str] | None = None
+ for name, ch in channels.items():
+ if name in done:
+ continue
+ if ch._closed and not ch._items:
+ if ch._error is not None:
+ raise ch._error
+ done.add(name)
+ continue
+ if ch._items:
+ stamp = ch._items[0][0]
+ if best is None or stamp < best[0]:
+ best = (stamp, name)
+
+ if best is not None:
+ _stamp, item = channels[best[1]]._items.popleft()
+ yield (best[1], item)
+ else:
+ pump = self._mux._pump_fn
+ if pump is None or not pump():
+ before = len(done)
+ for name, ch in channels.items():
+ if name not in done and not ch._items:
+ if ch._closed:
+ if ch._error is not None:
+ raise ch._error
+ done.add(name)
+ if len(done) == before:
+ break
+ finally:
+ for ch in channels.values():
+ ch._subscribed = False
+
+
+@beta(message="The v3 streaming protocol on Pregel is experimental.")
+class AsyncGraphRunStream:
+ """Async run stream with caller-driven pumping.
+
+ Async iteration on any projection drives the graph forward — there
+ is no background task. Concurrent consumers share a single-flight
+ pump via an `asyncio.Lock`, so each awaiting cursor contributes one
+ event per acquisition. Backpressure comes from the logs: when a
+ subscribed log's buffer reaches `maxlen`, `apush` awaits the
+ subscriber to drain, which holds back the pump and paces the graph.
+
+ Projections are single-consumer — a second `aiter(run.values)`
+ raises. Use `projection.tee(n)` for fan-out.
+
+ Use as an async context manager to guarantee clean shutdown on
+ early exit:
+
+ ```python
+ async with await handler.astream(input) as run:
+ async for msg in run.messages:
+ ...
+ ```
+
+ !!! warning
+
+ Awaited from `Pregel.astream_events(version="v3")`, which is
+ experimental and may change.
+ """
+
+ def __init__(
+ self,
+ graph_aiter: AsyncIterator[Any] | None,
+ mux: StreamMux,
+ *,
+ wire_pump: bool = True,
+ ) -> None:
+ """Initialize the async run stream.
+
+ Args:
+ graph_aiter: Async iterator over the graph's stream, or
+ `None` for nested run streams whose pump is driven by
+ an outer run (e.g. `AsyncSubgraphRunStream`).
+ mux: The StreamMux owning projections and the main log.
+ wire_pump: When True (default), bind `_apump_next` as the
+ mux's async pump callable. Subclasses that inherit a
+ parent pump via `StreamMux._make_child` should pass
+ False to preserve the parent binding.
+ """
+ self._graph_aiter = graph_aiter
+ self._mux = mux
+ self.extensions: Mapping[str, Any] = MappingProxyType(mux.extensions)
+ self._exhausted = False
+ self._latest: dict[str, Any] | None = None
+ self._interrupted = False
+ self._interrupts: list[Any] = []
+ self._scope_list: list[str] = list(mux.scope)
+ self._pump_cond = asyncio.Condition()
+ self._pumping = False
+ for key in mux.native_keys:
+ setattr(self, key, mux.extensions[key])
+ if wire_pump:
+ self._wire_arequest_more(mux)
+
+ def _observe_event(self, event: ProtocolEvent) -> None:
+ """Track values-event state for output/interrupted/interrupts."""
+ if event["method"] != "values":
+ return
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return
+ self._latest = params["data"]
+ interrupts = params.get("interrupts", ())
+ if interrupts:
+ self._interrupted = True
+ self._interrupts.extend(interrupts)
+
+ def _wire_arequest_more(self, mux: StreamMux) -> None:
+ """Wire the async pull callback through the mux.
+
+ Mirrors `_wire_request_more`: routing through
+ `mux.bind_apump` lets child mini-muxes inherit the pump
+ callable so cursors on subgraph handles drive the root
+ pump.
+ """
+ mux.bind_apump(self._apump_next)
+
+ async def _apump_next(self) -> bool:
+ """Drive one pump step, or wait for the active pumper to drive one.
+
+ "Take-a-number" semantics: at most one task at a time calls
+ `graph_aiter.__anext__()` (asyncio iterators can't be advanced
+ concurrently). Other callers wait on a Condition that the
+ active pumper notifies after each step. This lets a "passive"
+ consumer — one whose projection's buffer is being filled by the
+ active pumper's push — wake up as soon as its data lands,
+ instead of queueing on the pump and only observing its data one
+ graph event late.
+
+ `except Exception` is intentional — `CancelledError` and other
+ `BaseException` subclasses propagate, matching asyncio's
+ cancellation contract.
+
+ Returns:
+ True if a pump step completed (by this task or another),
+ False if the graph is exhausted.
+ """
+ async with self._pump_cond:
+ if self._exhausted or self._graph_aiter is None:
+ return False
+ if self._pumping:
+ # Another task is pumping; wait for its progress signal.
+ await self._pump_cond.wait()
+ return not self._exhausted
+ self._pumping = True
+
+ try:
+ try:
+ part = await self._graph_aiter.__anext__()
+ event = convert_to_protocol_event(part)
+ self._observe_event(event)
+ await self._mux.apush(event)
+ return True
+ except StopAsyncIteration:
+ self._exhausted = True
+ await self._mux.aclose()
+ return False
+ except Exception as e:
+ self._exhausted = True
+ await self._mux.afail(e)
+ return False
+ finally:
+ async with self._pump_cond:
+ self._pumping = False
+ self._pump_cond.notify_all()
+
+ async def abort(self) -> None:
+ """Stop the run early.
+
+ Marks the stream exhausted, wakes any pump-waiters, and closes
+ the mux. Any `apush` blocked on backpressure wakes and returns
+ without appending. Idempotent.
+ """
+ async with self._pump_cond:
+ if self._exhausted:
+ return
+ self._exhausted = True
+ self._pump_cond.notify_all()
+ try:
+ await self._mux.aclose()
+ except Exception:
+ pass
+
+ async def __aenter__(self) -> AsyncGraphRunStream:
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ await self.abort()
+
+ async def output(self) -> dict[str, Any] | None:
+ """Drive the run to completion and return the final state.
+
+ Methods (not properties) on the async lane so `run.output`
+ without `await` raises at type-check time instead of silently
+ yielding a coroutine object.
+
+ Example:
+ ```python
+ output = await run.output()
+ ```
+
+ Raises:
+ BaseException: If the run ended with an error.
+ """
+ await _adrive_until_done(self._apump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._latest
+
+ async def interrupted(self) -> bool:
+ """Drive the run to completion and return whether it was
+ interrupted.
+
+ Raises:
+ BaseException: If the run ended with an error.
+ """
+ await _adrive_until_done(self._apump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._interrupted
+
+ async def interrupts(self) -> list[Any]:
+ """Drive the run to completion and return interrupt payloads.
+
+ Raises:
+ BaseException: If the run ended with an error.
+ """
+ await _adrive_until_done(self._apump_next)
+ if (err := self._mux._events._error) is not None:
+ raise err
+ return self._interrupts
+
+ def __aiter__(self) -> AsyncIterator[ProtocolEvent]:
+ """Subscribe to the main event log and iterate protocol events."""
+ return self._mux._events.__aiter__()
+
+
+class _SubgraphRunStreamMixin:
+ """Subgraph metadata + parent-pump delegation shared by both lanes.
+
+ Inherits from `GraphRunStream` (or `AsyncGraphRunStream`) with
+ `graph_iter=None` + `wire_pump=False` — the mini-mux is driven
+ by the parent's pump (inherited via `StreamMux._make_child`), and
+ the handle never pulls upstream itself. Pump-driving methods
+ delegate to the parent pump so `handle.output` and friends drive
+ the root run.
+
+ Subclasses set the parent pump function captured at construction
+ (`_parent_pump_fn` / `_parent_apump_fn`) and override
+ `_pump_next` / `_apump_next` to delegate to it.
+
+ Status is updated in place by `SubgraphTransformer`. Iterate
+ `run.subgraphs` to receive handles as subgraphs spawn, then
+ drill into projections inside the loop body **before** the next
+ pump cycle — same lazy-subscribe constraint as root projections.
+ """
+
+ path: tuple[str, ...]
+ graph_name: str | None
+ trigger_call_id: str | None
+ status: SubgraphStatus
+ error: str | None
+ _seen_terminal: bool
+
+
+class SubgraphRunStream(GraphRunStream, _SubgraphRunStreamMixin):
+ """Sync handle for a discovered subgraph (extends `GraphRunStream`)."""
+
+ def __init__(
+ self,
+ mux: StreamMux,
+ *,
+ path: tuple[str, ...],
+ graph_name: str | None = None,
+ trigger_call_id: str | None = None,
+ ) -> None:
+ # Capture the parent-inherited pump before super().__init__
+ # touches anything; we delegate to it from `_pump_next`.
+ self._parent_pump_fn: Callable[[], bool] | None = mux._pump_fn
+ super().__init__(
+ graph_iter=None,
+ mux=mux,
+ wire_pump=False,
+ )
+ self.path = path
+ self.graph_name = graph_name
+ self.trigger_call_id = trigger_call_id
+ self.status = "started"
+ self.error = None
+ self._seen_terminal = False
+
+ def _pump_next(self) -> bool:
+ """Delegate to the parent's pump.
+
+ Cursors on this handle's projections call here when their
+ buffers empty. Driving the parent fans events into our
+ mini-mux, transparently advancing the whole run.
+ """
+ if (
+ self._exhausted
+ or self._seen_terminal
+ or self._mux._events._closed
+ or self._parent_pump_fn is None
+ ):
+ return False
+ return self._parent_pump_fn()
+
+
+class AsyncSubgraphRunStream(AsyncGraphRunStream, _SubgraphRunStreamMixin):
+ """Async handle for a discovered subgraph (extends `AsyncGraphRunStream`)."""
+
+ def __init__(
+ self,
+ mux: StreamMux,
+ *,
+ path: tuple[str, ...],
+ graph_name: str | None = None,
+ trigger_call_id: str | None = None,
+ ) -> None:
+ self._parent_apump_fn: Callable[[], Awaitable[bool]] | None = mux._apump_fn
+ super().__init__(
+ graph_aiter=None,
+ mux=mux,
+ wire_pump=False,
+ )
+ self.path = path
+ self.graph_name = graph_name
+ self.trigger_call_id = trigger_call_id
+ self.status = "started"
+ self.error = None
+ self._seen_terminal = False
+
+ async def _apump_next(self) -> bool:
+ """Delegate to the parent's async pump."""
+ if (
+ self._exhausted
+ or self._seen_terminal
+ or self._mux._events._closed
+ or self._parent_apump_fn is None
+ ):
+ return False
+ return await self._parent_apump_fn()
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/stream_channel.py b/python/user_packages/Python313/site-packages/langgraph/stream/stream_channel.py
new file mode 100644
index 0000000000000000000000000000000000000000..9af48ee287d4a3edb83c1b051a0d18e082bf198e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/stream_channel.py
@@ -0,0 +1,341 @@
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
+from typing import TYPE_CHECKING, Generic, TypeVar
+
+if TYPE_CHECKING:
+ from langgraph.stream._mux import StreamMux
+
+T = TypeVar("T")
+
+
+class StreamChannel(Generic[T]):
+ """Single-consumer drainable queue for streaming events, with optional
+ protocol auto-forwarding.
+
+ When constructed with a `name`, the StreamMux auto-wires every
+ `push()` to also inject a `ProtocolEvent` into the main event stream
+ using the channel's name as the method. When constructed without a
+ name, the channel is local-only — items are only visible to
+ in-process consumers that iterate the channel directly.
+
+ Items are popped off the front as the consumer advances — there is
+ no retention beyond what's currently queued. A channel accepts
+ exactly one subscriber; a second `__iter__` / `__aiter__` call
+ raises. Use `tee(n)` / `atee(n)` for fan-out.
+
+ Starts unbound — neither `__iter__` nor `__aiter__` is available
+ until the StreamMux calls `_bind(is_async)`. After binding, only
+ the matching iteration protocol works; the other raises `TypeError`.
+
+ Pump wiring (set by the run stream, not by `_bind`):
+ - `_request_more`: sync pump callable, returns True if a new
+ event was produced.
+ - `_arequest_more`: async pump coroutine factory, same contract.
+
+ Memory is bounded by caller pace: both sync and async use caller-
+ driven pumps, so each cursor advance produces at most one event.
+
+ Lazy-subscribe: `push` appends to the local buffer only when a
+ subscriber has registered. Auto-forward via `_wire_fn` always fires
+ regardless of subscription state.
+
+ Lifecycle (`close` / `fail`) is managed by the mux — transformers
+ don't need to close their channels manually.
+ """
+
+ def __init__(self, name: str | None = None, *, maxlen: int | None = None) -> None:
+ """Initialize the channel.
+
+ Args:
+ name: Optional protocol channel name. When set, the
+ StreamMux wires every `push()` to also inject a
+ `ProtocolEvent` into the main event stream. Surfaced
+ on the wire as `custom:` for user-defined
+ transformers, or as `` for channels owned by a
+ native transformer (`_native = True`). When `None`,
+ the channel is local-only.
+ maxlen: Accepted for forward compatibility; currently
+ unused. The caller-driven pump bounds memory naturally
+ for single-consumer use.
+
+ Raises:
+ ValueError: If `maxlen` is not a positive integer or `None`.
+ """
+ if maxlen is not None and maxlen <= 0:
+ raise ValueError("StreamChannel maxlen must be a positive int or None")
+ self.name = name
+ self._items: deque[tuple[int, T]] = deque()
+ self._maxlen: int | None = maxlen
+ self._closed = False
+ self._error: BaseException | None = None
+
+ self._is_async: bool | None = None
+
+ self._subscribed = False
+
+ self._request_more: Callable[[], bool] | None = None
+ self._arequest_more: Callable[[], Awaitable[bool]] | None = None
+
+ self._wire_fn: Callable[[T], None] | None = None
+ self._mux: StreamMux | None = None
+
+ # ------------------------------------------------------------------
+ # Binding
+ # ------------------------------------------------------------------
+
+ def _bind_mux(self, mux: StreamMux) -> None:
+ self._mux = mux
+
+ def _bind(self, *, is_async: bool) -> None:
+ """Bind this channel to sync or async mode.
+
+ Called by the StreamMux after transformer registration. Must be
+ called exactly once before any iteration.
+
+ Args:
+ is_async: True to enable async iteration, False for sync.
+
+ Raises:
+ RuntimeError: If the channel has already been bound.
+ """
+ if self._is_async is not None:
+ raise RuntimeError("StreamChannel is already bound")
+ self._is_async = is_async
+
+ # ------------------------------------------------------------------
+ # Mux wiring (not called by transformers directly)
+ # ------------------------------------------------------------------
+
+ def _wire(self, fn: Callable[[T], None]) -> None:
+ """Install the auto-forward callback (called by StreamMux)."""
+ self._wire_fn = fn
+
+ # ------------------------------------------------------------------
+ # Producer API
+ # ------------------------------------------------------------------
+
+ def push(self, item: T) -> None:
+ """Append an item. Auto-forwards if wired.
+
+ The local buffer append is a no-op when no subscriber is
+ registered, but auto-forwarding always fires so wired events
+ reach the main event log regardless of subscription state.
+
+ Items are stored as `(stamp, item)` tuples where stamp is a
+ monotonic counter from the owning mux. Stamps are stripped by
+ the default cursors; raw stamped tuples are visible on `_items`.
+
+ Raises:
+ RuntimeError: If the channel is closed (and subscribed).
+ """
+ if self._subscribed:
+ if self._closed:
+ raise RuntimeError("Cannot push to a closed StreamChannel")
+ stamp = self._mux._next_push_seq() if self._mux is not None else 0
+ self._items.append((stamp, item))
+ if self._wire_fn is not None:
+ self._wire_fn(item)
+
+ def close(self) -> None:
+ """Mark the channel as complete."""
+ self._closed = True
+
+ def fail(self, err: BaseException) -> None:
+ """Mark the channel as errored.
+
+ Args:
+ err: The exception to surface to the subscriber.
+ """
+ self._error = err
+ self._closed = True
+
+ # ------------------------------------------------------------------
+ # Sync iteration (caller-driven pump)
+ # ------------------------------------------------------------------
+
+ def __iter__(self) -> Iterator[T]:
+ """Subscribe and return a sync cursor. Can be called only once.
+
+ Raises:
+ TypeError: If the channel is unbound or bound to async mode.
+ RuntimeError: If the channel already has a subscriber.
+ """
+ if self._is_async is None:
+ raise TypeError(
+ "StreamChannel has not been bound yet. "
+ "Register the transformer with a StreamMux first."
+ )
+ if self._is_async:
+ raise TypeError(
+ "This StreamChannel is bound to async mode — use 'async for' instead."
+ )
+ if self._subscribed:
+ raise RuntimeError(
+ "StreamChannel already has a subscriber; use .tee(n) for fan-out."
+ )
+ self._subscribed = True
+ return self._sync_cursor()
+
+ def _sync_cursor(self) -> Iterator[T]:
+ while True:
+ if self._items:
+ _stamp, item = self._items.popleft()
+ yield item
+ elif self._closed:
+ if self._error is not None:
+ raise self._error
+ return
+ elif self._request_more is not None:
+ if not self._request_more():
+ if not self._items and not self._closed:
+ return
+ else:
+ return
+
+ # ------------------------------------------------------------------
+ # Async iteration (caller-driven pump)
+ # ------------------------------------------------------------------
+
+ def __aiter__(self) -> AsyncIterator[T]:
+ """Subscribe and return an async cursor. Can be called only once.
+
+ Raises:
+ TypeError: If the channel is unbound or bound to sync mode.
+ RuntimeError: If the channel already has a subscriber.
+ """
+ if self._is_async is None:
+ raise TypeError(
+ "StreamChannel has not been bound yet. "
+ "Register the transformer with a StreamMux first."
+ )
+ if not self._is_async:
+ raise TypeError(
+ "This StreamChannel is bound to sync mode — use 'for' instead."
+ )
+ if self._subscribed:
+ raise RuntimeError(
+ "StreamChannel already has a subscriber; use .atee(n) for fan-out."
+ )
+ self._subscribed = True
+ return self._async_cursor()
+
+ async def _async_cursor(self) -> AsyncIterator[T]:
+ while True:
+ if self._items:
+ _stamp, item = self._items.popleft()
+ yield item
+ elif self._closed:
+ if self._error is not None:
+ raise self._error
+ return
+ elif self._arequest_more is not None:
+ if not await self._arequest_more():
+ if not self._items and not self._closed:
+ return
+ else:
+ return
+
+ # ------------------------------------------------------------------
+ # Fan-out via tee
+ # ------------------------------------------------------------------
+
+ def tee(self, n: int = 2) -> tuple[Iterator[T], ...]:
+ """Subscribe and return `n` independent sync iterators.
+
+ Each branch has its own buffer; items pulled from the
+ underlying cursor are copied into every branch. Branches are
+ naturally bounded by caller pace since the sync pump is
+ caller-driven.
+
+ Args:
+ n: Number of branches to create. Must be >= 1.
+
+ Returns:
+ A tuple of `n` iterators over the same underlying stream.
+
+ Raises:
+ TypeError: If the channel is unbound or bound to async mode.
+ RuntimeError: If the channel already has a subscriber.
+ ValueError: If `n` < 1.
+ """
+ if n < 1:
+ raise ValueError("tee() requires n >= 1")
+ source = self.__iter__()
+ buffers: list[deque[T]] = [deque() for _ in range(n)]
+ exhausted = [False]
+
+ def branch(i: int) -> Iterator[T]:
+ buf = buffers[i]
+ while True:
+ if buf:
+ yield buf.popleft()
+ elif exhausted[0]:
+ return
+ else:
+ try:
+ item = next(source)
+ except StopIteration:
+ exhausted[0] = True
+ return
+ for b in buffers:
+ b.append(item)
+
+ return tuple(branch(i) for i in range(n))
+
+ def atee(self, n: int = 2) -> tuple[AsyncIterator[T], ...]:
+ """Subscribe and return `n` independent async iterators.
+
+ Caller-driven fan-out: each branch's `__anext__` either pops
+ from its own buffer or, under a shared `asyncio.Lock`, pulls
+ one item from the underlying cursor and distributes it to
+ every branch's buffer.
+
+ Args:
+ n: Number of branches to create. Must be >= 1.
+
+ Returns:
+ A tuple of `n` async iterators over the same underlying
+ stream.
+
+ Raises:
+ TypeError: If the channel is unbound or bound to sync mode.
+ RuntimeError: If the channel already has a subscriber.
+ ValueError: If `n` < 1.
+ """
+ if n < 1:
+ raise ValueError("atee() requires n >= 1")
+ source = self.__aiter__()
+ buffers: list[deque[T]] = [deque() for _ in range(n)]
+ exhausted = [False]
+ error: list[BaseException | None] = [None]
+ lock = asyncio.Lock()
+
+ async def branch(i: int) -> AsyncIterator[T]:
+ buf = buffers[i]
+ while True:
+ if buf:
+ yield buf.popleft()
+ continue
+ if exhausted[0]:
+ if error[0] is not None:
+ raise error[0]
+ return
+ async with lock:
+ if buf or exhausted[0]:
+ continue
+ try:
+ item = await source.__anext__()
+ except StopAsyncIteration:
+ exhausted[0] = True
+ continue
+ except Exception as e:
+ error[0] = e
+ exhausted[0] = True
+ continue
+ for b in buffers:
+ b.append(item)
+
+ return tuple(branch(i) for i in range(n))
diff --git a/python/user_packages/Python313/site-packages/langgraph/stream/transformers.py b/python/user_packages/Python313/site-packages/langgraph/stream/transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ce420af7ba81c3abd0c690fe2f56616d2da8284
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/stream/transformers.py
@@ -0,0 +1,928 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from langchain_core.language_models._compat_bridge import message_to_events
+from langchain_core.language_models.chat_model_stream import (
+ AsyncChatModelStream,
+ ChatModelStream,
+)
+from langchain_core.messages import AIMessageChunk, BaseMessage
+from langchain_protocol.protocol import MessagesData
+from typing_extensions import NotRequired, TypedDict
+
+from langgraph.errors import GraphDrained, GraphInterrupt
+from langgraph.stream._types import ProtocolEvent, StreamTransformer
+from langgraph.stream.run_stream import AsyncSubgraphRunStream, SubgraphRunStream
+from langgraph.stream.stream_channel import StreamChannel
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+
+ from langgraph.stream._mux import StreamMux
+
+_logger = logging.getLogger(__name__)
+
+
+class ValuesTransformer(StreamTransformer):
+ """Capture values events as a drainable stream of state snapshots.
+
+ Provides the `run.values` projection. `run.output`,
+ `run.interrupted` and `run.interrupts` are tracked directly
+ by the run stream and do not depend on this transformer.
+
+ Native transformer — projection keys are exposed as direct
+ attributes on the run stream (e.g. `run.values`).
+
+ Only values events at the run's own level are captured; snapshots
+ from deeper subgraphs are left in the main event log but excluded
+ from the projection. "Own level" is defined by `scope`, which
+ `stream_events(version="v3")` / `astream_events(version="v3")` populate from the caller's
+ checkpoint namespace so that a nested `stream_events(version="v3")` call still
+ sees its own root snapshots.
+ """
+
+ _native = True
+ required_stream_modes = ("values",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[dict[str, Any]] = StreamChannel()
+ self._latest: dict[str, Any] | None = None
+ self._interrupted = False
+ self._interrupts: list[Any] = []
+ # Cached as a list once for cheap equality with the protocol
+ # event's `namespace` field, which is `list[str]`.
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"values": self._log}
+
+ @property
+ def error(self) -> BaseException | None:
+ """The error that ended the run, or `None` if it succeeded.
+
+ Set by the mux when it auto-fails the projection log.
+ """
+ return self._log._error
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "values":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._latest = params["data"]
+ interrupts = params.get("interrupts", ())
+ if interrupts:
+ self._interrupted = True
+ self._interrupts.extend(interrupts)
+ self._log.push(params["data"])
+ return True
+
+
+class CustomTransformer(StreamTransformer):
+ """Capture custom events as a drainable stream of arbitrary payloads.
+
+ Nodes emit custom data via `get_stream_writer()`. This transformer
+ surfaces those events on `run.custom` as a `StreamChannel[Any]`,
+ preserving payloads in arrival order.
+
+ Only events at the run's own scope are captured; custom data from
+ deeper subgraphs is available on the respective subgraph handle's
+ `.custom` projection.
+
+ Native transformer — `run.custom` is a direct attribute.
+ """
+
+ _native = True
+ required_stream_modes = ("custom",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[Any] = StreamChannel()
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"custom": self._log}
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "custom":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._log.push(params["data"])
+ return True
+
+
+class UpdatesTransformer(StreamTransformer):
+ """Capture updates events as a drainable stream of node outputs.
+
+ Surfaces `stream_mode="updates"` data on `run.updates` as a
+ `StreamChannel[dict[str, Any]]`. Each item is a dict mapping a node
+ (or task) name to the update it returned after a step.
+
+ Only events at the run's own scope are captured; updates from deeper
+ subgraphs are available on the respective subgraph handle's
+ `.updates` projection.
+
+ Native transformer — `run.updates` is a direct attribute.
+ """
+
+ _native = True
+ required_stream_modes = ("updates",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[dict[str, Any]] = StreamChannel()
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"updates": self._log}
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "updates":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._log.push(params["data"])
+ return True
+
+
+class MessagesTransformer(StreamTransformer):
+ """Capture messages events as ChatModelStream objects.
+
+ The messages projection yields one `ChatModelStream` (or
+ `AsyncChatModelStream`) per LLM call. Consumers iterate
+ `run.messages` to get stream handles, then use each handle's typed
+ projections (`.text`, `.reasoning`, `.tool_calls`, `.usage`,
+ `.output`) for per-message content.
+
+ Two input shapes are handled (via `params["data"] = (payload,
+ metadata)` from `StreamMessagesHandler`):
+
+ 1. Protocol event (dict with `"event"` key) — emitted by
+ `stream_events(version="v3")` / `astream_events(version="v3")` via the `on_stream_event`
+ callback. Routed to an existing `ChatModelStream` by
+ `metadata["run_id"]`. A `message-start` event creates a new
+ stream; `message-finish` closes it.
+ 2. Whole `AIMessage` — emitted from `on_chain_end` when a node
+ returns a finalized message. Replayed as a synthetic protocol
+ event lifecycle via `message_to_events`, then the
+ already-complete stream is pushed to the log.
+
+ V1 `AIMessageChunk` tuples (from `on_llm_new_token`) are not
+ streamed into this projection: chat models that want to populate
+ `run.messages` with content-block streaming must use
+ `stream_events(version="v3")` / `astream_events(version="v3")`. Models called via the legacy
+ `stream()` method still surface their final `AIMessage` via
+ `on_chain_end` when a node returns it as state.
+
+ Only events at the run's own level are projected; tokens from
+ deeper subgraphs are left in the main event log but excluded from
+ `.messages`. "Own level" is defined by `scope`, which
+ `stream_events(version="v3")` / `astream_events(version="v3")` populate from the caller's checkpoint
+ namespace so that a `stream_events(version="v3")` call inside a node still sees its
+ own root chat model streams on `.messages`. Consumers that need
+ subgraph tokens should iterate the raw event stream or register a
+ custom transformer.
+
+ Native transformer — the `messages` projection is exposed as a
+ direct attribute on the run stream.
+ """
+
+ _native = True
+ required_stream_modes = ("messages",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[ChatModelStream] = StreamChannel()
+ # Correlate protocol events back to a ChatModelStream by run_id
+ # (attached to the event's metadata by StreamMessagesHandler).
+ self._by_run: dict[str, ChatModelStream] = {}
+ self._pump_fn: Callable[[], bool] | None = None
+ self._apump_fn: Callable[[], Awaitable[bool]] | None = None
+ # Cached as a list once for cheap equality with the protocol
+ # event's `namespace` field, which is `list[str]`.
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"messages": self._log}
+
+ def _bind_pump(self, fn: Callable[[], bool]) -> None:
+ """Wire the sync pull callback. Called by GraphRunStream._wire_request_more."""
+ self._pump_fn = fn
+
+ def _bind_apump(self, fn: Callable[[], Awaitable[bool]]) -> None:
+ """Wire the async pull callback.
+
+ Called by `AsyncGraphRunStream._wire_arequest_more` so each
+ `AsyncChatModelStream` this transformer creates can drive the
+ shared graph pump from its projection cursors.
+ """
+ self._apump_fn = fn
+
+ def _make_stream(
+ self,
+ *,
+ namespace: list[str],
+ node: str | None,
+ message_id: str | None,
+ ) -> ChatModelStream:
+ """Create a ChatModelStream (sync) or AsyncChatModelStream (async).
+
+ Wires whichever pump is bound. Prefers the async pump so nested
+ iteration under `AsyncGraphRunStream` drives the graph forward
+ without a background task. The unwired fallback (no pump bound)
+ is used by unit tests that dispatch events manually.
+ """
+ if self._apump_fn is not None:
+ astream = AsyncChatModelStream(
+ namespace=namespace,
+ node=node,
+ message_id=message_id,
+ )
+ astream.set_arequest_more(self._apump_fn)
+ return astream
+ if self._pump_fn is not None:
+ stream: ChatModelStream = ChatModelStream(
+ namespace=namespace,
+ node=node,
+ message_id=message_id,
+ )
+ stream.set_request_more(self._pump_fn)
+ return stream
+ return AsyncChatModelStream(
+ namespace=namespace,
+ node=node,
+ message_id=message_id,
+ )
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "messages":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+
+ payload, metadata = params["data"]
+ node: str | None = metadata.get("langgraph_node")
+ run_id = str(metadata.get("run_id", "")) if metadata else ""
+
+ if isinstance(payload, dict) and "event" in payload:
+ self._route_protocol_event(
+ cast("MessagesData", payload), run_id=run_id, node=node
+ )
+ elif isinstance(payload, BaseMessage) and not isinstance(
+ payload, AIMessageChunk
+ ):
+ self._route_whole_message(payload, node=node)
+ # Legacy AIMessageChunk tuples (from on_llm_new_token) are ignored;
+ # v1 streaming callers must switch to stream_events(version="v3") to populate this
+ # projection.
+
+ return True
+
+ def _route_protocol_event(
+ self,
+ event: MessagesData,
+ *,
+ run_id: str,
+ node: str | None,
+ ) -> None:
+ event_type = event.get("event")
+ if event_type == "message-start":
+ message_id = event.get("message_id")
+ stream = self._make_stream(
+ namespace=[],
+ node=node,
+ message_id=str(message_id) if message_id is not None else None,
+ )
+ self._by_run[run_id] = stream
+ self._log.push(stream)
+ stream.dispatch(event)
+ elif run_id in self._by_run:
+ stream = self._by_run[run_id]
+ stream.dispatch(event)
+ if event_type == "message-finish":
+ del self._by_run[run_id]
+
+ def _route_whole_message(self, message: BaseMessage, *, node: str | None) -> None:
+ stream = self._make_stream(namespace=[], node=node, message_id=message.id)
+ for evt in message_to_events(message, message_id=message.id):
+ stream.dispatch(evt)
+ self._log.push(stream)
+
+ def finalize(self) -> None:
+ """Clear any routing state — streams close themselves via `message-finish`."""
+ self._by_run.clear()
+
+ def fail(self, err: BaseException) -> None:
+ """Propagate run error to any streams still open when the graph fails."""
+ for stream in list(self._by_run.values()):
+ stream.fail(err)
+ self._by_run.clear()
+
+
+SubgraphStatus = Literal["started", "completed", "failed", "interrupted", "drained"]
+
+
+def _parse_ns_segment(segment: str) -> tuple[str, str | None]:
+ """Split a namespace segment into `(graph_name, trigger_call_id)`.
+
+ Segments are formatted `node_name:task_id` by `prepare_next_tasks`.
+ Returns `(segment, None)` if no `:` is present.
+ """
+ name, sep, task_id = segment.partition(":")
+ return name, task_id if sep else None
+
+
+class LifecyclePayload(TypedDict, total=False):
+ """Payload of a lifecycle event surfaced on the `lifecycle` channel.
+
+ Auto-forwarded as `lifecycle` protocol events (no `custom:` prefix
+ because `LifecycleTransformer` is a native transformer) so remote
+ SDK clients receive the same data in-process consumers see via
+ `run.lifecycle`.
+ """
+
+ event: SubgraphStatus
+ namespace: list[str]
+ graph_name: NotRequired[str]
+ trigger_call_id: NotRequired[str]
+ error: NotRequired[str]
+
+
+class _TasksLifecycleBase(StreamTransformer):
+ """Shared bookkeeping for `tasks`-event-driven lifecycle inference.
+
+ Both `LifecycleTransformer` (wire-serializable channel) and
+ `SubgraphTransformer` (in-process navigation handles) discover
+ subgraphs by watching the same `tasks` stream — `started` on the
+ first event at a tracked namespace, terminal status when the
+ parent's `TaskResultPayload` arrives. Centralizing the dispatch
+ + open-set bookkeeping here keeps the inference rules from
+ drifting between the two surfaces.
+
+ Subclasses provide three template-method hooks:
+
+ - `_should_track(ns)` — scope filter (e.g. multi-depth vs
+ direct-children-only).
+ - `_on_started(ns, graph_name, trigger_call_id)` — first sighting
+ action (push payload / build handle / etc.). Called once per
+ discovered namespace.
+ - `_on_terminal(ns, status, error)` — terminal action (push
+ terminal payload / mark handle status). Called once per
+ tracked namespace at result time, or via `finalize` / `fail`
+ sweeps if no parent result arrived.
+
+ Tasks events are suppressed from the main event log (`process`
+ returns False) — they're folded into whichever projection the
+ subclass populates; consumers iterating the raw protocol stream
+ see the higher-level view.
+ """
+
+ required_stream_modes = ("tasks",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._seen: set[tuple[str, ...]] = set()
+ # Maps tracked namespace -> task_id of the parent task whose
+ # `TaskResultPayload` will close it.
+ self._open: dict[tuple[str, ...], str] = {}
+
+ # --- Template-method hooks (subclass overrides) ---
+
+ def _should_track(self, ns: tuple[str, ...]) -> bool:
+ """Scope filter — return True iff `ns` is in this transformer's region."""
+ raise NotImplementedError
+
+ def _on_started(
+ self,
+ ns: tuple[str, ...],
+ graph_name: str | None,
+ trigger_call_id: str | None,
+ ) -> None:
+ """Fired once per discovered namespace (first observed task event)."""
+ raise NotImplementedError
+
+ def _on_terminal(
+ self,
+ ns: tuple[str, ...],
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ """Fired once per tracked namespace when its parent's result arrives,
+ or via finalize/fail safety-net sweeps.
+ """
+ raise NotImplementedError
+
+ # --- Dispatch + bookkeeping (shared) ---
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "tasks":
+ return True
+ ns = tuple(event["params"]["namespace"])
+ data = event["params"]["data"]
+ if "result" in data:
+ self._handle_task_result(ns, data)
+ else:
+ self._handle_task_start(ns)
+ # Tasks events are folded into the synthesized projections;
+ # suppress from the main event log so iterators don't double-see
+ # the same information in two shapes.
+ return False
+
+ def _handle_task_start(self, ns: tuple[str, ...]) -> None:
+ if not self._should_track(ns) or ns in self._seen:
+ return
+ self._seen.add(ns)
+ graph_name, trigger_call_id = _parse_ns_segment(ns[-1])
+ self._on_started(ns, graph_name or None, trigger_call_id)
+ if trigger_call_id is not None:
+ self._open[ns] = trigger_call_id
+
+ def _pop_terminal_transitions(
+ self, ns: tuple[str, ...], data: dict[str, Any]
+ ) -> list[tuple[tuple[str, ...], SubgraphStatus, str | None]]:
+ """Return and remove tracked children closed by this task result."""
+ result_id = data.get("id")
+ if not result_id:
+ return []
+ transitions: list[tuple[tuple[str, ...], SubgraphStatus, str | None]] = []
+ for child_ns, parent_task_id in list(self._open.items()):
+ if child_ns[:-1] != ns or parent_task_id != result_id:
+ continue
+ status, error = _terminal_from_result(data)
+ transitions.append((child_ns, status, error))
+ del self._open[child_ns]
+ return transitions
+
+ def _handle_task_result(self, ns: tuple[str, ...], data: dict[str, Any]) -> None:
+ for child_ns, status, error in self._pop_terminal_transitions(ns, data):
+ self._on_terminal(child_ns, status, error)
+
+ def finalize(self) -> None:
+ """Emit `completed` for any tracked namespace still open at run end."""
+ for ns in list(self._open):
+ self._on_terminal(ns, "completed", None)
+ self._open.clear()
+
+ def fail(self, err: BaseException) -> None:
+ """Emit terminal status for any tracked namespace still open."""
+ status, error_str = _status_from_exception(err)
+ for ns in list(self._open):
+ self._on_terminal(ns, status, error_str)
+ self._open.clear()
+
+
+def _status_from_exception(err: BaseException) -> tuple[SubgraphStatus, str | None]:
+ """Map a run exception to a subgraph terminal status and error string."""
+ if isinstance(err, GraphDrained):
+ return "drained", None
+ if isinstance(err, GraphInterrupt):
+ return "interrupted", None
+ return "failed", str(err)
+
+
+def _terminal_from_result(
+ payload: dict[str, Any],
+) -> tuple[SubgraphStatus, str | None]:
+ """Map a `TaskResultPayload` to a `(status, error)` pair.
+
+ Order matters: a result with both `error` and `interrupts` prefers
+ the interrupt classification, since `GraphInterrupt` manifests as
+ a populated `interrupts` list, not as `error`.
+ """
+ if payload.get("interrupts"):
+ return "interrupted", None
+ error = payload.get("error")
+ if error:
+ return "failed", str(error)
+ return "completed", None
+
+
+class LifecycleTransformer(_TasksLifecycleBase):
+ """Surface subgraph lifecycle as `lifecycle` protocol events.
+
+ Pushes `LifecyclePayload` to a `StreamChannel` named `lifecycle`.
+ The channel is auto-forwarded by the mux so payloads land in the
+ main event log under `method = "lifecycle"` (native transformer —
+ no `custom:` prefix) — visible to remote SDK clients over the
+ wire and to in-process consumers via `run.lifecycle`.
+
+ Tracks subgraphs at every depth strictly below the transformer's
+ scope, so a graph → subgraph → subgraph chain produces lifecycle
+ events for both nested levels in a flat stream.
+
+ Native transformer — projection key `lifecycle` is exposed as
+ `run.lifecycle`.
+ """
+
+ _native = True
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._channel: StreamChannel[LifecyclePayload] = StreamChannel("lifecycle")
+
+ def init(self) -> dict[str, Any]:
+ return {"lifecycle": self._channel}
+
+ def _should_track(self, ns: tuple[str, ...]) -> bool:
+ depth = len(self.scope)
+ return len(ns) > depth and ns[:depth] == self.scope
+
+ def _on_started(
+ self,
+ ns: tuple[str, ...],
+ graph_name: str | None,
+ trigger_call_id: str | None,
+ ) -> None:
+ if trigger_call_id is None:
+ # Without a task id we can't correlate a parent-result
+ # event back to this namespace — skip the started payload
+ # and rely on finalize/fail to close.
+ return
+ payload: LifecyclePayload = {"event": "started", "namespace": list(ns)}
+ if graph_name:
+ payload["graph_name"] = graph_name
+ payload["trigger_call_id"] = trigger_call_id
+ self._channel.push(payload)
+
+ def _on_terminal(
+ self,
+ ns: tuple[str, ...],
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ payload: LifecyclePayload = {"event": status, "namespace": list(ns)}
+ if error is not None:
+ payload["error"] = error
+ self._channel.push(payload)
+
+
+class SubgraphTransformer(_TasksLifecycleBase):
+ """Discover subgraph invocations as in-process navigation handles.
+
+ Per discovered direct-child subgraph, builds a `SubgraphRunStream`
+ (or `AsyncSubgraphRunStream`) wrapping a child mini-mux scoped to
+ the subgraph's namespace. Consumers iterate `run.subgraphs` to
+ receive handles, then drill into `handle.values` / `handle.messages`
+ / `handle.subgraphs` (recursive grandchildren) / `handle.lifecycle`.
+
+ Each mini-mux owns its own scope and uses its own
+ `SubgraphTransformer` to discover its direct children, so
+ grandchildren live on the child handle — never on the root's
+ `subgraphs` log. Forwarding events into the matching child mini-mux
+ is what keeps the child's projections populated.
+
+ Native transformer — `subgraphs` is exposed as `run.subgraphs`.
+ """
+
+ _native = True
+ supports_sync = True
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[SubgraphRunStream | AsyncSubgraphRunStream] = (
+ StreamChannel()
+ )
+ self._handles: dict[
+ tuple[str, ...], SubgraphRunStream | AsyncSubgraphRunStream
+ ] = {}
+ self._mux: StreamMux | None = None
+
+ def init(self) -> dict[str, Any]:
+ return {"subgraphs": self._log}
+
+ def _on_register(self, mux: Any) -> None:
+ self._mux = mux
+
+ def _should_track(self, ns: tuple[str, ...]) -> bool:
+ # Direct children only — grandchildren are picked up by the
+ # child mini-mux's own SubgraphTransformer.
+ depth = len(self.scope)
+ return len(ns) == depth + 1 and ns[:depth] == self.scope
+
+ def _on_started(
+ self,
+ ns: tuple[str, ...],
+ graph_name: str | None,
+ trigger_call_id: str | None,
+ ) -> None:
+ if self._mux is None:
+ return
+ try:
+ child_mux = self._mux._make_child(ns)
+ except RuntimeError:
+ return
+ handle_cls = AsyncSubgraphRunStream if child_mux.is_async else SubgraphRunStream
+ handle = handle_cls(
+ mux=child_mux,
+ path=ns,
+ graph_name=graph_name,
+ trigger_call_id=trigger_call_id,
+ )
+ self._handles[ns] = handle
+ self._log.push(handle)
+
+ def _on_terminal(
+ self,
+ ns: tuple[str, ...],
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ handle = self._handles.get(ns)
+ if handle is None or not self._mark_terminal(handle, status, error):
+ return
+ self._close_or_fail_handle(handle, status, error)
+
+ async def _aon_terminal(
+ self,
+ ns: tuple[str, ...],
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ handle = self._handles.get(ns)
+ if handle is None or not self._mark_terminal(handle, status, error):
+ return
+ await self._aclose_or_fail_handle(handle, status, error)
+
+ def _mark_terminal(
+ self,
+ handle: SubgraphRunStream | AsyncSubgraphRunStream,
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> bool:
+ """Mark a handle terminal once. Returns True on first transition."""
+ if handle._seen_terminal:
+ return False
+ handle.status = status
+ if error is not None and handle.error is None:
+ handle.error = error
+ handle._seen_terminal = True
+ return True
+
+ def _close_or_fail_handle(
+ self,
+ handle: SubgraphRunStream | AsyncSubgraphRunStream,
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ if handle._mux is None or handle._mux._events._closed:
+ return
+ if status == "failed":
+ handle._mux.fail(RuntimeError(error or "Subgraph failed"))
+ else:
+ handle._mux.close()
+
+ async def _aclose_or_fail_handle(
+ self,
+ handle: SubgraphRunStream | AsyncSubgraphRunStream,
+ status: SubgraphStatus,
+ error: str | None,
+ ) -> None:
+ if handle._mux is None or handle._mux._events._closed:
+ return
+ if status == "failed":
+ await handle._mux.afail(RuntimeError(error or "Subgraph failed"))
+ else:
+ await handle._mux.aclose()
+
+ def _handle_for_event(
+ self, event: ProtocolEvent
+ ) -> SubgraphRunStream | AsyncSubgraphRunStream | None:
+ ns = tuple(event["params"]["namespace"])
+ depth = len(self.scope)
+ if len(ns) < depth + 1:
+ return None
+ handle = self._handles.get(ns[: depth + 1])
+ if handle is None or handle._mux is None or handle._mux._events._closed:
+ return None
+ return handle
+
+ def process(self, event: ProtocolEvent) -> bool:
+ # Run tasks bookkeeping first so a `started` handle exists
+ # by the time we forward the event to the child mini-mux.
+ keep = super().process(event)
+ handle = self._handle_for_event(event)
+ if handle is not None:
+ handle._observe_event(event)
+ handle._mux.push(event)
+ return keep
+
+ async def aprocess(self, event: ProtocolEvent) -> bool:
+ # Async counterpart: repeats the tasks bookkeeping here so
+ # child mini-muxes receive events through their async lane.
+ if event["method"] == "tasks":
+ ns = tuple(event["params"]["namespace"])
+ data = event["params"]["data"]
+ if "result" in data:
+ for child_ns, status, error in self._pop_terminal_transitions(ns, data):
+ await self._aon_terminal(child_ns, status, error)
+ else:
+ self._handle_task_start(ns)
+ keep = False
+ else:
+ keep = True
+ handle = self._handle_for_event(event)
+ if handle is not None:
+ handle._observe_event(event)
+ await handle._mux.apush(event)
+ return keep
+
+ def _complete_open_handles(self) -> BaseException | None:
+ first_error: BaseException | None = None
+ for ns in list(self._open):
+ try:
+ self._on_terminal(ns, "completed", None)
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ self._open.clear()
+ for handle in self._handles.values():
+ if self._mark_terminal(handle, "completed", None):
+ try:
+ self._close_or_fail_handle(handle, "completed", None)
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ return first_error
+
+ async def _acomplete_open_handles(self) -> BaseException | None:
+ first_error: BaseException | None = None
+ for ns in list(self._open):
+ try:
+ await self._aon_terminal(ns, "completed", None)
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ self._open.clear()
+ for handle in self._handles.values():
+ if self._mark_terminal(handle, "completed", None):
+ try:
+ await self._aclose_or_fail_handle(handle, "completed", None)
+ except BaseException as e:
+ if first_error is None:
+ first_error = e
+ return first_error
+
+ def finalize(self) -> None:
+ first_error = self._complete_open_handles()
+ if first_error is not None:
+ raise first_error
+
+ async def afinalize(self) -> None:
+ first_error = await self._acomplete_open_handles()
+ if first_error is not None:
+ raise first_error
+
+ def fail(self, err: BaseException) -> None:
+ status, error_str = _status_from_exception(err)
+ self._open.clear()
+ for handle in self._handles.values():
+ self._mark_terminal(handle, status, error_str)
+ if handle._mux is not None and not handle._mux._events._closed:
+ try:
+ handle._mux.fail(err)
+ except Exception:
+ _logger.warning(
+ "Error failing subgraph mini-mux at %s; "
+ "subscribers may not see the terminal error.",
+ handle.path,
+ exc_info=True,
+ )
+
+ async def afail(self, err: BaseException) -> None:
+ status, error_str = _status_from_exception(err)
+ self._open.clear()
+ for handle in self._handles.values():
+ self._mark_terminal(handle, status, error_str)
+ if handle._mux is not None and not handle._mux._events._closed:
+ try:
+ await handle._mux.afail(err)
+ except Exception:
+ _logger.warning(
+ "Error failing subgraph mini-mux at %s; "
+ "subscribers may not see the terminal error.",
+ handle.path,
+ exc_info=True,
+ )
+
+
+class CheckpointsTransformer(StreamTransformer):
+ """Capture checkpoint events as a drainable stream.
+
+ Surfaces `stream_mode="checkpoints"` data on `run.checkpoints` as
+ a `StreamChannel[dict[str, Any]]`. Each item is in the same format
+ as returned by `get_state()`.
+
+ Checkpoint events are only emitted when a checkpointer is configured
+ on the graph. When no checkpointer is present, the projection exists
+ but receives no events.
+
+ Only events at the run's own scope are captured; checkpoint data from
+ deeper subgraphs is available on the respective subgraph handle's
+ `.checkpoints` projection.
+
+ Native transformer — `run.checkpoints` is a direct attribute.
+ """
+
+ _native = True
+ required_stream_modes = ("checkpoints",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[dict[str, Any]] = StreamChannel()
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"checkpoints": self._log}
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "checkpoints":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._log.push(params["data"])
+ return True
+
+
+class DebugTransformer(StreamTransformer):
+ """Capture debug events as a drainable stream.
+
+ Surfaces `stream_mode="debug"` data on `run.debug` as a
+ `StreamChannel[dict[str, Any]]`. Each item is a debug event with
+ step-level detail (checkpoint snapshots, task payloads, and
+ task results wrapped with step number and timestamp).
+
+ Only events at the run's own scope are captured; debug data from
+ deeper subgraphs is available on the respective subgraph handle's
+ `.debug` projection.
+
+ Native transformer — `run.debug` is a direct attribute.
+ """
+
+ _native = True
+ required_stream_modes = ("debug",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[dict[str, Any]] = StreamChannel()
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"debug": self._log}
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "debug":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._log.push(params["data"])
+ return True
+
+
+class TasksTransformer(StreamTransformer):
+ """Capture raw task events as a drainable stream.
+
+ Surfaces `stream_mode="tasks"` data on `run.tasks` as a
+ `StreamChannel[dict[str, Any]]`. Each item is a task payload
+ (start or result).
+
+ `LifecycleTransformer` and `SubgraphTransformer` also consume
+ `tasks` events for subgraph discovery and lifecycle tracking.
+ This transformer captures the raw payloads independently for
+ consumers who need task-level detail.
+
+ Only events at the run's own scope are captured; task data from
+ deeper subgraphs is available on the respective subgraph handle's
+ `.tasks` projection.
+
+ Native transformer — `run.tasks` is a direct attribute.
+ """
+
+ _native = True
+ required_stream_modes = ("tasks",)
+
+ def __init__(self, scope: tuple[str, ...] = ()) -> None:
+ super().__init__(scope)
+ self._log: StreamChannel[dict[str, Any]] = StreamChannel()
+ self._scope_list: list[str] = list(scope)
+
+ def init(self) -> dict[str, Any]:
+ return {"tasks": self._log}
+
+ def process(self, event: ProtocolEvent) -> bool:
+ if event["method"] != "tasks":
+ return True
+ params = event["params"]
+ if params["namespace"] != self._scope_list:
+ return True
+ self._log.push(params["data"])
+ return True
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/__init__.py b/python/user_packages/Python313/site-packages/langgraph/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f11b2b494ae7eecd26b675a550efeb6de20cf5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/utils/__init__.py
@@ -0,0 +1 @@
+"""Legacy utilities module, to be removed in v1."""
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b2532943fc0a809ee8221dbb849389f7c974cf8
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/config.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5facffa5f4ee14930e331abfccf9e81ef6b6bd7d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/config.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/runnable.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/runnable.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c196ffe59302bbb5e36d6f344b670ba8e6490061
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph/utils/__pycache__/runnable.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/config.py b/python/user_packages/Python313/site-packages/langgraph/utils/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..f855d0a12dc617a0842d008a73a4b2a8356ed7c9
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/utils/config.py
@@ -0,0 +1,4 @@
+"""Backwards compat imports for config utilities, to be removed in v1."""
+
+from langgraph._internal._config import ensure_config, patch_configurable # noqa: F401
+from langgraph.config import get_config, get_store # noqa: F401
diff --git a/python/user_packages/Python313/site-packages/langgraph/utils/runnable.py b/python/user_packages/Python313/site-packages/langgraph/utils/runnable.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e7ccc668b8dc1cd4061e4f550438eac5cc780c8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph/utils/runnable.py
@@ -0,0 +1,3 @@
+"""Backwards compat imports for runnable utilities, to be removed in v1."""
+
+from langgraph._internal._runnable import RunnableCallable, RunnableLike # noqa: F401
diff --git a/python/user_packages/Python313/site-packages/langgraph_checkpoint-4.1.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/langgraph_checkpoint-4.1.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..fc0602feecdd6748623c852ab534e1ca612673c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_checkpoint-4.1.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python/user_packages/Python313/site-packages/langgraph_prebuilt-1.1.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/langgraph_prebuilt-1.1.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..fc0602feecdd6748623c852ab534e1ca612673c7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_prebuilt-1.1.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1704b5e654c7a4213daa74f725871cba4e541a20
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/cache.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/cache.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e50f8f311af5d8e610b8d7cd2e3ab072d0b322dd
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/cache.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/client.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/client.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e8e56c6022a920e8518997ef32e5c87e53148b0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/client.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/errors.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..447392d46cbee3c23c96fb3527bc7fe142846f03
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/errors.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/runtime.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/runtime.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..813fdb7d07132e508e76ef226954e01980a6d278
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/runtime.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/schema.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/schema.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c4cb359eea4e5a8381a6c67045ffbf61369df80
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/schema.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/sse.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/sse.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89c9e6577e771cc4e3a8301afb50820b6c1cbb56
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/__pycache__/sse.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4f094dfd0ed5f50479d7292d5654f9cf6cf7c8d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c0d009ad2b807d6359b9712ccbd4dcda1466d2e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e2cbdbe721d38a631d34384a8639f6b44e37bc9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2931bf565b2f45a9e8e498c32d8d3282e1f1f5e6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c48914462c511c421786b1d2a0a33e10ad3ab3b
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1d6d74aed45fb59ffb3fd2ddf78fe38c2636d79
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b6971e7f9ed2a404ac153c5e782d3d05555523a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fddbba4555e33003054c7961b48c9ad90c4f627
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbce12dfce58fd21cf946a528089848a8b13525f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a2696a7380d2532958a235a4c1a4678e9ecd6dc
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6193f01effa4d7c5232605a1568420ac7d309876
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__init__.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ab36bf804bf431c415683bae0e69d7baa813bd7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__init__.py
@@ -0,0 +1,20 @@
+"""Sync client exports."""
+
+from langgraph_sdk._sync.assistants import SyncAssistantsClient
+from langgraph_sdk._sync.client import SyncLangGraphClient, get_sync_client
+from langgraph_sdk._sync.cron import SyncCronClient
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk._sync.runs import SyncRunsClient
+from langgraph_sdk._sync.store import SyncStoreClient
+from langgraph_sdk._sync.threads import SyncThreadsClient
+
+__all__ = [
+ "SyncAssistantsClient",
+ "SyncCronClient",
+ "SyncHttpClient",
+ "SyncLangGraphClient",
+ "SyncRunsClient",
+ "SyncStoreClient",
+ "SyncThreadsClient",
+ "get_sync_client",
+]
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc804483d74e29be3e0cb869e53fb745d34ef979
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2c714020b2cbf57503b280e47b11036e0e2d572
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ca2191c7b6bdf392c28aba8d6132d35562fdb60
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74f000fe4657d011564814b8bc148baa825071e9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..083d1eaccfc3944d794f983c81a9a9ae644d9098
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a93f51b4b21cbeb49f5fda005281423a0aa5e23
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ccd5c6660f417db560d1c75d68f961cd94ad91a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a96e2881c5209e4411523ce2e3d4caa2566981a9
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/client.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a0d641e201cac771899e929187585926ec65184
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/client.py
@@ -0,0 +1,127 @@
+"""Sync LangGraph client."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from types import TracebackType
+
+import httpx
+
+from langgraph_sdk._shared.types import TimeoutTypes
+from langgraph_sdk._shared.utilities import NOT_PROVIDED, _get_headers
+from langgraph_sdk._sync.assistants import SyncAssistantsClient
+from langgraph_sdk._sync.cron import SyncCronClient
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk._sync.runs import SyncRunsClient
+from langgraph_sdk._sync.store import SyncStoreClient
+from langgraph_sdk._sync.threads import SyncThreadsClient
+
+
+def get_sync_client(
+ *,
+ url: str | None = None,
+ api_key: str | None = NOT_PROVIDED,
+ headers: Mapping[str, str] | None = None,
+ timeout: TimeoutTypes | None = None,
+) -> SyncLangGraphClient:
+ """Get a synchronous LangGraphClient instance.
+
+ Args:
+ url: The URL of the LangGraph API.
+ api_key: API key for authentication. Can be:
+ - A string: use this exact API key
+ - `None`: explicitly skip loading from environment variables
+ - Not provided (default): auto-load from environment in this order:
+ 1. `LANGGRAPH_API_KEY`
+ 2. `LANGSMITH_API_KEY`
+ 3. `LANGCHAIN_API_KEY`
+ headers: Optional custom headers
+ timeout: Optional timeout configuration for the HTTP client.
+ Accepts an httpx.Timeout instance, a float (seconds), or a tuple of timeouts.
+ Tuple format is (connect, read, write, pool)
+ If not provided, defaults to connect=5s, read=300s, write=300s, and pool=5s.
+ Returns:
+ SyncLangGraphClient: The top-level synchronous client for accessing AssistantsClient,
+ ThreadsClient, RunsClient, and CronClient.
+
+ ???+ example "Example"
+
+ ```python
+ from langgraph_sdk import get_sync_client
+
+ # get top-level synchronous LangGraphClient
+ client = get_sync_client(url="http://localhost:8123")
+
+ # example usage: client..()
+ assistant = client.assistants.get(assistant_id="some_uuid")
+ ```
+
+ ???+ example "Skip auto-loading API key from environment:"
+
+ ```python
+ from langgraph_sdk import get_sync_client
+
+ # Don't load API key from environment variables
+ client = get_sync_client(
+ url="http://localhost:8123",
+ api_key=None
+ )
+ ```
+ """
+
+ if url is None:
+ url = "http://localhost:8123"
+
+ transport = httpx.HTTPTransport(retries=5)
+ client = httpx.Client(
+ base_url=url,
+ transport=transport,
+ timeout=(
+ httpx.Timeout(timeout) # type: ignore[arg-type]
+ if timeout is not None
+ else httpx.Timeout(connect=5, read=300, write=300, pool=5)
+ ),
+ headers=_get_headers(api_key, headers),
+ )
+ return SyncLangGraphClient(client)
+
+
+class SyncLangGraphClient:
+ """Synchronous client for interacting with the LangGraph API.
+
+ This class provides synchronous access to LangGraph API endpoints for managing
+ assistants, threads, runs, cron jobs, and data storage.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant = client.assistants.get("asst_123")
+ ```
+ """
+
+ def __init__(self, client: httpx.Client) -> None:
+ self.http = SyncHttpClient(client)
+ self.assistants = SyncAssistantsClient(self.http)
+ self.threads = SyncThreadsClient(self.http)
+ self.runs = SyncRunsClient(self.http)
+ self.crons = SyncCronClient(self.http)
+ self.store = SyncStoreClient(self.http)
+
+ def __enter__(self) -> SyncLangGraphClient:
+ """Enter the sync context manager."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> None:
+ """Exit the sync context manager."""
+ self.close()
+
+ def close(self) -> None:
+ """Close the underlying HTTP client."""
+ if hasattr(self, "http"):
+ self.http.client.close()
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/cron.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/cron.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4a66d4354afea5019db5e27359b023fedfc05eb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/cron.py
@@ -0,0 +1,508 @@
+"""Synchronous cron client for LangGraph SDK."""
+
+from __future__ import annotations
+
+import warnings
+from collections.abc import Mapping, Sequence
+from datetime import datetime, tzinfo
+from typing import Any
+
+from langgraph_sdk._shared.utilities import _resolve_timezone
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ All,
+ Config,
+ Context,
+ Cron,
+ CronSelectField,
+ CronSortBy,
+ Durability,
+ Input,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ SortOrder,
+ StreamMode,
+)
+
+
+class SyncCronClient:
+ """Synchronous client for managing cron jobs in LangGraph.
+
+ This class provides methods to create and manage scheduled tasks (cron jobs) for automated graph executions.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")
+ ```
+
+ !!! note "Feature Availability"
+
+ The crons client functionality is not supported on all licenses.
+ Please check the relevant license documentation for the most up-to-date
+ details on feature availability.
+ """
+
+ def __init__(self, http_client: SyncHttpClient) -> None:
+ self.http = http_client
+
+ def create_for_thread(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron job for a thread.
+
+ Args:
+ thread_id: the thread ID to run the cron job on.
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled. By default, it is considered enabled.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The cron `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_run = client.crons.create_for_thread(
+ thread_id="my-thread-id",
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True
+ )
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "checkpoint_during": checkpoint_during,
+ "webhook": webhook,
+ "multitask_strategy": multitask_strategy,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ f"/threads/{thread_id}/runs/crons",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def create(
+ self,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron run.
+
+ Args:
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' (default) or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up. Clients are responsible for cleaning up kept threads.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled. By default, it is considered enabled.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The cron `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_run = client.crons.create(
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ checkpoint_during=True,
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True
+ )
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint_during": checkpoint_during,
+ "on_run_completed": on_run_completed,
+ "multitask_strategy": multitask_strategy,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ "/runs/crons", json=payload, headers=headers, params=params
+ )
+
+ def delete(
+ self,
+ cron_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a cron.
+
+ Args:
+ cron_id: The cron ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.crons.delete(
+ cron_id="cron_to_delete"
+ )
+ ```
+
+ """
+ self.http.delete(f"/runs/crons/{cron_id}", headers=headers, params=params)
+
+ def update(
+ self,
+ cron_id: str,
+ *,
+ schedule: str | None = None,
+ end_time: datetime | None = None,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ webhook: str | None = None,
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Cron:
+ """Update a cron job by ID.
+
+ Args:
+ cron_id: The cron ID to update.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ end_time: The end date to stop running the cron.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context added to the assistant.
+ webhook: Webhook to call after LangGraph API call is done.
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to interrupt immediately after they get executed.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up.
+ enabled: Enable or disable the cron job.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated cron job.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ updated_cron = client.crons.update(
+ cron_id="1ef3cefa-4c09-6926-96d0-3dc97fd5e39b",
+ schedule="0 10 * * *",
+ enabled=False,
+ )
+ ```
+
+ """
+ payload = {
+ "schedule": schedule,
+ "end_time": end_time.isoformat() if end_time else None,
+ "input": input,
+ "metadata": metadata,
+ "config": config,
+ "context": context,
+ "webhook": webhook,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "on_run_completed": on_run_completed,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.patch(
+ f"/runs/crons/{cron_id}",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def search(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ enabled: bool | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: CronSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[CronSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Cron]:
+ """Get a list of cron jobs.
+
+ Args:
+ assistant_id: The assistant ID or graph name to search for.
+ thread_id: the thread ID to search for.
+ enabled: Whether the cron job is enabled.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The list of cron jobs returned by the search,
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_jobs = client.crons.search(
+ assistant_id="my_assistant_id",
+ thread_id="my_thread_id",
+ enabled=True,
+ limit=5,
+ offset=5,
+ )
+ print(cron_jobs)
+ ```
+
+ ```shell
+ ----------------------------------------------------------
+
+ [
+ {
+ 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
+ 'assistant_id': 'my_assistant_id',
+ 'thread_id': 'my_thread_id',
+ 'user_id': None,
+ 'payload':
+ {
+ 'input': {'start_time': ''},
+ 'schedule': '4 * * * *',
+ 'assistant_id': 'my_assistant_id'
+ },
+ 'schedule': '4 * * * *',
+ 'next_run_date': '2024-07-25T17:04:00+00:00',
+ 'end_time': None,
+ 'created_at': '2024-07-08T06:02:23.073257+00:00',
+ 'updated_at': '2024-07-08T06:02:23.073257+00:00'
+ }
+ ]
+ ```
+ """
+ payload: dict[str, Any] = {
+ "assistant_id": assistant_id,
+ "thread_id": thread_id,
+ "enabled": enabled,
+ "limit": limit,
+ "offset": offset,
+ }
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ "/runs/crons/search", json=payload, headers=headers, params=params
+ )
+
+ def count(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count cron jobs matching filters.
+
+ Args:
+ assistant_id: Assistant ID to filter by.
+ thread_id: Thread ID to filter by.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of crons matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if assistant_id:
+ payload["assistant_id"] = assistant_id
+ if thread_id:
+ payload["thread_id"] = thread_id
+ return self.http.post(
+ "/runs/crons/count", json=payload, headers=headers, params=params
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/http.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/http.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba56543be0cc30b157f5afe4aaa3c5ab8288ea16
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/http.py
@@ -0,0 +1,303 @@
+"""Synchronous HTTP client for LangGraph API."""
+
+from __future__ import annotations
+
+import logging
+import sys
+import warnings
+from collections.abc import Callable, Iterator, Mapping
+from typing import Any, cast
+
+import httpx
+import orjson
+
+from langgraph_sdk._shared.utilities import (
+ _orjson_default,
+ _validate_reconnect_location,
+)
+from langgraph_sdk.errors import _raise_for_status_typed
+from langgraph_sdk.schema import QueryParamTypes, StreamPart
+from langgraph_sdk.sse import SSEDecoder, iter_lines_raw
+
+logger = logging.getLogger(__name__)
+
+
+class SyncHttpClient:
+ """Handle synchronous requests to the LangGraph API.
+
+ Provides error messaging and content handling enhancements above the
+ underlying httpx client, mirroring the interface of [HttpClient](#HttpClient)
+ but for sync usage.
+
+ Attributes:
+ client (httpx.Client): Underlying HTTPX sync client.
+ """
+
+ def __init__(self, client: httpx.Client) -> None:
+ self.client = client
+
+ def get(
+ self,
+ path: str,
+ *,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `GET` request."""
+ r = self.client.get(path, params=params, headers=headers)
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def post(
+ self,
+ path: str,
+ *,
+ json: dict[str, Any] | list | None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `POST` request."""
+ if json is not None:
+ request_headers, content = _encode_json(json)
+ else:
+ request_headers, content = {}, b""
+ if headers:
+ request_headers.update(headers)
+ r = self.client.post(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def put(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PUT` request."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+
+ r = self.client.put(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def patch(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PATCH` request."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+ r = self.client.patch(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def delete(
+ self,
+ path: str,
+ *,
+ json: Any | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> None:
+ """Send a `DELETE` request."""
+ r = self.client.request(
+ "DELETE", path, json=json, params=params, headers=headers
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+
+ def request_reconnect(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ reconnect_limit: int = 5,
+ ) -> Any:
+ """Send a request that automatically reconnects to Location header."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+ with self.client.stream(
+ method, path, headers=request_headers, content=content, params=params
+ ) as r:
+ if on_response:
+ on_response(r)
+ try:
+ r.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ body = r.read().decode()
+ if sys.version_info >= (3, 11):
+ e.add_note(body)
+ else:
+ logger.error(f"Error from langgraph-api: {body}", exc_info=e)
+ raise e
+ loc = r.headers.get("location")
+ if reconnect_limit <= 0 or not loc:
+ return _decode_json(r)
+ _validate_reconnect_location(self.client.base_url, loc)
+ try:
+ return _decode_json(r)
+ except httpx.HTTPError:
+ warnings.warn(
+ f"Request failed, attempting reconnect to Location: {loc}",
+ stacklevel=2,
+ )
+ r.close()
+ return self.request_reconnect(
+ loc,
+ "GET",
+ headers=request_headers,
+ # don't pass on_response so it's only called once
+ reconnect_limit=reconnect_limit - 1,
+ )
+
+ def stream(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Iterator[StreamPart]:
+ """Stream the results of a request using SSE."""
+ if json is not None:
+ request_headers, content = _encode_json(json)
+ else:
+ request_headers, content = {}, None
+ request_headers["Accept"] = "text/event-stream"
+ request_headers["Cache-Control"] = "no-store"
+ if headers:
+ request_headers.update(headers)
+
+ reconnect_headers = {
+ key: value
+ for key, value in request_headers.items()
+ if key.lower() not in {"content-length", "content-type"}
+ }
+
+ last_event_id: str | None = None
+ reconnect_path: str | None = None
+ reconnect_attempts = 0
+ max_reconnect_attempts = 5
+
+ while True:
+ current_headers = dict(
+ request_headers if reconnect_path is None else reconnect_headers
+ )
+ if last_event_id is not None:
+ current_headers["Last-Event-ID"] = last_event_id
+
+ current_method = method if reconnect_path is None else "GET"
+ current_content = content if reconnect_path is None else None
+ current_params = params if reconnect_path is None else None
+
+ retry = False
+ with self.client.stream(
+ current_method,
+ reconnect_path or path,
+ headers=current_headers,
+ content=current_content,
+ params=current_params,
+ ) as res:
+ if reconnect_path is None and on_response:
+ on_response(res)
+ # check status
+ _raise_for_status_typed(res)
+ # check content type
+ content_type = res.headers.get("content-type", "").partition(";")[0]
+ if "text/event-stream" not in content_type:
+ raise httpx.TransportError(
+ "Expected response header Content-Type to contain 'text/event-stream', "
+ f"got {content_type!r}"
+ )
+
+ reconnect_location = res.headers.get("location")
+ if reconnect_location:
+ _validate_reconnect_location(
+ self.client.base_url, reconnect_location
+ )
+ reconnect_path = reconnect_location
+
+ decoder = SSEDecoder()
+ try:
+ for line in iter_lines_raw(res):
+ sse = decoder.decode(cast(bytes, line).rstrip(b"\n"))
+ if sse is not None:
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ yield sse
+ except httpx.HTTPError:
+ # httpx.TransportError inherits from HTTPError, so transient
+ # disconnects during streaming land here.
+ if reconnect_path is None:
+ raise
+ retry = True
+ else:
+ if sse := decoder.decode(b""):
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ # See async stream implementation for rationale on
+ # skipping empty flush events.
+ yield sse
+ if retry:
+ reconnect_attempts += 1
+ if reconnect_attempts > max_reconnect_attempts:
+ raise httpx.TransportError(
+ "Exceeded maximum SSE reconnection attempts"
+ )
+ continue
+ break
+
+
+def _encode_json(json: Any) -> tuple[dict[str, str], bytes]:
+ body = orjson.dumps(
+ json,
+ _orjson_default,
+ orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
+ )
+ content_length = str(len(body))
+ content_type = "application/json"
+ headers = {"Content-Length": content_length, "Content-Type": content_type}
+ return headers, body
+
+
+def _decode_json(r: httpx.Response) -> Any:
+ body = r.read()
+ return orjson.loads(body) if body else None
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/runs.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/runs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a184d3209d42f32e3ede6444be0ed0a4b608579
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/runs.py
@@ -0,0 +1,1162 @@
+"""Synchronous client for managing runs in LangGraph."""
+
+from __future__ import annotations
+
+import builtins
+import warnings
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from typing import Any, Literal, overload
+
+import httpx
+
+from langgraph_sdk._shared.utilities import (
+ _get_run_metadata_from_response,
+ _sse_to_v2_dict,
+)
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ All,
+ BulkCancelRunsStatus,
+ CancelAction,
+ Checkpoint,
+ Command,
+ Config,
+ Context,
+ DisconnectMode,
+ Durability,
+ IfNotExists,
+ Input,
+ LangSmithTracing,
+ MultitaskStrategy,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ RunCreate,
+ RunCreateMetadata,
+ RunSelectField,
+ RunStatus,
+ StreamMode,
+ StreamPart,
+ StreamPartV2,
+ StreamVersion,
+)
+
+
+def _wrap_stream_v2_sync(
+ raw: Iterator[StreamPart],
+) -> Iterator[StreamPartV2]:
+ """Wrap a raw SSE stream, converting each event to a v2 dict."""
+ for part in raw:
+ v2 = _sse_to_v2_dict(part.event, part.data)
+ if v2 is not None:
+ yield v2
+
+
+class SyncRunsClient:
+ """Synchronous client for managing runs in LangGraph.
+
+ This class provides methods to create, retrieve, and manage runs, which represent
+ individual executions of graphs.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> Iterator[StreamPartV2]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> Iterator[StreamPartV2]: ...
+
+ def stream(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ version: StreamVersion = "v1",
+ ) -> Iterator[StreamPart | StreamPartV2]:
+ """Create a run and stream the results.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ feedback_keys: Feedback keys to assign to run.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ version: Stream format version. "v1" (default) returns raw SSE StreamPart
+ NamedTuples. "v2" returns typed dicts with `type`, `ns`, and `data` keys.
+
+ Returns:
+ Iterator of stream results.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ async for chunk in client.runs.stream(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ stream_mode=["values","debug"],
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ ):
+ print(chunk)
+ ```
+ ```shell
+ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
+ StreamPart(event='end', data=None)
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload: dict[str, Any] = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "feedback_keys": feedback_keys,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ endpoint = (
+ f"/threads/{thread_id}/runs/stream"
+ if thread_id is not None
+ else "/runs/stream"
+ )
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ raw = self.http.stream(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+ if version == "v2":
+ return _wrap_stream_v2_sync(raw)
+ return raw
+
+ @overload
+ def create(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ @overload
+ def create(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ def create(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> Run:
+ """Create a background run.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The created background `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ background_run = client.runs.create(
+ thread_id="my_thread_id",
+ assistant_id="my_assistant_id",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(background_run)
+ ```
+
+ ```shell
+ --------------------------------------------------------------------------------
+
+ {
+ 'run_id': 'my_run_id',
+ 'thread_id': 'my_thread_id',
+ 'assistant_id': 'my_assistant_id',
+ 'created_at': '2024-07-25T15:35:42.598503+00:00',
+ 'updated_at': '2024-07-25T15:35:42.598503+00:00',
+ 'metadata': {},
+ 'status': 'pending',
+ 'kwargs':
+ {
+ 'input':
+ {
+ 'messages': [
+ {
+ 'role': 'user',
+ 'content': 'how are you?'
+ }
+ ]
+ },
+ 'config':
+ {
+ 'metadata':
+ {
+ 'created_by': 'system'
+ },
+ 'configurable':
+ {
+ 'run_id': 'my_run_id',
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'my_thread_id',
+ 'checkpoint_id': None,
+ 'assistant_id': 'my_assistant_id'
+ }
+ },
+ 'context':
+ {
+ 'model_name': 'openai'
+ },
+ 'webhook': "https://my.fake.webhook.com",
+ 'temporary': False,
+ 'stream_mode': ['values'],
+ 'feedback_keys': None,
+ 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
+ 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
+ },
+ 'multitask_strategy': 'interrupt'
+ }
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ return self.http.post(
+ f"/threads/{thread_id}/runs" if thread_id else "/runs",
+ json=payload,
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+
+ def create_batch(
+ self,
+ payloads: builtins.list[RunCreate],
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """Create a batch of stateless background runs."""
+
+ def filter_payload(payload: RunCreate):
+ return {k: v for k, v in payload.items() if v is not None}
+
+ filtered = [filter_payload(payload) for payload in payloads]
+ return self.http.post(
+ "/runs/batch", json=filtered, headers=headers, params=params
+ )
+
+ @overload
+ def wait(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ @overload
+ def wait(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ def wait(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ thread_id: the thread ID to create the run on.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to run.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ raise_error: Whether to raise an error if the run fails.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The output of the `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ final_state_of_run = client.runs.wait(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(final_state_of_run)
+ ```
+
+ ```shell
+
+ -------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ }
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "checkpoint_during": checkpoint_during,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "raise_error": raise_error,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ endpoint = (
+ f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
+ )
+ return self.http.request_reconnect(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+
+ def list(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ offset: int = 0,
+ status: RunStatus | None = None,
+ select: builtins.list[RunSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """List runs.
+
+ Args:
+ thread_id: The thread ID to list runs for.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The runs for the thread.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.list(
+ thread_id="thread_id",
+ limit=5,
+ offset=5,
+ )
+ ```
+
+ """
+ query_params: dict[str, Any] = {"limit": limit, "offset": offset}
+ if status is not None:
+ query_params["status"] = status
+ if select:
+ query_params["select"] = select
+ if params:
+ query_params.update(params)
+ return self.http.get(
+ f"/threads/{thread_id}/runs", params=query_params, headers=headers
+ )
+
+ def get(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to get.
+ run_id: The run ID to get.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ `Run` object.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ run = client.runs.get(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete",
+ )
+ ```
+ """
+
+ return self.http.get(
+ f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
+ )
+
+ def cancel(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ wait: bool = False,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to cancel.
+ run_id: The run ID to cancel.
+ wait: Whether to wait until run has completed.
+ action: Action to take when cancelling the run. Possible values
+ are `interrupt` or `rollback`. Default is `interrupt`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.cancel(
+ thread_id="thread_id_to_cancel",
+ run_id="run_id_to_cancel",
+ wait=True,
+ action="interrupt"
+ )
+ ```
+
+ """
+ query_params = {
+ "wait": 1 if wait else 0,
+ "action": action,
+ }
+ if params:
+ query_params.update(params)
+ if wait:
+ return self.http.request_reconnect(
+ f"/threads/{thread_id}/runs/{run_id}/cancel",
+ "POST",
+ json=None,
+ params=query_params,
+ headers=headers,
+ )
+ return self.http.post(
+ f"/threads/{thread_id}/runs/{run_id}/cancel",
+ json=None,
+ params=query_params,
+ headers=headers,
+ )
+
+ def cancel_many(
+ self,
+ *,
+ thread_id: str | None = None,
+ run_ids: Sequence[str] | None = None,
+ status: BulkCancelRunsStatus | None = None,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Cancel one or more runs.
+
+ Can cancel runs by thread ID and run IDs, or by status filter.
+
+ Args:
+ thread_id: The ID of the thread containing runs to cancel.
+ run_ids: List of run IDs to cancel.
+ status: Filter runs by status to cancel. Must be one of
+ `"pending"`, `"running"`, or `"all"`.
+ action: Action to take when cancelling the run. Possible values
+ are `"interrupt"` or `"rollback"`. Default is `"interrupt"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ # Cancel all pending runs
+ client.runs.cancel_many(status="pending")
+ # Cancel specific runs on a thread
+ client.runs.cancel_many(
+ thread_id="my_thread_id",
+ run_ids=["run_1", "run_2"],
+ action="rollback",
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if run_ids:
+ payload["run_ids"] = run_ids
+ if status:
+ payload["status"] = status
+ query_params: dict[str, Any] = {"action": action}
+ if params:
+ query_params.update(params)
+ self.http.post(
+ "/runs/cancel",
+ json=payload,
+ headers=headers,
+ params=query_params,
+ )
+
+ def join(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict:
+ """Block until a run is done. Returns the final state of the thread.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.join(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join"
+ )
+ ```
+
+ """
+ return self.http.request_reconnect(
+ f"/threads/{thread_id}/runs/{run_id}/join",
+ "GET",
+ headers=headers,
+ params=params,
+ )
+
+ def join_stream(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ cancel_on_disconnect: bool = False,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ last_event_id: str | None = None,
+ ) -> Iterator[StreamPart]:
+ """Stream output from a run in real-time, until the run is done.
+ Output is not buffered, so any output produced before this call will
+ not be received here.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
+ when creating the run. Background runs default to having the union of all
+ stream modes.
+ cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+ last_event_id: The last event ID to use for the stream.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.join_stream(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join",
+ stream_mode=["values", "debug"]
+ )
+ ```
+
+ """
+ query_params = {
+ "stream_mode": stream_mode,
+ "cancel_on_disconnect": cancel_on_disconnect,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{thread_id}/runs/{run_id}/stream",
+ "GET",
+ params=query_params,
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ }
+ or None,
+ )
+
+ def delete(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a run.
+
+ Args:
+ thread_id: The thread ID to delete.
+ run_id: The run ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.delete(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete"
+ )
+ ```
+
+ """
+ self.http.delete(
+ f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/store.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/store.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e698fe70d3130976c80244e66278c65d49ca29b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/store.py
@@ -0,0 +1,313 @@
+"""Synchronous store client for LangGraph SDK."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any, Literal
+
+from langgraph_sdk._shared.utilities import _provided_vals
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ Item,
+ ListNamespaceResponse,
+ QueryParamTypes,
+ SearchItemsResponse,
+)
+
+
+class SyncStoreClient:
+ """A client for synchronous operations on a key-value store.
+
+ Provides methods to interact with a remote key-value store, allowing
+ storage and retrieval of items within namespaced hierarchies.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024"))
+ client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ def put_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ value: Mapping[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ ttl: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Store or update an item.
+
+ Args:
+ namespace: A list of strings representing the namespace path.
+ key: The unique identifier for the item within the namespace.
+ value: A dictionary containing the item's data.
+ index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
+ ttl: Optional time-to-live in minutes for the item, or None for no expiration.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.store.put_item(
+ ["documents", "user123"],
+ key="item456",
+ value={"title": "My Document", "content": "Hello World"}
+ )
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+ payload = {
+ "namespace": namespace,
+ "key": key,
+ "value": value,
+ "index": index,
+ "ttl": ttl,
+ }
+ self.http.put(
+ "/store/items", json=_provided_vals(payload), headers=headers, params=params
+ )
+
+ def get_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Item:
+ """Retrieve a single item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The retrieved item.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ item = client.store.get_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ print(item)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------
+
+ {
+ 'namespace': ['documents', 'user123'],
+ 'key': 'item456',
+ 'value': {'title': 'My Document', 'content': 'Hello World'},
+ 'created_at': '2024-07-30T12:00:00Z',
+ 'updated_at': '2024-07-30T12:00:00Z'
+ }
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+
+ query_params: dict[str, Any] = {"key": key, "namespace": ".".join(namespace)}
+ if refresh_ttl is not None:
+ query_params["refresh_ttl"] = refresh_ttl
+ if params:
+ query_params.update(params)
+ return self.http.get("/store/items", params=query_params, headers=headers)
+
+ def delete_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete an item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.store.delete_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ ```
+ """
+ self.http.delete(
+ "/store/items",
+ json={"key": key, "namespace": namespace},
+ headers=headers,
+ params=params,
+ )
+
+ def search_items(
+ self,
+ namespace_prefix: Sequence[str],
+ /,
+ filter: Mapping[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ query: str | None = None,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> SearchItemsResponse:
+ """Search for items within a namespace prefix.
+
+ Args:
+ namespace_prefix: List of strings representing the namespace prefix.
+ filter: Optional dictionary of key-value pairs to filter results.
+ limit: Maximum number of items to return (default is 10).
+ offset: Number of items to skip before returning results (default is 0).
+ query: Optional query for natural language search.
+ refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of items matching the search criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ items = client.store.search_items(
+ ["documents"],
+ filter={"author": "John Doe"},
+ limit=5,
+ offset=0
+ )
+ print(items)
+ ```
+ ```shell
+ ----------------------------------------------------------------
+
+ {
+ "items": [
+ {
+ "namespace": ["documents", "user123"],
+ "key": "item789",
+ "value": {
+ "title": "Another Document",
+ "author": "John Doe"
+ },
+ "created_at": "2024-07-30T12:00:00Z",
+ "updated_at": "2024-07-30T12:00:00Z"
+ },
+ # ... additional items ...
+ ]
+ }
+ ```
+ """
+ payload = {
+ "namespace_prefix": namespace_prefix,
+ "filter": filter,
+ "limit": limit,
+ "offset": offset,
+ "query": query,
+ "refresh_ttl": refresh_ttl,
+ }
+ return self.http.post(
+ "/store/items/search",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
+
+ def list_namespaces(
+ self,
+ prefix: list[str] | None = None,
+ suffix: list[str] | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ListNamespaceResponse:
+ """List namespaces with optional match conditions.
+
+ Args:
+ prefix: Optional list of strings representing the prefix to filter namespaces.
+ suffix: Optional list of strings representing the suffix to filter namespaces.
+ max_depth: Optional integer specifying the maximum depth of namespaces to return.
+ limit: Maximum number of namespaces to return (default is 100).
+ offset: Number of namespaces to skip before returning results (default is 0).
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ A list of namespaces matching the criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ namespaces = client.store.list_namespaces(
+ prefix=["documents"],
+ max_depth=3,
+ limit=10,
+ offset=0
+ )
+ print(namespaces)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------
+
+ [
+ ["documents", "user123", "reports"],
+ ["documents", "user456", "invoices"],
+ ...
+ ]
+ ```
+ """
+ payload = {
+ "prefix": prefix,
+ "suffix": suffix,
+ "max_depth": max_depth,
+ "limit": limit,
+ "offset": offset,
+ }
+ return self.http.post(
+ "/store/namespaces",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/threads.py b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/threads.py
new file mode 100644
index 0000000000000000000000000000000000000000..d18aabecb4da0616da26414ee053177cd5d17634
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/langgraph_sdk/_sync/threads.py
@@ -0,0 +1,762 @@
+"""Synchronous client for managing threads in LangGraph."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Literal, overload
+
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ Checkpoint,
+ Json,
+ OnConflictBehavior,
+ PruneStrategy,
+ QueryParamTypes,
+ SortOrder,
+ StreamPart,
+ Thread,
+ ThreadSelectField,
+ ThreadSortBy,
+ ThreadState,
+ ThreadStatus,
+ ThreadStreamMode,
+ ThreadUpdateStateResponse,
+)
+
+
+class SyncThreadsClient:
+ """Synchronous client for managing threads in LangGraph.
+
+ This class provides methods to create, retrieve, and manage threads,
+ which represent conversations or stateful interactions.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.create(metadata={"user_id": "123"})
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ def get(
+ self,
+ thread_id: str,
+ *,
+ include: Sequence[str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Get a thread by ID.
+
+ Args:
+ thread_id: The ID of the thread to get.
+ include: Additional fields to include in the response.
+ Supported values: `"ttl"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `Thread` object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.get(
+ thread_id="my_thread_id"
+ )
+ print(thread)
+ ```
+ ```shell
+ -----------------------------------------------------
+
+ {
+ 'thread_id': 'my_thread_id',
+ 'created_at': '2024-07-18T18:35:15.540834+00:00',
+ 'updated_at': '2024-07-18T18:35:15.540834+00:00',
+ 'metadata': {'graph_id': 'agent'}
+ }
+ ```
+
+ """
+ query_params: dict[str, Any] = {}
+ if include:
+ query_params["include"] = ",".join(include)
+ if params:
+ query_params.update(params)
+ return self.http.get(
+ f"/threads/{thread_id}",
+ headers=headers,
+ params=query_params or None,
+ )
+
+ def create(
+ self,
+ *,
+ metadata: Json = None,
+ thread_id: str | None = None,
+ if_exists: OnConflictBehavior | None = None,
+ supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
+ graph_id: str | None = None,
+ ttl: int | Mapping[str, Any] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Create a new thread.
+
+ Args:
+ metadata: Metadata to add to thread.
+ thread_id: ID of thread.
+ If `None`, ID will be a randomly generated UUID.
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
+ supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
+ Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
+ graph_id: Optional graph ID to associate with the thread.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The created `Thread`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.create(
+ metadata={"number":1},
+ thread_id="my-thread-id",
+ if_exists="raise"
+ )
+ ```
+ )
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if metadata or graph_id:
+ payload["metadata"] = {
+ **(metadata or {}),
+ **({"graph_id": graph_id} if graph_id else {}),
+ }
+ if if_exists:
+ payload["if_exists"] = if_exists
+ if supersteps:
+ payload["supersteps"] = [
+ {
+ "updates": [
+ {
+ "values": u["values"],
+ "command": u.get("command"),
+ "as_node": u["as_node"],
+ }
+ for u in s["updates"]
+ ]
+ }
+ for s in supersteps
+ ]
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+
+ return self.http.post("/threads", json=payload, headers=headers, params=params)
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[False] = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread: ...
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[True],
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None: ...
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None: ...
+
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None:
+ """Update a thread.
+
+ Args:
+ thread_id: ID of thread to update.
+ metadata: Metadata to merge with existing thread metadata.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ return_minimal: If `True`, request a 204 response with no body.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated `Thread`, or `None` when `return_minimal=True`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.update(
+ thread_id="my-thread-id",
+ metadata={"number":1},
+ ttl=43_200,
+ )
+ ```
+ """
+ payload: dict[str, Any] = {"metadata": metadata}
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+ request_headers = dict(headers or {})
+ if return_minimal:
+ request_headers["Prefer"] = "return=minimal"
+ return self.http.patch(
+ f"/threads/{thread_id}",
+ json=payload,
+ headers=request_headers or None,
+ params=params,
+ )
+
+ def delete(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a thread.
+
+ Args:
+ thread_id: The ID of the thread to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client.threads.delete(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ self.http.delete(f"/threads/{thread_id}", headers=headers, params=params)
+
+ def search(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ ids: Sequence[str] | None = None,
+ status: ThreadStatus | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: ThreadSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[ThreadSelectField] | None = None,
+ extract: dict[str, str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Thread]:
+ """Search for threads.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ ids: List of thread IDs to filter by.
+ status: Thread status to filter on.
+ Must be one of 'idle', 'busy', 'interrupted' or 'error'.
+ limit: Limit on number of threads to return.
+ offset: Offset in threads table to start search from.
+ sort_by: Sort by field.
+ sort_order: Sort order.
+ select: List of fields to include in the response.
+ extract: Dictionary mapping aliases to JSONB paths to extract
+ from thread data. Paths use dot notation for nested keys and
+ bracket notation for array indices (e.g.,
+ `{"last_msg": "values.messages[-1]"}`). Extracted values are
+ returned in an `extracted` field on each thread. Maximum 10
+ paths per request.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ List of the threads matching the search parameters.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ threads = client.threads.search(
+ metadata={"number":1},
+ status="interrupted",
+ limit=15,
+ offset=5
+ )
+ ```
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if ids:
+ payload["ids"] = ids
+ if status:
+ payload["status"] = status
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ if extract:
+ payload["extract"] = extract
+ return self.http.post(
+ "/threads/search", json=payload, headers=headers, params=params
+ )
+
+ def count(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ status: ThreadStatus | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count threads matching filters.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ status: Thread status to filter on.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of threads matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if status:
+ payload["status"] = status
+ return self.http.post(
+ "/threads/count", json=payload, headers=headers, params=params
+ )
+
+ def copy(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Copy a thread.
+
+ Args:
+ thread_id: The ID of the thread to copy.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.threads.copy(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ return self.http.post(
+ f"/threads/{thread_id}/copy", json=None, headers=headers, params=params
+ )
+
+ def prune(
+ self,
+ thread_ids: Sequence[str],
+ *,
+ strategy: PruneStrategy = "delete",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict[str, Any]:
+ """Prune threads by ID.
+
+ Args:
+ thread_ids: List of thread IDs to prune.
+ strategy: The prune strategy. `"delete"` removes threads entirely.
+ `"keep_latest"` prunes old checkpoints but keeps threads and their
+ latest state. Defaults to `"delete"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A dict containing `pruned_count` (number of threads pruned).
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ result = client.threads.prune(
+ thread_ids=["thread_1", "thread_2"],
+ )
+ print(result) # {'pruned_count': 2}
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "thread_ids": thread_ids,
+ }
+ if strategy != "delete":
+ payload["strategy"] = strategy
+ return self.http.post(
+ "/threads/prune", json=payload, headers=headers, params=params
+ )
+
+ def get_state(
+ self,
+ thread_id: str,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ *,
+ subgraphs: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadState:
+ """Get the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state of.
+ checkpoint: The checkpoint to get the state of.
+ subgraphs: Include subgraphs states.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The thread of the state.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread_state = client.threads.get_state(
+ thread_id="my_thread_id",
+ checkpoint_id="my_checkpoint_id"
+ )
+ print(thread_state)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'values': {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ },
+ 'next': [],
+ 'checkpoint':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
+ }
+ 'metadata':
+ {
+ 'step': 1,
+ 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
+ 'source': 'loop',
+ 'writes':
+ {
+ 'agent':
+ {
+ 'messages': [
+ {
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'name': None,
+ 'type': 'ai',
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'example': False,
+ 'tool_calls': [],
+ 'usage_metadata': None,
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'invalid_tool_calls': []
+ }
+ ]
+ }
+ },
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'created_by': 'system',
+ 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
+ 'created_at': '2024-07-25T15:35:44.184703+00:00',
+ 'parent_config':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
+ }
+ }
+ ```
+
+ """
+ if checkpoint:
+ return self.http.post(
+ f"/threads/{thread_id}/state/checkpoint",
+ json={"checkpoint": checkpoint, "subgraphs": subgraphs},
+ headers=headers,
+ params=params,
+ )
+ elif checkpoint_id:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return self.http.get(
+ f"/threads/{thread_id}/state/{checkpoint_id}",
+ params=get_params,
+ headers=headers,
+ )
+ else:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return self.http.get(
+ f"/threads/{thread_id}/state",
+ params=get_params,
+ headers=headers,
+ )
+
+ def update_state(
+ self,
+ thread_id: str,
+ values: dict[str, Any] | Sequence[dict] | None,
+ *,
+ as_node: str | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadUpdateStateResponse:
+ """Update the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to update.
+ values: The values to update the state with.
+ as_node: Update the state as if this node had just executed.
+ checkpoint: The checkpoint to update the state of.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ Response after updating a thread's state.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ response = await client.threads.update_state(
+ thread_id="my_thread_id",
+ values={"messages":[{"role": "user", "content": "hello!"}]},
+ as_node="my_node",
+ )
+ print(response)
+
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'checkpoint': {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
+ 'checkpoint_map': {}
+ }
+ }
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "values": values,
+ }
+ if checkpoint_id:
+ payload["checkpoint_id"] = checkpoint_id
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ if as_node:
+ payload["as_node"] = as_node
+ return self.http.post(
+ f"/threads/{thread_id}/state", json=payload, headers=headers, params=params
+ )
+
+ def get_history(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ before: str | Checkpoint | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ checkpoint: Checkpoint | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[ThreadState]:
+ """Get the state history of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state history for.
+ checkpoint: Return states for this subgraph. If empty defaults to root.
+ limit: The maximum number of states to return.
+ before: Return states before this checkpoint.
+ metadata: Filter states by metadata key-value pairs.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The state history of the `Thread`.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ thread_state = client.threads.get_history(
+ thread_id="my_thread_id",
+ limit=5,
+ before="my_timestamp",
+ metadata={"name":"my_name"}
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ }
+ if before:
+ payload["before"] = before
+ if metadata:
+ payload["metadata"] = metadata
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ return self.http.post(
+ f"/threads/{thread_id}/history",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def join_stream(
+ self,
+ thread_id: str,
+ *,
+ stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
+ last_event_id: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Iterator[StreamPart]:
+ """Get a stream of events for a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the stream for.
+ last_event_id: The ID of the last event to get.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ An iterator of stream parts.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ for chunk in client.threads.join_stream(
+ thread_id="my_thread_id",
+ last_event_id="my_event_id",
+ stream_mode="run_modes",
+ ):
+ print(chunk)
+ ```
+
+ """
+ query_params = {
+ "stream_mode": stream_mode,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{thread_id}/stream",
+ "GET",
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ },
+ params=query_params,
+ )
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cfe775ebf07ffdfb7b7b6780112e97a57a44bc2
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93cb9252b2d75f9f408b99586b43ce5e74d30dc7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57432db48e53e4bdbc5bade0f1b94b3e09a0a610
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09040ad6eea255570a4b5ecf339f0c7d80810484
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac12ee8d7c6a8ca3dd3d681a1f0efeeb9c61366d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-313.pyc differ
", "", result) + + return result + + def http_get(self, url: str) -> Dict: + response = requests.get(url, headers=self.headers) + response.raise_for_status() + + return response.json() + + def get_documents(self) -> Iterator[Document]: + user_id = self.get_user_id() + books = self.get_books(user_id) + + for book in books: + book_id = book["id"] + document_ids = self.get_document_ids(book_id) + for document_id in document_ids: + document = self.get_document(book_id, document_id) + parsed_document = self.parse_document(document) + yield parsed_document + + def load(self) -> List[Document]: + """Load documents from `Yuque`.""" + return list(self.get_documents()) diff --git a/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14aa448841e61551f6e2e55468caeb8b52009029 --- /dev/null +++ b/python/user_packages/Python313/site-packages/langchain_community/document_transformers/__init__.py @@ -0,0 +1,95 @@ +"""**Document Transformers** are classes to transform Documents. + +**Document Transformers** usually used to transform a lot of Documents in a single run. + +**Class hierarchy:** + +.. code-block:: + + BaseDocumentTransformer -->
{node_name}
" + if node_name.startswith(tuple(MARKDOWN_SPECIAL_CHARS)) + and node_name.endswith(tuple(MARKDOWN_SPECIAL_CHARS)) + else node_name + ) + if node.metadata: + label = ( + f"{label}" + + "\n".join(f"{k} = {value}" for k, value in node.metadata.items()) + + "" + ) + node_label = format_dict.get(key, format_dict[default_class_label]).format( + _to_safe_id(key), label + ) + return f"{indent}{node_label}\n" + + # Add non-subgraph nodes to the graph + if with_styles: + for key, node in regular_nodes.items(): + mermaid_graph += render_node(key, node) + + # Group edges by their common prefixes + edge_groups: dict[str, list[Edge]] = {} + for edge in edges: + src_parts = edge.source.split(":") + tgt_parts = edge.target.split(":") + common_prefix = ":".join( + src for src, tgt in zip(src_parts, tgt_parts, strict=False) if src == tgt + ) + edge_groups.setdefault(common_prefix, []).append(edge) + + seen_subgraphs = set() + + def add_subgraph(edges: list[Edge], prefix: str) -> None: + nonlocal mermaid_graph + self_loop = len(edges) == 1 and edges[0].source == edges[0].target + if prefix and not self_loop: + subgraph = prefix.rsplit(":", maxsplit=1)[-1] + if subgraph in seen_subgraphs: + msg = ( + f"Found duplicate subgraph '{subgraph}' -- this likely means that " + "you're reusing a subgraph node with the same name. " + "Please adjust your graph to have subgraph nodes with unique names." + ) + raise ValueError(msg) + + seen_subgraphs.add(subgraph) + mermaid_graph += f"\tsubgraph {subgraph}\n" + + # Add nodes that belong to this subgraph + if with_styles and prefix in subgraph_nodes: + for key, node in subgraph_nodes[prefix].items(): + mermaid_graph += render_node(key, node) + + for edge in edges: + source, target = edge.source, edge.target + + # Add BR every wrap_label_n_words words + if edge.data is not None: + edge_data = edge.data + words = str(edge_data).split() # Split the string into words + # Group words into chunks of wrap_label_n_words size + if len(words) > wrap_label_n_words: + edge_data = " 
 ".join( + " ".join(words[i : i + wrap_label_n_words]) + for i in range(0, len(words), wrap_label_n_words) + ) + if edge.conditional: + edge_label = f" -. {edge_data} .-> " + else: + edge_label = f" -- {edge_data} --> " + else: + edge_label = " -.-> " if edge.conditional else " --> " + + mermaid_graph += ( + f"\t{_to_safe_id(source)}{edge_label}{_to_safe_id(target)};\n" + ) + + # Recursively add nested subgraphs + for nested_prefix, edges_ in edge_groups.items(): + if not nested_prefix.startswith(prefix + ":") or nested_prefix == prefix: + continue + # only go to first level subgraphs + if ":" in nested_prefix[len(prefix) + 1 :]: + continue + add_subgraph(edges_, nested_prefix) + + if prefix and not self_loop: + mermaid_graph += "\tend\n" + + # Start with the top-level edges (no common prefix) + add_subgraph(edge_groups.get("", []), "") + + # Add remaining subgraphs with edges + for prefix, edges_ in edge_groups.items(): + if not prefix or ":" in prefix: + continue + add_subgraph(edges_, prefix) + seen_subgraphs.add(prefix) + + # Add empty subgraphs (subgraphs with no internal edges) + if with_styles: + for prefix, subgraph_node in subgraph_nodes.items(): + if ":" not in prefix and prefix not in seen_subgraphs: + mermaid_graph += f"\tsubgraph {prefix}\n" + + # Add nodes that belong to this subgraph + for key, node in subgraph_node.items(): + mermaid_graph += render_node(key, node) + + mermaid_graph += "\tend\n" + seen_subgraphs.add(prefix) + + # Add custom styles for nodes + if with_styles: + mermaid_graph += _generate_mermaid_graph_styles(node_styles or NodeStyles()) + return mermaid_graph + + +def _to_safe_id(label: str) -> str: + """Convert a string into a Mermaid-compatible node id. + + Keep [a-zA-Z0-9_-] characters unchanged. + Map every other character -> backslash + lowercase hex codepoint. + + Result is guaranteed to be unique and Mermaid-compatible, + so nodes with special characters always render correctly. + """ + allowed = string.ascii_letters + string.digits + "_-" + out = [ch if ch in allowed else "\\" + format(ord(ch), "x") for ch in label] + return "".join(out) + + +def _generate_mermaid_graph_styles(node_colors: NodeStyles) -> str: + """Generates Mermaid graph styles for different node types.""" + styles = "" + for class_name, style in asdict(node_colors).items(): + styles += f"\tclassDef {class_name} {style}\n" + return styles + + +def draw_mermaid_png( + mermaid_syntax: str, + output_file_path: str | None = None, + draw_method: MermaidDrawMethod = MermaidDrawMethod.API, + background_color: str | None = "white", + padding: int = 10, + max_retries: int = 1, + retry_delay: float = 1.0, + base_url: str | None = None, + proxies: dict[str, str] | None = None, +) -> bytes: + """Draws a Mermaid graph as PNG using provided syntax. + + Args: + mermaid_syntax: Mermaid graph syntax. + output_file_path: Path to save the PNG image. + draw_method: Method to draw the graph. + background_color: Background color of the image. + padding: Padding around the image. + max_retries: Maximum number of retries (MermaidDrawMethod.API). + retry_delay: Delay between retries (MermaidDrawMethod.API). + base_url: Base URL for the Mermaid.ink API. + proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`). + + Returns: + PNG image bytes. + + Raises: + ValueError: If an invalid draw method is provided. + """ + if draw_method == MermaidDrawMethod.PYPPETEER: + img_bytes = asyncio.run( + _render_mermaid_using_pyppeteer( + mermaid_syntax, output_file_path, background_color, padding + ) + ) + elif draw_method == MermaidDrawMethod.API: + img_bytes = _render_mermaid_using_api( + mermaid_syntax, + output_file_path=output_file_path, + background_color=background_color, + max_retries=max_retries, + retry_delay=retry_delay, + base_url=base_url, + proxies=proxies, + ) + else: + supported_methods = ", ".join([m.value for m in MermaidDrawMethod]) + msg = ( + f"Invalid draw method: {draw_method}. " + f"Supported draw methods are: {supported_methods}" + ) + raise ValueError(msg) + + return img_bytes + + +async def _render_mermaid_using_pyppeteer( + mermaid_syntax: str, + output_file_path: str | None = None, + background_color: str | None = "white", + padding: int = 10, + device_scale_factor: int = 3, +) -> bytes: + """Renders Mermaid graph using Pyppeteer.""" + if not _HAS_PYPPETEER: + msg = "Install Pyppeteer to use the Pyppeteer method: `pip install pyppeteer`." + raise ImportError(msg) + + browser = await launch() + page = await browser.newPage() + + # Setup Mermaid JS + await page.goto("about:blank") + await page.addScriptTag( + {"url": "https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"} + ) + await page.evaluate( + """() => { + mermaid.initialize({startOnLoad:true}); + }""" + ) + + # Render SVG + svg_code = await page.evaluate( + """(mermaidGraph) => { + return mermaid.mermaidAPI.render('mermaid', mermaidGraph); + }""", + mermaid_syntax, + ) + + # Set the page background to white + await page.evaluate( + """(svg, background_color) => { + document.body.innerHTML = svg; + document.body.style.background = background_color; + }""", + svg_code["svg"], + background_color, + ) + + # Take a screenshot + dimensions = await page.evaluate( + """() => { + const svgElement = document.querySelector('svg'); + const rect = svgElement.getBoundingClientRect(); + return { width: rect.width, height: rect.height }; + }""" + ) + await page.setViewport( + { + "width": int(dimensions["width"] + padding), + "height": int(dimensions["height"] + padding), + "deviceScaleFactor": device_scale_factor, + } + ) + + img_bytes = cast("bytes", await page.screenshot({"fullPage": False})) + await browser.close() + + if output_file_path is not None: + await asyncio.get_event_loop().run_in_executor( + None, Path(output_file_path).write_bytes, img_bytes + ) + + return img_bytes + + +def _render_mermaid_using_api( + mermaid_syntax: str, + *, + output_file_path: str | None = None, + background_color: str | None = "white", + file_type: Literal["jpeg", "png", "webp"] | None = "png", + max_retries: int = 1, + retry_delay: float = 1.0, + proxies: dict[str, str] | None = None, + base_url: str | None = None, +) -> bytes: + """Renders Mermaid graph using the Mermaid.INK API.""" + # Automated scanners: please do not open security advisories about `base_url` + # here. This parameter is only ever explicitly controlled by developers, and it + # is not exposed by default over the network by the framework, so this is not + # an SSRF sink unless an application explicitly wires untrusted input into it. + # It exists to support user-managed Mermaid API deployments. + # Defaults to using the public mermaid.ink server. + base_url = base_url if base_url is not None else "https://mermaid.ink" + + if not _HAS_REQUESTS: + msg = ( + "Install the `requests` module to use the Mermaid.INK API: " + "`pip install requests`." + ) + raise ImportError(msg) + + # Use Mermaid API to render the image + mermaid_syntax_encoded = base64.b64encode(mermaid_syntax.encode("utf8")).decode( + "ascii" + ) + + # Check if the background color is a hexadecimal color code using regex + if background_color is not None: + hex_color_pattern = re.compile(r"^#(?:[0-9a-fA-F]{3}){1,2}$") + if not hex_color_pattern.match(background_color): + background_color = f"!{background_color}" + + # URL-encode the background_color to handle special characters like '!' + encoded_bg_color = urllib.parse.quote(str(background_color), safe="") + image_url = ( + f"{base_url}/img/{mermaid_syntax_encoded}" + f"?type={file_type}&bgColor={encoded_bg_color}" + ) + + error_msg_suffix = ( + "To resolve this issue:\n" + "1. Check your internet connection and try again\n" + "2. Try with higher retry settings: " + "`draw_mermaid_png(..., max_retries=5, retry_delay=2.0)`\n" + "3. Use the Pyppeteer rendering method which will render your graph locally " + "in a browser: `draw_mermaid_png(..., draw_method=MermaidDrawMethod.PYPPETEER)`" + ) + + for attempt in range(max_retries + 1): + try: + response = requests.get(image_url, timeout=10, proxies=proxies) + if response.status_code == requests.codes.ok: + img_bytes = response.content + if output_file_path is not None: + Path(output_file_path).write_bytes(response.content) + + return img_bytes + + # If we get a server error (5xx), retry + if ( + requests.codes.internal_server_error <= response.status_code + and attempt < max_retries + ): + # Exponential backoff with jitter + sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto + time.sleep(sleep_time) + continue + + # For other status codes, fail immediately + msg = ( + f"Failed to reach {base_url} API while trying to render " + f"your graph. Status code: {response.status_code}.\n\n" + ) + error_msg_suffix + raise ValueError(msg) + + except (requests.RequestException, requests.Timeout) as e: + if attempt < max_retries: + # Exponential backoff with jitter + sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto + time.sleep(sleep_time) + else: + msg = ( + f"Failed to reach {base_url} API while trying to render " + f"your graph after {max_retries} retries. " + ) + error_msg_suffix + raise ValueError(msg) from e + + # This should not be reached, but just in case + msg = ( + f"Failed to reach {base_url} API while trying to render " + f"your graph after {max_retries} retries. " + ) + error_msg_suffix + raise ValueError(msg) diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py new file mode 100644 index 0000000000000000000000000000000000000000..97b6b1f21f2b5f4ab33d216e2084556aadec7b82 --- /dev/null +++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/graph_png.py @@ -0,0 +1,215 @@ +"""Helper class to draw a state graph into a PNG file.""" + +from itertools import groupby +from typing import Any, cast + +from langchain_core.runnables.graph import Graph, LabelsDict + +try: + import pygraphviz as pgv # type: ignore[import-not-found] + + _HAS_PYGRAPHVIZ = True +except ImportError: + _HAS_PYGRAPHVIZ = False + + +class PngDrawer: + """Helper class to draw a state graph into a PNG file. + + It requires `graphviz` and `pygraphviz` to be installed. + + Example: + ```python + drawer = PngDrawer() + drawer.draw(state_graph, "graph.png") + ``` + """ + + def __init__( + self, fontname: str | None = None, labels: LabelsDict | None = None + ) -> None: + """Initializes the PNG drawer. + + Args: + fontname: The font to use for the labels. Defaults to "arial". + labels: A dictionary of label overrides. The dictionary + should have the following format: + { + "nodes": { + "node1": "CustomLabel1", + "node2": "CustomLabel2", + "__end__": "End Node" + }, + "edges": { + "continue": "ContinueLabel", + "end": "EndLabel" + } + } + The keys are the original labels, and the values are the new labels. + + """ + self.fontname = fontname or "arial" + self.labels = labels or LabelsDict(nodes={}, edges={}) + + def get_node_label(self, label: str) -> str: + """Returns the label to use for a node. + + Args: + label: The original label. + + Returns: + The new label. + """ + label = self.labels.get("nodes", {}).get(label, label) + return f"<{label}>" + + def get_edge_label(self, label: str) -> str: + """Returns the label to use for an edge. + + Args: + label: The original label. + + Returns: + The new label. + """ + label = self.labels.get("edges", {}).get(label, label) + return f"<{label}>" + + def add_node(self, viz: Any, node: str) -> None: + """Adds a node to the graph. + + Args: + viz: The graphviz object. + node: The node to add. + """ + viz.add_node( + node, + label=self.get_node_label(node), + style="filled", + fillcolor="yellow", + fontsize=15, + fontname=self.fontname, + ) + + def add_edge( + self, + viz: Any, + source: str, + target: str, + label: str | None = None, + conditional: bool = False, # noqa: FBT001,FBT002 + ) -> None: + """Adds an edge to the graph. + + Args: + viz: The graphviz object. + source: The source node. + target: The target node. + label: The label for the edge. + conditional: Whether the edge is conditional. + """ + viz.add_edge( + source, + target, + label=self.get_edge_label(label) if label else "", + fontsize=12, + fontname=self.fontname, + style="dotted" if conditional else "solid", + ) + + def draw(self, graph: Graph, output_path: str | None = None) -> bytes | None: + """Draw the given state graph into a PNG file. + + Requires `graphviz` and `pygraphviz` to be installed. + + Args: + graph: The graph to draw + output_path: The path to save the PNG. If `None`, PNG bytes are returned. + + Raises: + ImportError: If `pygraphviz` is not installed. + + Returns: + The PNG bytes if `output_path` is None, else None. + """ + if not _HAS_PYGRAPHVIZ: + msg = "Install pygraphviz to draw graphs: `pip install pygraphviz`." + raise ImportError(msg) + + # Create a directed graph + viz = pgv.AGraph(directed=True, nodesep=0.9, ranksep=1.0) + + # Add nodes, conditional edges, and edges to the graph + self.add_nodes(viz, graph) + self.add_edges(viz, graph) + self.add_subgraph(viz, [node.split(":") for node in graph.nodes]) + + # Update entrypoint and END styles + self.update_styles(viz, graph) + + # Save the graph as PNG + try: + return cast("bytes | None", viz.draw(output_path, format="png", prog="dot")) + finally: + viz.close() + + def add_nodes(self, viz: Any, graph: Graph) -> None: + """Add nodes to the graph. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ + for node in graph.nodes: + self.add_node(viz, node) + + def add_subgraph( + self, + viz: Any, + nodes: list[list[str]], + parent_prefix: list[str] | None = None, + ) -> None: + """Add subgraphs to the graph. + + Args: + viz: The graphviz object. + nodes: The nodes to add. + parent_prefix: The prefix of the parent subgraph. + """ + for prefix, grouped in groupby( + [node[:] for node in sorted(nodes)], + key=lambda x: x.pop(0), + ): + current_prefix = (parent_prefix or []) + [prefix] + grouped_nodes = list(grouped) + if len(grouped_nodes) > 1: + subgraph = viz.add_subgraph( + [":".join(current_prefix + node) for node in grouped_nodes], + name="cluster_" + ":".join(current_prefix), + ) + self.add_subgraph(subgraph, grouped_nodes, current_prefix) + + def add_edges(self, viz: Any, graph: Graph) -> None: + """Add edges to the graph. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ + for start, end, data, cond in graph.edges: + self.add_edge( + viz, start, end, str(data) if data is not None else None, cond + ) + + @staticmethod + def update_styles(viz: Any, graph: Graph) -> None: + """Update the styles of the entrypoint and END nodes. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ + if first := graph.first_node(): + viz.get_node(first.id).attr.update(fillcolor="lightblue") + if last := graph.last_node(): + viz.get_node(last.id).attr.update(fillcolor="orange") diff --git a/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py b/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py new file mode 100644 index 0000000000000000000000000000000000000000..c85386735cd202b02ac0b503a414a2ecbb72960b --- /dev/null +++ b/python/user_packages/Python313/site-packages/langchain_core/runnables/history.py @@ -0,0 +1,631 @@ +"""`Runnable` that manages chat message history for another `Runnable`.""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Sequence +from types import GenericAlias +from typing import ( + TYPE_CHECKING, + Any, +) + +from pydantic import BaseModel +from typing_extensions import override + +from langchain_core._api.deprecation import warn_deprecated +from langchain_core.chat_history import BaseChatMessageHistory +from langchain_core.load.load import load +from langchain_core.messages import AIMessage, BaseMessage, HumanMessage +from langchain_core.runnables.base import Runnable, RunnableBindingBase, RunnableLambda +from langchain_core.runnables.passthrough import RunnablePassthrough +from langchain_core.runnables.utils import ( + ConfigurableFieldSpec, + Output, + get_unique_config_specs, +) +from langchain_core.utils.pydantic import create_model_v2 + +if TYPE_CHECKING: + from langchain_core.language_models.base import LanguageModelLike + from langchain_core.runnables.config import RunnableConfig + from langchain_core.tracers.schemas import Run + + +MessagesOrDictWithMessages = Sequence["BaseMessage"] | dict[str, Any] +GetSessionHistoryCallable = Callable[..., BaseChatMessageHistory] + + +class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef] + """`Runnable` that manages chat message history for another `Runnable`. + + A chat message history is a sequence of messages that represent a conversation. + + `RunnableWithMessageHistory` wraps another `Runnable` and manages the chat message + history for it; it is responsible for reading and updating the chat message + history. + + The formats supported for the inputs and outputs of the wrapped `Runnable` + are described below. + + `RunnableWithMessageHistory` must always be called with a config that contains + the appropriate parameters for the chat message history factory. + + By default, the `Runnable` is expected to take a single configuration parameter + called `session_id` which is a string. This parameter is used to create a new + or look up an existing chat message history that matches the given `session_id`. + + In this case, the invocation would look like this: + + `with_history.invoke(..., config={"configurable": {"session_id": "bar"}})` + ; e.g., `{"configurable": {"session_id": "