Skip to content

The agent engineering platform.

chore(langchain_v1): further namespace clean up (#33428)

Eugene Yurtsevc2205f88e62d
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index 9f68d1087e..e009b2e3ab 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -44,8 +44,7 @@ from langchain.agents.structured_output import (
ToolStrategy,
)
from langchain.chat_models import init_chat_model
-from langchain.tools import ToolNode
-from langchain.tools.tool_node import ToolCallWithContext
+from langchain.tools.tool_node import ToolCallWithContext, _ToolNode
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Sequence
@@ -670,7 +669,7 @@ def create_agent( # noqa: PLR0915
awrap_tool_call_wrapper = _chain_async_tool_call_wrappers(async_wrappers)
# Setup tools
- tool_node: ToolNode | None = None
+ tool_node: _ToolNode | None = None
# Extract built-in provider tools (dict format) and regular tools (BaseTool/callables)
built_in_tools = [t for t in tools if isinstance(t, dict)]
regular_tools = [t for t in tools if not isinstance(t, dict)]
@@ -680,7 +679,7 @@ def create_agent( # noqa: PLR0915
# Only create ToolNode if we have client-side tools
tool_node = (
- ToolNode(
+ _ToolNode(
tools=available_tools,
wrap_tool_call=wrap_tool_call_wrapper,
awrap_tool_call=awrap_tool_call_wrapper,
@@ -1464,7 +1463,7 @@ def _make_model_to_model_edge(
def _make_tools_to_model_edge(
*,
- tool_node: ToolNode,
+ tool_node: _ToolNode,
model_destination: str,
structured_output_tools: dict[str, OutputToolBinding],
end_destination: str,
diff --git a/libs/langchain_v1/langchain/documents/__init__.py b/libs/langchain_v1/langchain/documents/__init__.py
deleted file mode 100644
index dcc14ce68b..0000000000
--- a/libs/langchain_v1/langchain/documents/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""Document."""
-
-from langchain_core.documents import Document
-
-__all__ = [
- "Document",
-]
diff --git a/libs/langchain_v1/langchain/embeddings/__init__.py b/libs/langchain_v1/langchain/embeddings/__init__.py
index 84c453a9f6..b75c7a307c 100644
--- a/libs/langchain_v1/langchain/embeddings/__init__.py
+++ b/libs/langchain_v1/langchain/embeddings/__init__.py
@@ -3,10 +3,8 @@
from langchain_core.embeddings import Embeddings
from langchain.embeddings.base import init_embeddings
-from langchain.embeddings.cache import CacheBackedEmbeddings
__all__ = [
- "CacheBackedEmbeddings",
"Embeddings",
"init_embeddings",
]
diff --git a/libs/langchain_v1/langchain/embeddings/cache.py b/libs/langchain_v1/langchain/embeddings/cache.py
deleted file mode 100644
index 3096d340cf..0000000000
--- a/libs/langchain_v1/langchain/embeddings/cache.py
+++ /dev/null
@@ -1,361 +0,0 @@
-"""Module contains code for a cache backed embedder.
-
-The cache backed embedder is a wrapper around an embedder that caches
-embeddings in a key-value store. The cache is used to avoid recomputing
-embeddings for the same text.
-
-The text is hashed and the hash is used as the key in the cache.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import uuid
-import warnings
-from typing import TYPE_CHECKING, Literal, cast
-
-from langchain_core.embeddings import Embeddings
-from langchain_core.utils.iter import batch_iterate
-
-from langchain.storage.encoder_backed import EncoderBackedStore
-
-if TYPE_CHECKING:
- from collections.abc import Callable, Sequence
-
- from langchain_core.stores import BaseStore, ByteStore
-
-NAMESPACE_UUID = uuid.UUID(int=1985)
-
-
-def _sha1_hash_to_uuid(text: str) -> uuid.UUID:
- """Return a UUID derived from *text* using SHA-1 (deterministic).
-
- Deterministic and fast, **but not collision-resistant**.
-
- A malicious attacker could try to create two different texts that hash to the same
- UUID. This may not necessarily be an issue in the context of caching embeddings,
- but new applications should swap this out for a stronger hash function like
- xxHash, BLAKE2 or SHA-256, which are collision-resistant.
- """
- sha1_hex = hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()
- # Embed the hex string in `uuid5` to obtain a valid UUID.
- return uuid.uuid5(NAMESPACE_UUID, sha1_hex)
-
-
-def _make_default_key_encoder(namespace: str, algorithm: str) -> Callable[[str], str]:
- """Create a default key encoder function.
-
- Args:
- namespace: Prefix that segregates keys from different embedding models.
- algorithm:
- * `'sha1'` - fast but not collision-resistant
- * `'blake2b'` - cryptographically strong, faster than SHA-1
- * `'sha256'` - cryptographically strong, slower than SHA-1
- * `'sha512'` - cryptographically strong, slower than SHA-1
-
- Returns:
- A function that encodes a key using the specified algorithm.
- """
- if algorithm == "sha1":
- _warn_about_sha1_encoder()
-
- def _key_encoder(key: str) -> str:
- """Encode a key using the specified algorithm."""
- if algorithm == "sha1":
- return f"{namespace}{_sha1_hash_to_uuid(key)}"
- if algorithm == "blake2b":
- return f"{namespace}{hashlib.blake2b(key.encode('utf-8')).hexdigest()}"
- if algorithm == "sha256":
- return f"{namespace}{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
- if algorithm == "sha512":
- return f"{namespace}{hashlib.sha512(key.encode('utf-8')).hexdigest()}"
- msg = f"Unsupported algorithm: {algorithm}"
- raise ValueError(msg)
-
- return _key_encoder
-
-
-def _value_serializer(value: Sequence[float]) -> bytes:
- """Serialize a value."""
- return json.dumps(value).encode()
-
-
-def _value_deserializer(serialized_value: bytes) -> list[float]:
- """Deserialize a value."""
- return cast("list[float]", json.loads(serialized_value.decode()))
-
-
-# The warning is global; track emission, so it appears only once.
-_warned_about_sha1: bool = False
-
-
-def _warn_about_sha1_encoder() -> None:
- """Emit a one-time warning about SHA-1 collision weaknesses."""
- global _warned_about_sha1 # noqa: PLW0603
- if not _warned_about_sha1:
- warnings.warn(
- "Using default key encoder: SHA-1 is *not* collision-resistant. "
- "While acceptable for most cache scenarios, a motivated attacker "
- "can craft two different payloads that map to the same cache key. "
- "If that risk matters in your environment, supply a stronger "
- "encoder (e.g. SHA-256 or BLAKE2) via the `key_encoder` argument. "
- "If you change the key encoder, consider also creating a new cache, "
- "to avoid (the potential for) collisions with existing keys.",
- category=UserWarning,
- stacklevel=2,
- )
- _warned_about_sha1 = True
-
-
-class CacheBackedEmbeddings(Embeddings):
- """Interface for caching results from embedding models.
-
- The interface allows works with any store that implements
- the abstract store interface accepting keys of type str and values of list of
- floats.
-
- If need be, the interface can be extended to accept other implementations
- of the value serializer and deserializer, as well as the key encoder.
-
- Note that by default only document embeddings are cached. To cache query
- embeddings too, pass in a query_embedding_store to constructor.
-
- Examples:
- ```python
- from langchain.embeddings import CacheBackedEmbeddings
- from langchain.storage import LocalFileStore
- from langchain_community.embeddings import OpenAIEmbeddings
-
- store = LocalFileStore("./my_cache")
-
- underlying_embedder = OpenAIEmbeddings()
- embedder = CacheBackedEmbeddings.from_bytes_store(
- underlying_embedder, store, namespace=underlying_embedder.model
- )
-
- # Embedding is computed and cached
- embeddings = embedder.embed_documents(["hello", "goodbye"])
-
- # Embeddings are retrieved from the cache, no computation is done
- embeddings = embedder.embed_documents(["hello", "goodbye"])
- ```
- """
-
- def __init__(
- self,
- underlying_embeddings: Embeddings,
- document_embedding_store: BaseStore[str, list[float]],
- *,
- batch_size: int | None = None,
- query_embedding_store: BaseStore[str, list[float]] | None = None,
- ) -> None:
- """Initialize the embedder.
-
- Args:
- underlying_embeddings: the embedder to use for computing embeddings.
- document_embedding_store: The store to use for caching document embeddings.
- batch_size: The number of documents to embed between store updates.
- query_embedding_store: The store to use for caching query embeddings.
- If `None`, query embeddings are not cached.
- """
- super().__init__()
- self.document_embedding_store = document_embedding_store
- self.query_embedding_store = query_embedding_store
- self.underlying_embeddings = underlying_embeddings
- self.batch_size = batch_size
-
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
- """Embed a list of texts.
-
- The method first checks the cache for the embeddings.
- If the embeddings are not found, the method uses the underlying embedder
- to embed the documents and stores the results in the cache.
-
- Args:
- texts: A list of texts to embed.
-
- Returns:
- A list of embeddings for the given texts.
- """
- vectors: list[list[float] | None] = self.document_embedding_store.mget(
- texts,
- )
- all_missing_indices: list[int] = [i for i, vector in enumerate(vectors) if vector is None]
-
- for missing_indices in batch_iterate(self.batch_size, all_missing_indices):
- missing_texts = [texts[i] for i in missing_indices]
- missing_vectors = self.underlying_embeddings.embed_documents(missing_texts)
- self.document_embedding_store.mset(
- list(zip(missing_texts, missing_vectors, strict=False)),
- )
- for index, updated_vector in zip(missing_indices, missing_vectors, strict=False):
- vectors[index] = updated_vector
-
- return cast(
- "list[list[float]]",
- vectors,
- ) # Nones should have been resolved by now
-
- async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
- """Embed a list of texts.
-
- The method first checks the cache for the embeddings.
- If the embeddings are not found, the method uses the underlying embedder
- to embed the documents and stores the results in the cache.
-
- Args:
- texts: A list of texts to embed.
-
- Returns:
- A list of embeddings for the given texts.
- """
- vectors: list[list[float] | None] = await self.document_embedding_store.amget(texts)
- all_missing_indices: list[int] = [i for i, vector in enumerate(vectors) if vector is None]
-
- # batch_iterate supports None batch_size which returns all elements at once
- # as a single batch.
- for missing_indices in batch_iterate(self.batch_size, all_missing_indices):
- missing_texts = [texts[i] for i in missing_indices]
- missing_vectors = await self.underlying_embeddings.aembed_documents(
- missing_texts,
- )
- await self.document_embedding_store.amset(
- list(zip(missing_texts, missing_vectors, strict=False)),
- )
- for index, updated_vector in zip(missing_indices, missing_vectors, strict=False):
- vectors[index] = updated_vector
-
- return cast(
- "list[list[float]]",
- vectors,
- ) # Nones should have been resolved by now
-
- def embed_query(self, text: str) -> list[float]:
- """Embed query text.
-
- By default, this method does not cache queries. To enable caching, set the
- `cache_query` parameter to `True` when initializing the embedder.
-
- Args:
- text: The text to embed.
-
- Returns:
- The embedding for the given text.
- """
- if not self.query_embedding_store:
- return self.underlying_embeddings.embed_query(text)
-
- (cached,) = self.query_embedding_store.mget([text])
- if cached is not None:
- return cached
-
- vector = self.underlying_embeddings.embed_query(text)
- self.query_embedding_store.mset([(text, vector)])
- return vector
-
- async def aembed_query(self, text: str) -> list[float]:
- """Embed query text.
-
- By default, this method does not cache queries. To enable caching, set the
- `cache_query` parameter to `True` when initializing the embedder.
-
- Args:
- text: The text to embed.
-
- Returns:
- The embedding for the given text.
- """
- if not self.query_embedding_store:
- return await self.underlying_embeddings.aembed_query(text)
-
- (cached,) = await self.query_embedding_store.amget([text])
- if cached is not None:
- return cached
-
- vector = await self.underlying_embeddings.aembed_query(text)
- await self.query_embedding_store.amset([(text, vector)])
- return vector
-
- @classmethod
- def from_bytes_store(
- cls,
- underlying_embeddings: Embeddings,
- document_embedding_cache: ByteStore,
- *,
- namespace: str = "",
- batch_size: int | None = None,
- query_embedding_cache: bool | ByteStore = False,
- key_encoder: Callable[[str], str] | Literal["sha1", "blake2b", "sha256", "sha512"] = "sha1",
- ) -> CacheBackedEmbeddings:
- """On-ramp that adds the necessary serialization and encoding to the store.
-
- Args:
- underlying_embeddings: The embedder to use for embedding.
- document_embedding_cache: The cache to use for storing document embeddings.
- namespace: The namespace to use for document cache.
- This namespace is used to avoid collisions with other caches.
- For example, set it to the name of the embedding model used.
- batch_size: The number of documents to embed between store updates.
- query_embedding_cache: The cache to use for storing query embeddings.
- True to use the same cache as document embeddings.
- False to not cache query embeddings.
- key_encoder: Optional callable to encode keys. 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.
-
- If you change a key encoder in an existing cache, consider
- just creating a new cache, to avoid (the potential for)
- collisions with existing keys or having duplicate keys
- for the same text in the cache.
-
- Returns:
- An instance of CacheBackedEmbeddings that uses the provided cache.
- """
- if isinstance(key_encoder, str):
- key_encoder = _make_default_key_encoder(namespace, key_encoder)
- elif callable(key_encoder):
- # If a custom key encoder is provided, it should not be used with a
- # namespace.
- # A user can handle namespacing in directly their custom key encoder.
- if namespace:
- msg = (
- "Do not supply `namespace` when using a custom key_encoder; "
- "add any prefixing inside the encoder itself."
- )
- raise ValueError(msg)
- else:
- msg = (
- "key_encoder must be either 'blake2b', 'sha1', 'sha256', 'sha512' "
- "or a callable that encodes keys."
- )
- raise ValueError(msg) # noqa: TRY004
-
- document_embedding_store = EncoderBackedStore[str, list[float]](
- document_embedding_cache,
- key_encoder,
- _value_serializer,
- _value_deserializer,
- )
- if query_embedding_cache is True:
- query_embedding_store = document_embedding_store
- elif query_embedding_cache is False:
- query_embedding_store = None
- else:
- query_embedding_store = EncoderBackedStore[str, list[float]](
- query_embedding_cache,
- key_encoder,
- _value_serializer,
- _value_deserializer,
- )
-
- return cls(
- underlying_embeddings,
- document_embedding_store,
- batch_size=batch_size,
- query_embedding_store=query_embedding_store,
- )
diff --git a/libs/langchain_v1/langchain/storage/__init__.py b/libs/langchain_v1/langchain/storage/__init__.py
deleted file mode 100644
index 74680e1db9..0000000000
--- a/libs/langchain_v1/langchain/storage/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""Implementations of key-value stores and storage helpers.
-
-Module provides implementations of various key-value stores that conform
-to a simple key-value interface.
-
-The primary goal of these storages is to support implementation of caching.
-"""
-
-from langchain_core.stores import (
- InMemoryByteStore,
- InMemoryStore,
- InvalidKeyException,
-)
-
-from langchain.storage.encoder_backed import EncoderBackedStore
-
-__all__ = [
- "EncoderBackedStore",
- "InMemoryByteStore",
- "InMemoryStore",
- "InvalidKeyException",
-]
diff --git a/libs/langchain_v1/langchain/storage/encoder_backed.py b/libs/langchain_v1/langchain/storage/encoder_backed.py
deleted file mode 100644
index 80e60c32a5..0000000000
--- a/libs/langchain_v1/langchain/storage/encoder_backed.py
+++ /dev/null
@@ -1,122 +0,0 @@
-"""Encoder-backed store implementation."""
-
-from collections.abc import AsyncIterator, Callable, Iterator, Sequence
-from typing import (
- Any,
- TypeVar,
-)
-
-from langchain_core.stores import BaseStore
-
-K = TypeVar("K")
-V = TypeVar("V")
-
-
-class EncoderBackedStore(BaseStore[K, V]):
- """Wraps a store with key and value encoders/decoders.
-
- Examples that uses JSON for encoding/decoding:
-
- ```python
- import json
-
-
- def key_encoder(key: int) -> str:
- return json.dumps(key)
-
-
- def value_serializer(value: float) -> str:
- return json.dumps(value)
-
-
- def value_deserializer(serialized_value: str) -> float:
- return json.loads(serialized_value)
-
-
- # Create an instance of the abstract store
- abstract_store = MyCustomStore()
-
- # Create an instance of the encoder-backed store
- store = EncoderBackedStore(
- store=abstract_store,
- key_encoder=key_encoder,
- value_serializer=value_serializer,
- value_deserializer=value_deserializer,
- )
-
- # Use the encoder-backed store methods
- store.mset([(1, 3.14), (2, 2.718)])
- values = store.mget([1, 2]) # Retrieves [3.14, 2.718]
- store.mdelete([1, 2]) # Deletes the keys 1 and 2
- ```
- """
-
- def __init__(
- self,
- store: BaseStore[str, Any],
- key_encoder: Callable[[K], str],
- value_serializer: Callable[[V], bytes],
- value_deserializer: Callable[[Any], V],
- ) -> None:
- """Initialize an EncodedStore."""
- self.store = store
- self.key_encoder = key_encoder
- self.value_serializer = value_serializer
- self.value_deserializer = value_deserializer
-
- def mget(self, keys: Sequence[K]) -> list[V | None]:
- """Get the values associated with the given keys."""
- encoded_keys: list[str] = [self.key_encoder(key) for key in keys]
- values = self.store.mget(encoded_keys)
- return [self.value_deserializer(value) if value is not None else value for value in values]
-
- async def amget(self, keys: Sequence[K]) -> list[V | None]:
- """Get the values associated with the given keys."""
- encoded_keys: list[str] = [self.key_encoder(key) for key in keys]
- values = await self.store.amget(encoded_keys)
- return [self.value_deserializer(value) if value is not None else value for value in values]
-
- def mset(self, key_value_pairs: Sequence[tuple[K, V]]) -> None:
- """Set the values for the given keys."""
- encoded_pairs = [
- (self.key_encoder(key), self.value_serializer(value)) for key, value in key_value_pairs
- ]
- self.store.mset(encoded_pairs)
-
- async def amset(self, key_value_pairs: Sequence[tuple[K, V]]) -> None:
- """Set the values for the given keys."""
- encoded_pairs = [
- (self.key_encoder(key), self.value_serializer(value)) for key, value in key_value_pairs
- ]
- await self.store.amset(encoded_pairs)
-
- def mdelete(self, keys: Sequence[K]) -> None:
- """Delete the given keys and their associated values."""
- encoded_keys = [self.key_encoder(key) for key in keys]
- self.store.mdelete(encoded_keys)
-
- async def amdelete(self, keys: Sequence[K]) -> None:
- """Delete the given keys and their associated values."""
- encoded_keys = [self.key_encoder(key) for key in keys]
- await self.store.amdelete(encoded_keys)
-
- def yield_keys(
- self,
- *,
- prefix: str | None = None,
- ) -> Iterator[K] | Iterator[str]:
- """Get an iterator over keys that match the given prefix."""
- # For the time being this does not return K, but str
- # it's for debugging purposes. Should fix this.
- yield from self.store.yield_keys(prefix=prefix)
-
- async def ayield_keys(
- self,
- *,
- prefix: str | None = None,
- ) -> AsyncIterator[K] | AsyncIterator[str]:
- """Get an iterator over keys that match the given prefix."""
- # For the time being this does not return K, but str
- # it's for debugging purposes. Should fix this.
- async for key in self.store.ayield_keys(prefix=prefix):
- yield key
diff --git a/libs/langchain_v1/langchain/storage/exceptions.py b/libs/langchain_v1/langchain/storage/exceptions.py
deleted file mode 100644
index 74d2a43c53..0000000000
--- a/libs/langchain_v1/langchain/storage/exceptions.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Store exceptions."""
-
-from langchain_core.stores import InvalidKeyException
-
-__all__ = ["InvalidKeyException"]
diff --git a/libs/langchain_v1/langchain/storage/in_memory.py b/libs/langchain_v1/langchain/storage/in_memory.py
deleted file mode 100644
index 296bc19a02..0000000000
--- a/libs/langchain_v1/langchain/storage/in_memory.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""In memory store that is not thread safe and has no eviction policy.
-
-This is a simple implementation of the BaseStore using a dictionary that is useful
-primarily for unit testing purposes.
-"""
-
-from langchain_core.stores import InMemoryBaseStore, InMemoryByteStore, InMemoryStore
-
-__all__ = [
- "InMemoryBaseStore",
- "InMemoryByteStore",
- "InMemoryStore",
-]
diff --git a/libs/langchain_v1/langchain/tools/__init__.py b/libs/langchain_v1/langchain/tools/__init__.py
index e413550dbe..6d74894c31 100644
--- a/libs/langchain_v1/langchain/tools/__init__.py
+++ b/libs/langchain_v1/langchain/tools/__init__.py
@@ -8,7 +8,7 @@ from langchain_core.tools import (
tool,
)
-from langchain.tools.tool_node import InjectedState, InjectedStore, ToolInvocationError, ToolNode
+from langchain.tools.tool_node import InjectedState, InjectedStore, ToolInvocationError
__all__ = [
"BaseTool",
@@ -18,6 +18,5 @@ __all__ = [
"InjectedToolCallId",
"ToolException",
"ToolInvocationError",
- "ToolNode",
"tool",
]
diff --git a/libs/langchain_v1/langchain/tools/tool_node.py b/libs/langchain_v1/langchain/tools/tool_node.py
index 8066a22f08..e5d06f99f1 100644
--- a/libs/langchain_v1/langchain/tools/tool_node.py
+++ b/libs/langchain_v1/langchain/tools/tool_node.py
@@ -392,7 +392,7 @@ def _infer_handled_types(handler: Callable[..., str]) -> tuple[type[Exception],
return (Exception,)
-class ToolNode(RunnableCallable):
+class _ToolNode(RunnableCallable):
"""A node for executing tools in LangGraph workflows.
Handles tool execution patterns including function calls, state injection,
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py
index b9a9336a3d..01edf609b0 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py
@@ -1,15 +1,15 @@
"""Test Middleware handling of tools in agents."""
-import pytest
from collections.abc import Callable
-from langchain.agents.middleware.types import AgentMiddleware, AgentState, ModelRequest
+import pytest
+
from langchain.agents.factory import create_agent
-from langchain.tools import ToolNode
+from langchain.agents.middleware.types import AgentMiddleware, AgentState, ModelRequest
+from langchain.tools.tool_node import _ToolNode
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.tools import tool
from .model import FakeToolCallingModel
-from langgraph.runtime import Runtime
def test_model_request_tools_are_base_tools() -> None:
@@ -105,7 +105,6 @@ def test_middleware_can_modify_tools() -> None:
def test_unknown_tool_raises_error() -> None:
"""Test that using an unknown tool in ModelRequest raises a clear error."""
- from langchain_core.tools import BaseTool
@tool
def known_tool(input: str) -> str:
@@ -327,9 +326,9 @@ def test_tool_node_not_accepted() -> None:
"""Some tool."""
return "result"
- tool_node = ToolNode([some_tool])
+ tool_node = _ToolNode([some_tool])
- with pytest.raises(TypeError, match="'ToolNode' object is not iterable"):
+ with pytest.raises(TypeError, match="'_ToolNode' object is not iterable"):
create_agent(
model=FakeToolCallingModel(),
tools=tool_node, # type: ignore[arg-type]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py b/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py
index 65439b2888..71da2d0157 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py
@@ -33,10 +33,10 @@ from pydantic.v1 import BaseModel as BaseModelV1
from typing_extensions import TypedDict
from langchain.tools import (
- ToolNode,
InjectedState,
InjectedStore,
)
+from langchain.tools.tool_node import _ToolNode
from langchain.tools.tool_node import TOOL_CALL_ERROR_TEMPLATE, ToolInvocationError, tools_condition
from .messages import _AnyIdHumanMessage, _AnyIdToolMessage
@@ -88,7 +88,7 @@ tool5.handle_tool_error = "foo"
async def test_tool_node() -> None:
"""Test tool node."""
- result = ToolNode([tool1]).invoke(
+ result = _ToolNode([tool1]).invoke(
{
"messages": [
AIMessage(
@@ -110,7 +110,7 @@ async def test_tool_node() -> None:
assert tool_message.content == "1 - foo"
assert tool_message.tool_call_id == "some 0"
- result2 = await ToolNode([tool2]).ainvoke(
+ result2 = await _ToolNode([tool2]).ainvoke(
{
"messages": [
AIMessage(
@@ -132,7 +132,7 @@ async def test_tool_node() -> None:
assert tool_message.content == "tool2: 2 - bar"
# list of dicts tool content
- result3 = await ToolNode([tool3]).ainvoke(
+ result3 = await _ToolNode([tool3]).ainvoke(
{
"messages": [
AIMessage(
@@ -156,7 +156,7 @@ async def test_tool_node() -> None:
assert tool_message.tool_call_id == "some 2"
# list of content blocks tool content
- result4 = await ToolNode([tool4]).ainvoke(
+ result4 = await _ToolNode([tool4]).ainvoke(
{
"messages": [
AIMessage(
@@ -186,7 +186,7 @@ async def test_tool_node_tool_call_input() -> None:
"id": "some 0",
"type": "tool_call",
}
- result = ToolNode([tool1]).invoke([tool_call_1])
+ result = _ToolNode([tool1]).invoke([tool_call_1])
assert result["messages"] == [
ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),
]
@@ -198,7 +198,7 @@ async def test_tool_node_tool_call_input() -> None:
"id": "some 1",
"type": "tool_call",
}
- result = ToolNode([tool1]).invoke([tool_call_1, tool_call_2])
+ result = _ToolNode([tool1]).invoke([tool_call_1, tool_call_2])
assert result["messages"] == [
ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),
ToolMessage(content="2 - bar", tool_call_id="some 1", name="tool1"),
@@ -207,7 +207,7 @@ async def test_tool_node_tool_call_input() -> None:
# Test with unknown tool
tool_call_3 = tool_call_1.copy()
tool_call_3["name"] = "tool2"
- result = ToolNode([tool1]).invoke([tool_call_1, tool_call_3])
+ result = _ToolNode([tool1]).invoke([tool_call_1, tool_call_3])
assert result["messages"] == [
ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),
ToolMessage(
@@ -220,7 +220,7 @@ async def test_tool_node_tool_call_input() -> None:
def test_tool_node_error_handling_default_invocation() -> None:
- tn = ToolNode([tool1])
+ tn = _ToolNode([tool1])
result = tn.invoke(
{
"messages": [
@@ -247,7 +247,7 @@ def test_tool_node_error_handling_default_invocation() -> None:
def test_tool_node_error_handling_default_exception() -> None:
- tn = ToolNode([tool1])
+ tn = _ToolNode([tool1])
with pytest.raises(ValueError):
tn.invoke(
{
@@ -280,7 +280,7 @@ async def test_tool_node_error_handling() -> None:
(ValueError, ToolException, ToolInvocationError),
handle_all,
):
- result_error = await ToolNode(
+ result_error = await _ToolNode(
[tool1, tool2, tool3], handle_tool_errors=handle_tool_errors
).ainvoke(
{
@@ -337,7 +337,7 @@ async def test_tool_node_error_handling_callable() -> None:
return "Tool exception"
for handle_tool_errors in ("Value error", handle_value_error):
- result_error = await ToolNode([tool1], handle_tool_errors=handle_tool_errors).ainvoke(
+ result_error = await _ToolNode([tool1], handle_tool_errors=handle_tool_errors).ainvoke(
{
"messages": [
AIMessage(
@@ -363,7 +363,7 @@ async def test_tool_node_error_handling_callable() -> None:
# - passing a callable with all exceptions in the signature
for handle_tool_errors in ((ValueError,), handle_value_error):
with pytest.raises(ToolException) as exc_info:
- await ToolNode([tool1, tool2], handle_tool_errors=handle_tool_errors).ainvoke(
+ await _ToolNode([tool1, tool2], handle_tool_errors=handle_tool_errors).ainvoke(
{
"messages": [
AIMessage(
@@ -388,7 +388,7 @@ async def test_tool_node_error_handling_callable() -> None:
for handle_tool_errors in ((ToolException,), handle_tool_exception):
with pytest.raises(ValueError) as exc_info:
- await ToolNode([tool1, tool2], handle_tool_errors=handle_tool_errors).ainvoke(
+ await _ToolNode([tool1, tool2], handle_tool_errors=handle_tool_errors).ainvoke(
{
"messages": [
AIMessage(
@@ -414,7 +414,7 @@ async def test_tool_node_error_handling_callable() -> None:
async def test_tool_node_handle_tool_errors_false() -> None:
with pytest.raises(ValueError) as exc_info:
- ToolNode([tool1], handle_tool_errors=False).invoke(
+ _ToolNode([tool1], handle_tool_errors=False).invoke(
{
"messages": [
AIMessage(
@@ -434,7 +434,7 @@ async def test_tool_node_handle_tool_errors_false() -> None:
assert str(exc_info.value) == "Test error"
with pytest.raises(ToolException):
- await ToolNode([tool2], handle_tool_errors=False).ainvoke(
+ await _ToolNode([tool2], handle_tool_errors=False).ainvoke(
{
"messages": [
AIMessage(
@@ -455,7 +455,7 @@ async def test_tool_node_handle_tool_errors_false() -> None:
# test validation errors get raised if handle_tool_errors is False
with pytest.raises(ToolInvocationError):
- ToolNode([tool1], handle_tool_errors=False).invoke(
+ _ToolNode([tool1], handle_tool_errors=False).invoke(
{
"messages": [
AIMessage(
@@ -475,7 +475,7 @@ async def test_tool_node_handle_tool_errors_false() -> None:
def test_tool_node_individual_tool_error_handling() -> None:
# test error handling on individual tools (and that it overrides overall error handling!)
- result_individual_tool_error_handler = ToolNode([tool5], handle_tool_errors="bar").invoke(
+ result_individual_tool_error_handler = _ToolNode([tool5], handle_tool_errors="bar").invoke(
{
"messages": [
AIMessage(
@@ -500,7 +500,7 @@ def test_tool_node_individual_tool_error_handling() -> None:
def test_tool_node_incorrect_tool_name() -> None:
- result_incorrect_name = ToolNode([tool1, tool2]).invoke(
+ result_incorrect_name = _ToolNode([tool1, tool2]).invoke(
{
"messages": [
AIMessage(
@@ -534,7 +534,7 @@ def test_tool_node_node_interrupt() -> None:
return "handled"
for handle_tool_errors in (True, (GraphBubbleUp,), "handled", handle, False):
- node = ToolNode([tool_interrupt], handle_tool_errors=handle_tool_errors)
+ node = _ToolNode([tool_interrupt], handle_tool_errors=handle_tool_errors)
with pytest.raises(GraphBubbleUp) as exc_info:
node.invoke(
{
@@ -637,7 +637,7 @@ async def test_tool_node_command(input_type: str) -> None:
input_ = {"messages": [AIMessage("", tool_calls=tool_calls)]}
elif input_type == "tool_calls":
input_ = tool_calls
- result = ToolNode([add, transfer_to_bob]).invoke(input_)
+ result = _ToolNode([add, transfer_to_bob]).invoke(input_)
assert result == [
{
@@ -668,7 +668,7 @@ async def test_tool_node_command(input_type: str) -> None:
# test sync tools
for tool in [transfer_to_bob, custom_tool]:
- result = ToolNode([tool]).invoke(
+ result = _ToolNode([tool]).invoke(
{"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]}
)
assert result == [
@@ -689,7 +689,7 @@ async def test_tool_node_command(input_type: str) -> None:
# test async tools
for tool in [async_transfer_to_bob, async_custom_tool]:
- result = await ToolNode([tool]).ainvoke(
+ result = await _ToolNode([tool]).ainvoke(
{"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]}
)
assert result == [
@@ -709,7 +709,7 @@ async def test_tool_node_command(input_type: str) -> None:
]
# test multiple commands
- result = ToolNode([transfer_to_bob, custom_tool]).invoke(
+ result = _ToolNode([transfer_to_bob, custom_tool]).invoke(
{
"messages": [
AIMessage(
@@ -759,7 +759,7 @@ async def test_tool_node_command(input_type: str) -> None:
"""My tool"""
return Command(update=[ToolMessage(content="foo", tool_call_id=tool_call_id)])
- ToolNode([list_update_tool]).invoke(
+ _ToolNode([list_update_tool]).invoke(
{
"messages": [
AIMessage(
@@ -778,7 +778,7 @@ async def test_tool_node_command(input_type: str) -> None:
"""My tool"""
return Command(update={"messages": []})
- ToolNode([no_update_tool]).invoke(
+ _ToolNode([no_update_tool]).invoke(
{
"messages": [
AIMessage(
@@ -797,7 +797,7 @@ async def test_tool_node_command(input_type: str) -> None:
"""My tool"""
return Command(update={"messages": [ToolMessage(content="foo", tool_call_id="2")]})
- ToolNode([mismatching_tool_call_id_tool]).invoke(
+ _ToolNode([mismatching_tool_call_id_tool]).invoke(
{
"messages": [
AIMessage(
@@ -820,7 +820,7 @@ async def test_tool_node_command(input_type: str) -> None:
"""No update"""
return Command(update={"messages": []}, graph=Command.PARENT)
- assert ToolNode([node_update_parent_tool]).invoke(
+ assert _ToolNode([node_update_parent_tool]).invoke(
{
"messages": [
AIMessage(
@@ -897,7 +897,7 @@ async def test_tool_node_command_list_input() -> None:
"""Add two numbers"""
return a + b
- result = ToolNode([add, transfer_to_bob]).invoke(
+ result = _ToolNode([add, transfer_to_bob]).invoke(
[
AIMessage(
"",
@@ -934,7 +934,7 @@ async def test_tool_node_command_list_input() -> None:
# test sync tools
for tool in [transfer_to_bob, custom_tool]:
- result = ToolNode([tool]).invoke(
+ result = _ToolNode([tool]).invoke(
[AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]
)
assert result == [
@@ -953,7 +953,7 @@ async def test_tool_node_command_list_input() -> None:
# test async tools
for tool in [async_transfer_to_bob, async_custom_tool]:
- result = await ToolNode([tool]).ainvoke(
+ result = await _ToolNode([tool]).ainvoke(
[AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]
)
assert result == [
@@ -971,7 +971,7 @@ async def test_tool_node_command_list_input() -> None:
]
# test multiple commands
- result = ToolNode([transfer_to_bob, custom_tool]).invoke(
+ result = _ToolNode([transfer_to_bob, custom_tool]).invoke(
[
AIMessage(
"",
@@ -1017,7 +1017,7 @@ async def test_tool_node_command_list_input() -> None:
update={"messages": [ToolMessage(content="foo", tool_call_id=tool_call_id)]}
)
- ToolNode([list_update_tool]).invoke(
+ _ToolNode([list_update_tool]).invoke(
[
AIMessage(
"",
@@ -1034,7 +1034,7 @@ async def test_tool_node_command_list_input() -> None:
"""My tool"""
return Command(update=[])
- ToolNode([no_update_tool]).invoke(
+ _ToolNode([no_update_tool]).invoke(
[
AIMessage(
"",
@@ -1051,7 +1051,7 @@ async def test_tool_node_command_list_input() -> None:
"""My tool"""
return Command(update=[ToolMessage(content="foo", tool_call_id="2")])
- ToolNode([mismatching_tool_call_id_tool]).invoke(
+ _ToolNode([mismatching_tool_call_id_tool]).invoke(
[
AIMessage(
"",
@@ -1066,7 +1066,7 @@ async def test_tool_node_command_list_input() -> None:
"""No update"""
return Command(update=[], graph=Command.PARENT)
- assert ToolNode([node_update_parent_tool]).invoke(
+ assert _ToolNode([node_update_parent_tool]).invoke(
[
AIMessage(
"",
@@ -1126,7 +1126,7 @@ def test_tool_node_parent_command_with_send() -> None:
{"args": {}, "id": "2", "name": "transfer_to_bob", "type": "tool_call"},
]
- result = ToolNode([transfer_to_alice, transfer_to_bob]).invoke(
+ result = _ToolNode([transfer_to_alice, transfer_to_bob]).invoke(
[AIMessage("", tool_calls=tool_calls)]
)
@@ -1171,7 +1171,7 @@ async def test_tool_node_command_remove_all_messages() -> None:
"""A tool that removes all messages."""
return Command(update={"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]})
- tool_node = ToolNode([remove_all_messages_tool])
+ tool_node = _ToolNode([remove_all_messages_tool])
tool_call = {
"name": "remove_all_messages_tool",
"args": {},
@@ -1244,7 +1244,7 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:
"""Tool 1 docstring."""
return msgs[0].content
- node = ToolNode([tool1, tool2, tool3, tool4], handle_tool_errors=True)
+ node = _ToolNode([tool1, tool2, tool3, tool4], handle_tool_errors=True)
for tool_name in ("tool1", "tool2", "tool3"):
tool_call = {
"name": tool_name,
@@ -1321,7 +1321,7 @@ def test_tool_node_inject_store() -> None:
store_val = store.get(namespace, "test_key").value["foo"]
return f"Some val: {some_val}, store val: {store_val}, state val: {bar}"
- node = ToolNode([tool1, tool2, tool3], handle_tool_errors=True)
+ node = _ToolNode([tool1, tool2, tool3], handle_tool_errors=True)
store.put(namespace, "test_key", {"foo": "bar"})
class State(MessagesState):
@@ -1380,7 +1380,7 @@ def test_tool_node_ensure_utf8() -> None:
data = ["星期一", "水曜日", "목요일", "Friday"]
tools = [get_day_list]
tool_calls = [ToolCall(name=get_day_list.name, args={"days": data}, id="test_id")]
- outputs: list[ToolMessage] = ToolNode(tools).invoke(
+ outputs: list[ToolMessage] = _ToolNode(tools).invoke(
[AIMessage(content="", tool_calls=tool_calls)]
)
assert outputs[0].content == json.dumps(data, ensure_ascii=False)
@@ -1406,7 +1406,7 @@ def test_tool_node_messages_key() -> None:
builder = StateGraph(State)
builder.add_node("agent", call_model)
- builder.add_node("tools", ToolNode([add], messages_key="subgraph_messages"))
+ builder.add_node("tools", _ToolNode([add], messages_key="subgraph_messages"))
builder.add_conditional_edges(
"agent", partial(tools_condition, messages_key="subgraph_messages")
)
@@ -1437,7 +1437,7 @@ def test_tool_node_stream_writer() -> None:
return x
- tool_node = ToolNode([streaming_tool])
+ tool_node = _ToolNode([streaming_tool])
graph = (
StateGraph(MessagesState).add_node("tools", tool_node).add_edge(START, "tools").compile()
)
diff --git a/libs/langchain_v1/tests/unit_tests/embeddings/test_caching.py b/libs/langchain_v1/tests/unit_tests/embeddings/test_caching.py
deleted file mode 100644
index 913da9f90a..0000000000
--- a/libs/langchain_v1/tests/unit_tests/embeddings/test_caching.py
+++ /dev/null
@@ -1,245 +0,0 @@
-"""Embeddings tests."""
-
-import contextlib
-import hashlib
-import importlib
-import warnings
-
-import pytest
-from langchain_core.embeddings import Embeddings
-
-from langchain.embeddings import CacheBackedEmbeddings
-from langchain.storage.in_memory import InMemoryStore
-
-
-class MockEmbeddings(Embeddings):
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
- # Simulate embedding documents
- embeddings: list[list[float]] = []
- for text in texts:
- if text == "RAISE_EXCEPTION":
- msg = "Simulated embedding failure"
- raise ValueError(msg)
- embeddings.append([len(text), len(text) + 1])
- return embeddings
-
- def embed_query(self, text: str) -> list[float]:
- # Simulate embedding a query
- return [5.0, 6.0]
-
-
-def cache_embeddings() -> CacheBackedEmbeddings:
- """Create a cache backed embeddings."""
- store = InMemoryStore()
- embeddings = MockEmbeddings()
- return CacheBackedEmbeddings.from_bytes_store(
- embeddings,
- store,
- namespace="test_namespace",
- )
-
-
-def cache_embeddings_batch() -> CacheBackedEmbeddings:
- """Create a cache backed embeddings with a batch_size of 3."""
- store = InMemoryStore()
- embeddings = MockEmbeddings()
- return CacheBackedEmbeddings.from_bytes_store(
- embeddings,
- store,
- namespace="test_namespace",
- batch_size=3,
- )
-
-
-def cache_embeddings_with_query() -> CacheBackedEmbeddings:
- """Create a cache backed embeddings with query caching."""
- doc_store = InMemoryStore()
- query_store = InMemoryStore()
- embeddings = MockEmbeddings()
- return CacheBackedEmbeddings.from_bytes_store(
- embeddings,
- document_embedding_cache=doc_store,
- namespace="test_namespace",
- query_embedding_cache=query_store,
- )
-
-
-def test_embed_documents(cache_embeddings: CacheBackedEmbeddings) -> None:
- texts = ["1", "22", "a", "333"]
- vectors = cache_embeddings.embed_documents(texts)
- expected_vectors: list[list[float]] = [[1, 2.0], [2.0, 3.0], [1.0, 2.0], [3.0, 4.0]]
- assert vectors == expected_vectors
- keys = list(cache_embeddings.document_embedding_store.yield_keys())
- assert len(keys) == 4
- # UUID is expected to be the same for the same text
- assert keys[0] == "test_namespace812b86c1-8ebf-5483-95c6-c95cf2b52d12"
-
-
-def test_embed_documents_batch(cache_embeddings_batch: CacheBackedEmbeddings) -> None:
- # "RAISE_EXCEPTION" forces a failure in batch 2
- texts = ["1", "22", "a", "333", "RAISE_EXCEPTION"]
- with contextlib.suppress(ValueError):
- cache_embeddings_batch.embed_documents(texts)
- keys = list(cache_embeddings_batch.document_embedding_store.yield_keys())
- # only the first batch of three embeddings should exist
- assert len(keys) == 3
- # UUID is expected to be the same for the same text
- assert keys[0] == "test_namespace812b86c1-8ebf-5483-95c6-c95cf2b52d12"
-
-
-def test_embed_query(cache_embeddings: CacheBackedEmbeddings) -> None:
- text = "query_text"
- vector = cache_embeddings.embed_query(text)
- expected_vector = [5.0, 6.0]
- assert vector == expected_vector
- assert cache_embeddings.query_embedding_store is None
-
-
-def test_embed_cached_query(cache_embeddings_with_query: CacheBackedEmbeddings) -> None:
- text = "query_text"
- vector = cache_embeddings_with_query.embed_query(text)
- expected_vector = [5.0, 6.0]
- assert vector == expected_vector
- keys = list(cache_embeddings_with_query.query_embedding_store.yield_keys()) # type: ignore[union-attr]
- assert len(keys) == 1
- assert keys[0] == "test_namespace89ec3dae-a4d9-5636-a62e-ff3b56cdfa15"
-
-
-async def test_aembed_documents(cache_embeddings: CacheBackedEmbeddings) -> None:
- texts = ["1", "22", "a", "333"]
- vectors = await cache_embeddings.aembed_documents(texts)
- expected_vectors: list[list[float]] = [[1, 2.0], [2.0, 3.0], [1.0, 2.0], [3.0, 4.0]]
- assert vectors == expected_vectors
- keys = [key async for key in cache_embeddings.document_embedding_store.ayield_keys()]
- assert len(keys) == 4
- # UUID is expected to be the same for the same text
- assert keys[0] == "test_namespace812b86c1-8ebf-5483-95c6-c95cf2b52d12"
-
-
-async def test_aembed_documents_batch(
- cache_embeddings_batch: CacheBackedEmbeddings,
-) -> None:
- # "RAISE_EXCEPTION" forces a failure in batch 2
- texts = ["1", "22", "a", "333", "RAISE_EXCEPTION"]
- with contextlib.suppress(ValueError):
- await cache_embeddings_batch.aembed_documents(texts)
- keys = [key async for key in cache_embeddings_batch.document_embedding_store.ayield_keys()]
- # only the first batch of three embeddings should exist
- assert len(keys) == 3
- # UUID is expected to be the same for the same text
- assert keys[0] == "test_namespace812b86c1-8ebf-5483-95c6-c95cf2b52d12"
-
-
-async def test_aembed_query(cache_embeddings: CacheBackedEmbeddings) -> None:
- text = "query_text"
- vector = await cache_embeddings.aembed_query(text)
- expected_vector = [5.0, 6.0]
- assert vector == expected_vector
-
-
-async def test_aembed_query_cached(
- cache_embeddings_with_query: CacheBackedEmbeddings,
-) -> None:
- text = "query_text"
- await cache_embeddings_with_query.aembed_query(text)
- keys = list(cache_embeddings_with_query.query_embedding_store.yield_keys()) # type: ignore[union-attr]
- assert len(keys) == 1
- assert keys[0] == "test_namespace89ec3dae-a4d9-5636-a62e-ff3b56cdfa15"
-
-
-def test_blake2b_encoder() -> None:
- """Test that the blake2b encoder is used to encode keys in the cache store."""
- store = InMemoryStore()
- emb = MockEmbeddings()
- cbe = CacheBackedEmbeddings.from_bytes_store(
- emb,
- store,
- namespace="ns_",
- key_encoder="blake2b",
- )
-
- text = "blake"
- cbe.embed_documents([text])
-
- # rebuild the key exactly as the library does
- expected_key = "ns_" + hashlib.blake2b(text.encode()).hexdigest()
- assert list(cbe.document_embedding_store.yield_keys()) == [expected_key]
-
-
-def test_sha256_encoder() -> None:
- """Test that the sha256 encoder is used to encode keys in the cache store."""
- store = InMemoryStore()
- emb = MockEmbeddings()
- cbe = CacheBackedEmbeddings.from_bytes_store(
- emb,
- store,
- namespace="ns_",
- key_encoder="sha256",
- )
-
- text = "foo"
- cbe.embed_documents([text])
-
- # rebuild the key exactly as the library does
- expected_key = "ns_" + hashlib.sha256(text.encode()).hexdigest()
- assert list(cbe.document_embedding_store.yield_keys()) == [expected_key]
-
-
-def test_sha512_encoder() -> None:
- """Test that the sha512 encoder is used to encode keys in the cache store."""
- store = InMemoryStore()
- emb = MockEmbeddings()
- cbe = CacheBackedEmbeddings.from_bytes_store(
- emb,
- store,
- namespace="ns_",
- key_encoder="sha512",
- )
-
- text = "foo"
- cbe.embed_documents([text])
-
- # rebuild the key exactly as the library does
- expected_key = "ns_" + hashlib.sha512(text.encode()).hexdigest()
- assert list(cbe.document_embedding_store.yield_keys()) == [expected_key]
-
-
-def test_sha1_warning_emitted_once() -> None:
- """Test that a warning is emitted when using SHA-1 as the default key encoder."""
- module = importlib.import_module(CacheBackedEmbeddings.__module__)
-
- # Create a *temporary* MonkeyPatch object whose effects disappear
- # automatically when the with-block exits.
- with pytest.MonkeyPatch.context() as mp:
- # We're monkey patching the module to reset the `_warned_about_sha1` flag
- # which may have been set while testing other parts of the codebase.
- mp.setattr(module, "_warned_about_sha1", False, raising=False)
-
- store = InMemoryStore()
- emb = MockEmbeddings()
-
- with warnings.catch_warnings(record=True) as caught:
- warnings.simplefilter("always")
- CacheBackedEmbeddings.from_bytes_store(emb, store) # triggers warning
- CacheBackedEmbeddings.from_bytes_store(emb, store) # silent
-
- sha1_msgs = [w for w in caught if "SHA-1" in str(w.message)]
- assert len(sha1_msgs) == 1
-
-
-def test_custom_encoder() -> None:
- """Test that a custom encoder can be used to encode keys in the cache store."""
- store = InMemoryStore()
- emb = MockEmbeddings()
-
- def custom_upper(text: str) -> str: # very simple demo encoder
- return "CUSTOM_" + text.upper()
-
- cbe = CacheBackedEmbeddings.from_bytes_store(emb, store, key_encoder=custom_upper)
- txt = "x"
- cbe.embed_documents([txt])
-
- assert list(cbe.document_embedding_store.yield_keys()) == ["CUSTOM_X"]
diff --git a/libs/langchain_v1/tests/unit_tests/embeddings/test_imports.py b/libs/langchain_v1/tests/unit_tests/embeddings/test_imports.py
index e13af37bea..80ecff96b9 100644
--- a/libs/langchain_v1/tests/unit_tests/embeddings/test_imports.py
+++ b/libs/langchain_v1/tests/unit_tests/embeddings/test_imports.py
@@ -1,7 +1,6 @@
from langchain import embeddings
EXPECTED_ALL = [
- "CacheBackedEmbeddings",
"Embeddings",
"init_embeddings",
]
diff --git a/libs/langchain_v1/tests/unit_tests/storage/__init__.py b/libs/langchain_v1/tests/unit_tests/storage/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/libs/langchain_v1/tests/unit_tests/storage/test_imports.py b/libs/langchain_v1/tests/unit_tests/storage/test_imports.py
deleted file mode 100644
index 83315291ac..0000000000
--- a/libs/langchain_v1/tests/unit_tests/storage/test_imports.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from langchain import storage
-
-EXPECTED_ALL = [
- "EncoderBackedStore",
- "InMemoryStore",
- "InMemoryByteStore",
- "InvalidKeyException",
-]
-
-
-def test_all_imports() -> None:
- assert set(storage.__all__) == set(EXPECTED_ALL)
diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_imports.py b/libs/langchain_v1/tests/unit_tests/tools/test_imports.py
index b629d8a825..aec66cd993 100644
--- a/libs/langchain_v1/tests/unit_tests/tools/test_imports.py
+++ b/libs/langchain_v1/tests/unit_tests/tools/test_imports.py
@@ -8,7 +8,6 @@ EXPECTED_ALL = {
"InjectedToolCallId",
"ToolException",
"ToolInvocationError",
- "ToolNode",
"tool",
}
diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
index b38b88fab1..21d1a35dfb 100644
--- a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
+++ b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
@@ -9,7 +9,7 @@ from langgraph.types import Command
from langchain.tools.tool_node import (
ToolCallRequest,
- ToolNode,
+ _ToolNode,
)
pytestmark = pytest.mark.anyio
@@ -44,7 +44,7 @@ def test_passthrough_handler() -> None:
"""Simple passthrough handler."""
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=passthrough_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=passthrough_handler)
result = tool_node.invoke(
{
@@ -80,7 +80,7 @@ async def test_passthrough_handler_async() -> None:
"""Simple passthrough handler."""
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=passthrough_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=passthrough_handler)
result = await tool_node.ainvoke(
{
@@ -119,7 +119,7 @@ def test_modify_arguments() -> None:
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=modify_args_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=modify_args_handler)
result = tool_node.invoke(
{
@@ -154,7 +154,7 @@ def test_handler_validation_no_return() -> None:
"""Handler that executes and returns result."""
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=handler_with_explicit_none)
+ tool_node = _ToolNode([add], wrap_tool_call=handler_with_explicit_none)
result = tool_node.invoke(
{
@@ -191,7 +191,7 @@ def test_handler_validation_no_yield() -> None:
# Don't call execute, just return None (invalid)
return None # type: ignore[return-value]
- tool_node = ToolNode([add], wrap_tool_call=bad_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=bad_handler)
# This will return None wrapped in messages
result = tool_node.invoke(
@@ -230,7 +230,7 @@ def test_handler_with_handle_tool_errors_true() -> None:
assert message.status == "error"
return message
- tool_node = ToolNode(
+ tool_node = _ToolNode(
[failing_tool], wrap_tool_call=passthrough_handler, handle_tool_errors=True
)
@@ -269,7 +269,7 @@ def test_multiple_tool_calls_with_handler() -> None:
call_count += 1
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=counting_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=counting_handler)
result = tool_node.invoke(
{
@@ -343,7 +343,7 @@ async def test_handler_with_async_execution() -> None:
request.tool_call["args"]["b"] += 10
return execute(request)
- tool_node = ToolNode([async_add], wrap_tool_call=modifying_handler)
+ tool_node = _ToolNode([async_add], wrap_tool_call=modifying_handler)
result = await tool_node.ainvoke(
{
@@ -383,7 +383,7 @@ def test_short_circuit_with_tool_message() -> None:
name=request.tool_call["name"],
)
- tool_node = ToolNode([add], wrap_tool_call=short_circuit_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=short_circuit_handler)
result = tool_node.invoke(
{
@@ -423,7 +423,7 @@ async def test_short_circuit_with_tool_message_async() -> None:
name=request.tool_call["name"],
)
- tool_node = ToolNode([add], wrap_tool_call=short_circuit_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=short_circuit_handler)
result = await tool_node.ainvoke(
{
@@ -470,7 +470,7 @@ def test_conditional_short_circuit() -> None:
# Odd: execute normally
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=conditional_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=conditional_handler)
# Test with even number (should be cached)
result1 = tool_node.invoke(
@@ -530,7 +530,7 @@ def test_direct_return_tool_message() -> None:
name=request.tool_call["name"],
)
- tool_node = ToolNode([add], wrap_tool_call=direct_return_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=direct_return_handler)
result = tool_node.invoke(
{
@@ -570,7 +570,7 @@ async def test_direct_return_tool_message_async() -> None:
name=request.tool_call["name"],
)
- tool_node = ToolNode([add], wrap_tool_call=direct_return_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=direct_return_handler)
result = await tool_node.ainvoke(
{
@@ -615,7 +615,7 @@ def test_conditional_direct_return() -> None:
# Execute tool normally
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=conditional_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=conditional_handler)
# Test with zero (should return directly)
result1 = tool_node.invoke(
@@ -675,7 +675,7 @@ def test_handler_can_throw_exception() -> None:
raise TypeError(msg)
return response
- tool_node = ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=True)
+ tool_node = _ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=True)
result = tool_node.invoke(
{
@@ -714,7 +714,7 @@ def test_handler_throw_without_handle_errors() -> None:
msg = "Handler error"
raise ValueError(msg)
- tool_node = ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=False)
+ tool_node = _ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=False)
with pytest.raises(ValueError, match="Handler error"):
tool_node.invoke(
@@ -759,7 +759,7 @@ def test_retry_middleware_with_exception() -> None:
# If we exhausted retries, return last response
return response
- tool_node = ToolNode([add], wrap_tool_call=retry_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=retry_handler)
result = tool_node.invoke(
{
@@ -798,7 +798,7 @@ async def test_async_handler_can_throw_exception() -> None:
msg = "Async handler rejected the request"
raise ValueError(msg)
- tool_node = ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=True)
+ tool_node = _ToolNode([add], wrap_tool_call=throwing_handler, handle_tool_errors=True)
result = await tool_node.ainvoke(
{
@@ -838,7 +838,7 @@ def test_handler_cannot_yield_multiple_tool_messages() -> None:
"""Handler that returns once (as all handlers do)."""
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=single_return_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=single_return_handler)
result = tool_node.invoke(
{
@@ -875,7 +875,7 @@ def test_handler_cannot_yield_request_after_tool_message() -> None:
# Return cached result (short-circuit)
return ToolMessage("cached", tool_call_id=request.tool_call["id"], name="add")
- tool_node = ToolNode([add], wrap_tool_call=single_return_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=single_return_handler)
result = tool_node.invoke(
{
@@ -910,7 +910,7 @@ def test_handler_can_short_circuit_with_command() -> None:
# Short-circuit with Command instead of executing tool
return Command(goto="end")
- tool_node = ToolNode([add], wrap_tool_call=command_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=command_handler)
result = tool_node.invoke(
{
@@ -948,7 +948,7 @@ def test_handler_cannot_yield_multiple_commands() -> None:
"""Handler that returns Command once."""
return Command(goto="step1")
- tool_node = ToolNode([add], wrap_tool_call=single_command_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=single_command_handler)
result = tool_node.invoke(
{
@@ -986,7 +986,7 @@ def test_handler_cannot_yield_request_after_command() -> None:
"""Handler that returns Command."""
return Command(goto="somewhere")
- tool_node = ToolNode([add], wrap_tool_call=command_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=command_handler)
result = tool_node.invoke(
{
@@ -1027,7 +1027,7 @@ def test_tool_returning_command_sent_to_handler() -> None:
received_commands.append(result)
return result
- tool_node = ToolNode([command_tool], wrap_tool_call=command_inspector_handler)
+ tool_node = _ToolNode([command_tool], wrap_tool_call=command_inspector_handler)
result = tool_node.invoke(
{
@@ -1071,7 +1071,7 @@ def test_handler_can_modify_command_from_tool() -> None:
return Command(goto=f"modified_{result.goto}")
return result
- tool_node = ToolNode([command_tool], wrap_tool_call=command_modifier_handler)
+ tool_node = _ToolNode([command_tool], wrap_tool_call=command_modifier_handler)
result = tool_node.invoke(
{
@@ -1109,7 +1109,7 @@ def test_state_extraction_with_dict_input() -> None:
state_seen.append(request.state)
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=state_inspector_handler)
input_state = {
"messages": [
@@ -1144,7 +1144,7 @@ def test_state_extraction_with_list_input() -> None:
state_seen.append(request.state)
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=state_inspector_handler)
input_state = [
AIMessage(
@@ -1178,7 +1178,7 @@ def test_state_extraction_with_tool_call_with_context() -> None:
state_seen.append(request.state)
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=state_inspector_handler)
# Simulate ToolCallWithContext as used by create_agent with Send API
actual_state = {
@@ -1221,7 +1221,7 @@ async def test_state_extraction_with_tool_call_with_context_async() -> None:
state_seen.append(request.state)
return execute(request)
- tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
+ tool_node = _ToolNode([add], wrap_tool_call=state_inspector_handler)
# Simulate ToolCallWithContext as used by create_agent with Send API
actual_state = {