The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
style: more refs work (#33707)
Mason Daughertye5e1d6c70521
diff --git a/.github/workflows/pr_lint.yml b/.github/workflows/pr_lint.ymlindex 0b86e01180..00505fec49 100644--- a/.github/workflows/pr_lint.yml+++ b/.github/workflows/pr_lint.yml@@ -30,7 +30,7 @@# core, cli, langchain, langchain_v1, langchain-classic, standard-tests,# text-splitters, docs, anthropic, chroma, deepseek, exa, fireworks, groq,# huggingface, mistralai, nomic, ollama, openai, perplexity, prompty, qdrant,-# xai, infra+# xai, infra, deps## Rules:# 1. The 'Type' must start with a lowercase letter.diff --git a/libs/core/langchain_core/chat_history.py b/libs/core/langchain_core/chat_history.pyindex 47b32e0dff..7c315d44d4 100644--- a/libs/core/langchain_core/chat_history.py+++ b/libs/core/langchain_core/chat_history.py@@ -121,7 +121,7 @@ class BaseChatMessageHistory(ABC):This method may be deprecated in a future release.Args:- message: The human message to add to the store.+ message: The `HumanMessage` to add to the store."""if isinstance(message, HumanMessage):self.add_message(message)@@ -129,7 +129,7 @@ class BaseChatMessageHistory(ABC):self.add_message(HumanMessage(content=message))def add_ai_message(self, message: AIMessage | str) -> None:- """Convenience method for adding an AI message string to the store.+ """Convenience method for adding an `AIMessage` string to the store.!!! noteThis is a convenience method. Code should favor the bulk `add_messages`@@ -138,7 +138,7 @@ class BaseChatMessageHistory(ABC):This method may be deprecated in a future release.Args:- message: The AI message to add.+ message: The `AIMessage` to add."""if isinstance(message, AIMessage):self.add_message(message)@@ -173,7 +173,7 @@ class BaseChatMessageHistory(ABC):in an efficient manner to avoid unnecessary round-trips to the underlying store.Args:- messages: A sequence of BaseMessage objects to store.+ messages: A sequence of `BaseMessage` objects to store."""for message in messages:self.add_message(message)@@ -182,7 +182,7 @@ class BaseChatMessageHistory(ABC):"""Async add a list of messages.Args:- messages: A sequence of BaseMessage objects to store.+ messages: A sequence of `BaseMessage` objects to store."""await run_in_executor(None, self.add_messages, messages)diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.pyindex 9967c8a70d..68eeca0fd3 100644--- a/libs/core/langchain_core/documents/base.py+++ b/libs/core/langchain_core/documents/base.py@@ -32,7 +32,7 @@ class BaseMedia(Serializable):# 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.+ # 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.diff --git a/libs/core/langchain_core/example_selectors/semantic_similarity.py b/libs/core/langchain_core/example_selectors/semantic_similarity.pyindex 27e88f0b64..1e7491a2eb 100644--- a/libs/core/langchain_core/example_selectors/semantic_similarity.py+++ b/libs/core/langchain_core/example_selectors/semantic_similarity.py@@ -41,7 +41,7 @@ class _VectorStoreExampleSelector(BaseExampleSelector, BaseModel, ABC):"""Optional keys to filter input to. If provided, the search is based onthe input variables instead of all variables."""vectorstore_kwargs: dict[str, Any] | None = None- """Extra arguments passed to similarity_search function of the vectorstore."""+ """Extra arguments passed to similarity_search function of the `VectorStore`."""model_config = ConfigDict(arbitrary_types_allowed=True,@@ -159,7 +159,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):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.+ of the `VectorStore`.vectorstore_cls_kwargs: optional kwargs containing url for vector storeReturns:@@ -203,7 +203,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):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.+ of the `VectorStore`.vectorstore_cls_kwargs: optional kwargs containing url for vector storeReturns:@@ -286,12 +286,12 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):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 Documents to fetch to pass to MMR algorithm.+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.input_keys: If provided, the search is based on the input variablesinstead of all variables.example_keys: If provided, keys to filter examples to.vectorstore_kwargs: Extra arguments passed to similarity_search function- of the vectorstore.+ of the `VectorStore`.vectorstore_cls_kwargs: optional kwargs containing url for vector storeReturns:@@ -333,12 +333,12 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):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 Documents to fetch to pass to MMR algorithm.+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.input_keys: If provided, the search is based on the input variablesinstead of all variables.example_keys: If provided, keys to filter examples to.vectorstore_kwargs: Extra arguments passed to similarity_search function- of the vectorstore.+ of the `VectorStore`.vectorstore_cls_kwargs: optional kwargs containing url for vector storeReturns:diff --git a/libs/core/langchain_core/indexing/__init__.py b/libs/core/langchain_core/indexing/__init__.pyindex aea7b9fadf..ceb25d2d07 100644--- a/libs/core/langchain_core/indexing/__init__.py+++ b/libs/core/langchain_core/indexing/__init__.py@@ -1,7 +1,7 @@"""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+a `VectorStore` while avoiding duplicated content and over-writing contentif it's unchanged."""diff --git a/libs/core/langchain_core/indexing/api.py b/libs/core/langchain_core/indexing/api.pyindex 6c75af601f..84bd746b53 100644--- a/libs/core/langchain_core/indexing/api.py+++ b/libs/core/langchain_core/indexing/api.py@@ -304,42 +304,42 @@ def index(!!! 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.+ 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.+ 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.+ 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 wereupdated.- vector_store: VectorStore or DocumentIndex to index the documents into.+ 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.+ 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.+ 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.+ 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 sourceof the document.@@ -363,7 +363,7 @@ def index(When changing the key encoder, you must change theindex 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.+ 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 version 0.3.10"@@ -375,10 +375,10 @@ def index(Raises:ValueError: If cleanup mode is not one of 'incremental', 'full' or NoneValueError: If cleanup mode is incremental and source_id_key is None.- ValueError: If vectorstore does not have+ 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.+ 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)."""@@ -415,7 +415,7 @@ def index(raise ValueError(msg)if type(destination).delete == VectorStore.delete:- # Checking if the vectorstore has overridden the default delete method+ # Checking if the VectorStore has overridden the default delete method# implementation which just raises a NotImplementedErrormsg = "Vectorstore has not implemented the delete method"raise ValueError(msg)@@ -466,11 +466,11 @@ def index(]if cleanup in {"incremental", "scoped_full"}:- # source ids are required.+ # 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"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]} "@@ -479,7 +479,7 @@ def index(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 cannot be None after for loop above.source_ids = cast("Sequence[str]", source_ids)exists_batch = record_manager.exists(@@ -538,7 +538,7 @@ def index(# 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+ # 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:@@ -642,42 +642,42 @@ async def aindex(!!! 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.+ 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.+ 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.+ 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 wereupdated.- vector_store: VectorStore or DocumentIndex to index the documents into.+ 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.+ 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.+ 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.+ 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 sourceof the document.@@ -701,7 +701,7 @@ async def aindex(When changing the key encoder, you must change theindex 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.+ 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 version 0.3.10"@@ -713,10 +713,10 @@ async def aindex(Raises:ValueError: If cleanup mode is not one of 'incremental', 'full' or NoneValueError: If cleanup mode is incremental and source_id_key is None.- ValueError: If vectorstore does not have+ 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.+ TypeError: If `vector_store` is not a `VectorStore` or DocumentIndex.AssertionError: If `source_id_key` is None when cleanup mode isincremental or `scoped_full` (should be unreachable)."""@@ -757,7 +757,7 @@ async def aindex(type(destination).adelete == VectorStore.adeleteand type(destination).delete == VectorStore.delete):- # Checking if the vectorstore has overridden the default adelete or delete+ # Checking if the VectorStore has overridden the default adelete or delete# methods implementation which just raises a NotImplementedErrormsg = "Vectorstore has not implemented the adelete or delete method"raise ValueError(msg)@@ -815,11 +815,11 @@ async def aindex(]if cleanup in {"incremental", "scoped_full"}:- # If the cleanup mode is incremental, source ids are required.+ # 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"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]} "@@ -828,7 +828,7 @@ async def aindex(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 cannot be None after for loop above.source_ids = cast("Sequence[str]", source_ids)exists_batch = await record_manager.aexists(@@ -888,7 +888,7 @@ async def aindex(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+ # 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:diff --git a/libs/core/langchain_core/indexing/base.py b/libs/core/langchain_core/indexing/base.pyindex a4a4310134..d8a891ddf9 100644--- a/libs/core/langchain_core/indexing/base.py+++ b/libs/core/langchain_core/indexing/base.py@@ -25,7 +25,7 @@ class RecordManager(ABC):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.+ written into a `VectorStore` and when they were written.The indexing API computes hashes for each document and stores the hashtogether with the write time and the source id in the record manager.@@ -37,7 +37,7 @@ class RecordManager(ABC):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+ To be supported, a `VectorStore` needs to only support the ability to add anddelete documents by ID. Using the record manager, the indexing API willbe able to delete outdated documents and avoid redundant indexing of documentsthat have already been indexed.@@ -45,13 +45,13 @@ class RecordManager(ABC):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.+ 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.+ 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__(@@ -460,7 +460,7 @@ class UpsertResponse(TypedDict):class DeleteResponse(TypedDict, total=False):"""A generic response for delete operation.- The fields in this response are optional and whether the vectorstore+ The fields in this response are optional and whether the `VectorStore`returns them or not is up to the implementation."""@@ -518,7 +518,7 @@ class DocumentIndex(BaseRetriever):if it is provided. If the ID is not provided, the upsert method is freeto generate an ID for the content.- When an ID is specified and the content already exists in the vectorstore,+ 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 contentdoes not exist, the upsert method should add the item to the `VectorStore`.@@ -528,20 +528,20 @@ class DocumentIndex(BaseRetriever):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+ successfully added or updated in the `VectorStore` and the list of IDs thatfailed 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.+ """Add or update documents in the `VectorStore`. Async version of `upsert`.The upsert functionality should utilize the ID field of the itemif it is provided. If the ID is not provided, the upsert method is freeto generate an ID for the item.- When an ID is specified and the item already exists in the vectorstore,+ 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 itemdoes not exist, the upsert method should add the item to the `VectorStore`.@@ -551,7 +551,7 @@ class DocumentIndex(BaseRetriever):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+ successfully added or updated in the `VectorStore` and the list of IDs thatfailed to be added or updated."""return await run_in_executor(@@ -568,7 +568,7 @@ class DocumentIndex(BaseRetriever):Calling delete without any input parameters should raise a ValueError!Args:- ids: List of ids to delete.+ 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.@@ -586,7 +586,7 @@ class DocumentIndex(BaseRetriever):Calling adelete without any input parameters should raise a ValueError!Args:- ids: List of ids to delete.+ 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.diff --git a/libs/core/langchain_core/indexing/in_memory.py b/libs/core/langchain_core/indexing/in_memory.pyindex 5fd6292a09..ae9cf84088 100644--- a/libs/core/langchain_core/indexing/in_memory.py+++ b/libs/core/langchain_core/indexing/in_memory.py@@ -62,10 +62,10 @@ class InMemoryDocumentIndex(DocumentIndex):"""Delete by IDs.Args:- ids: List of ids to delete.+ ids: List of IDs to delete.Raises:- ValueError: If ids is None.+ ValueError: If IDs is None.Returns:A response object that contains the list of IDs that were successfullydiff --git a/libs/core/langchain_core/language_models/base.py b/libs/core/langchain_core/language_models/base.pyindex 621f1da5b7..ec84230157 100644--- a/libs/core/langchain_core/language_models/base.py+++ b/libs/core/langchain_core/language_models/base.py@@ -262,13 +262,13 @@ class BaseLanguageModel(return self.lc_attributesdef get_token_ids(self, text: str) -> list[int]:- """Return the ordered ids of the tokens in a text.+ """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+ A list of IDs corresponding to the tokens in the text, in order they occurin the text."""if self.custom_get_token_ids is not None:diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.pyindex 595f522299..c6b6f60414 100644--- a/libs/core/langchain_core/messages/ai.py+++ b/libs/core/langchain_core/messages/ai.py@@ -655,13 +655,13 @@ def add_ai_message_chunks(chunk_id = id_breakelse:- # second pass: prefer lc_run-* ids over lc_* ids+ # second pass: prefer lc_run-* IDs over lc_* IDsfor id_ in candidates:if id_ and id_.startswith(LC_ID_PREFIX):chunk_id = id_breakelse:- # third pass: take any remaining id (auto-generated lc_* ids)+ # third pass: take any remaining ID (auto-generated lc_* IDs)for id_ in candidates:if id_:chunk_id = id_diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.pyindex 267bdfeb17..5554aa8abf 100644--- a/libs/core/langchain_core/messages/utils.py+++ b/libs/core/langchain_core/messages/utils.py@@ -1025,18 +1025,18 @@ def convert_to_openai_messages(messages: Message-like object or iterable of objects whose contents arein 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.+ - `'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.Raises:ValueError: if an unrecognized `text_format` is specified, or if a messagediff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.pyindex bf1d071bf2..76f1cc1f5b 100644--- a/libs/core/langchain_core/runnables/graph.py+++ b/libs/core/langchain_core/runnables/graph.py@@ -132,7 +132,7 @@ class Branch(NamedTuple):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. """+ """Optional dictionary of end node IDs for the branches. """class CurveStyle(Enum):@@ -706,8 +706,10 @@ class Graph: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.+ 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}@@ -722,8 +724,10 @@ def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | 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.+ 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}diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.pyindex d4b90d1d14..4b4e136ab5 100644--- a/libs/core/langchain_core/vectorstores/base.py+++ b/libs/core/langchain_core/vectorstores/base.py@@ -58,16 +58,16 @@ class VectorStore(ABC):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.+ **kwargs: `VectorStore` specific parameters.One of the kwargs should be `ids` which is a list of idsassociated with the texts.Returns:- List of ids from adding the texts into the `VectorStore`.+ 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.+ 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@@ -109,11 +109,12 @@ class VectorStore(ABC):"""Delete by vector ID or other criteria.Args:- ids: List of ids to delete. If `None`, delete all.+ 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.+ `True` if deletion is successful, `False` otherwise, `None` if not+ implemented."""msg = "delete method must be implemented by subclass."raise NotImplementedError(msg)@@ -135,10 +136,10 @@ class VectorStore(ABC):some IDs.Args:- ids: List of ids to retrieve.+ ids: List of IDs to retrieve.Returns:- List of Documents.+ List of `Document` objects."""msg = f"{self.__class__.__name__} does not yet support get_by_ids."raise NotImplementedError(msg)@@ -161,10 +162,10 @@ class VectorStore(ABC):some IDs.Args:- ids: List of ids to retrieve.+ ids: List of IDs to retrieve.Returns:- List of Documents.+ List of `Document` objects."""return await run_in_executor(None, self.get_by_ids, ids)@@ -172,11 +173,12 @@ class VectorStore(ABC):"""Async delete by vector ID or other criteria.Args:- ids: List of ids to delete. If `None`, delete all.+ 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.+ `True` if deletion is successful, `False` otherwise, `None` if not+ implemented."""return await run_in_executor(None, self.delete, ids, **kwargs)@@ -194,14 +196,14 @@ class VectorStore(ABC):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.+ **kwargs: `VectorStore` specific parameters.Returns:- List of ids from adding the texts into the `VectorStore`.+ 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.+ ValueError: If the number of IDs does not match the number of texts."""if ids is not None:# For backward compatibility@@ -230,13 +232,13 @@ class VectorStore(ABC):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.+ """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.+ if kwargs contains IDs and documents contain ids,+ the IDs in the kwargs will receive precedence.Returns:List of IDs of the added texts.@@ -291,17 +293,17 @@ class VectorStore(ABC):"""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".+ 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".+ ValueError: If `search_type` is not one of `'similarity'`,+ `'mmr'`, or `'similarity_score_threshold'`."""if search_type == "similarity":return self.similarity_search(query, **kwargs)@@ -326,16 +328,16 @@ class VectorStore(ABC):Args:query: Input text.- search_type: Type of search to perform. Can be "similarity",- "mmr", or "similarity_score_threshold".+ 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".+ 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)@@ -360,7 +362,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ k: Number of `Document` objects to return.**kwargs: Arguments to pass to the search method.Returns:@@ -457,7 +459,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ 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@@ -484,7 +486,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ 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@@ -508,7 +510,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ 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@@ -557,7 +559,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ 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@@ -601,7 +603,7 @@ class VectorStore(ABC):Args:query: Input text.- k: Number of Documents to return.+ k: Number of `Document` objects to return.**kwargs: Arguments to pass to the search method.Returns:@@ -619,7 +621,7 @@ class VectorStore(ABC):Args:embedding: Embedding to look up documents similar to.- k: Number of Documents to return.+ k: Number of `Document` objects to return.**kwargs: Arguments to pass to the search method.Returns:@@ -634,7 +636,7 @@ class VectorStore(ABC):Args:embedding: Embedding to look up documents similar to.- k: Number of Documents to return.+ k: Number of `Document` objects to return.**kwargs: Arguments to pass to the search method.Returns:@@ -662,11 +664,11 @@ class VectorStore(ABC):Args:query: Text to look up documents similar to.- k: Number of Documents to return.- fetch_k: Number of Documents to fetch to pass to MMR algorithm.- lambda_mult: Number between 0 and 1 that determines the degree+ 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 degreeof diversity among the results with 0 corresponding- to maximum diversity and 1 to minimum diversity.+ to maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.Returns:@@ -689,11 +691,11 @@ class VectorStore(ABC):Args:query: Text to look up documents similar to.- k: Number of Documents to return.- fetch_k: Number of Documents to fetch to pass to MMR algorithm.- lambda_mult: Number between 0 and 1 that determines the degree+ 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 degreeof diversity among the results with 0 corresponding- to maximum diversity and 1 to minimum diversity.+ to maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.Returns:@@ -727,11 +729,11 @@ class VectorStore(ABC):Args:embedding: Embedding to look up documents similar to.- k: Number of Documents to return.- fetch_k: Number of Documents to fetch to pass to MMR algorithm.- lambda_mult: Number between 0 and 1 that determines the degree+ 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 degreeof diversity among the results with 0 corresponding- to maximum diversity and 1 to minimum diversity.+ to maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.Returns:@@ -754,11 +756,11 @@ class VectorStore(ABC):Args:embedding: Embedding to look up documents similar to.- k: Number of Documents to return.- fetch_k: Number of Documents to fetch to pass to MMR algorithm.- lambda_mult: Number between 0 and 1 that determines the degree+ 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 degreeof diversity among the results with 0 corresponding- to maximum diversity and 1 to minimum diversity.+ to maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.Returns:@@ -845,7 +847,7 @@ class VectorStore(ABC):ids: list[str] | None = None,**kwargs: Any,) -> VST:- """Return VectorStore initialized from texts and embeddings.+ """Return `VectorStore` initialized from texts and embeddings.Args:texts: Texts to add to the `VectorStore`.@@ -855,7 +857,7 @@ class VectorStore(ABC):**kwargs: Additional keyword arguments.Returns:- VectorStore initialized from texts and embeddings.+ `VectorStore` initialized from texts and embeddings."""@classmethod@@ -868,7 +870,7 @@ class VectorStore(ABC):ids: list[str] | None = None,**kwargs: Any,) -> Self:- """Async return VectorStore initialized from texts and embeddings.+ """Async return `VectorStore` initialized from texts and embeddings.Args:texts: Texts to add to the `VectorStore`.@@ -878,7 +880,7 @@ class VectorStore(ABC):**kwargs: Additional keyword arguments.Returns:- VectorStore initialized from texts and embeddings.+ `VectorStore` initialized from texts and embeddings."""if ids is not None:kwargs["ids"] = ids@@ -899,19 +901,21 @@ class VectorStore(ABC):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++ * `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. Caninclude 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++ * `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 metadataReturns:Retriever class for `VectorStore`.@@ -954,7 +958,7 @@ class VectorStoreRetriever(BaseRetriever):vectorstore: VectorStore"""VectorStore to use for retrieval."""search_type: str = "similarity"- """Type of search to perform. Defaults to "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]] = (@@ -979,8 +983,8 @@ class VectorStoreRetriever(BaseRetriever):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)+ 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:diff --git a/libs/core/langchain_core/vectorstores/in_memory.py b/libs/core/langchain_core/vectorstores/in_memory.pyindex 90c6b84ce4..cb8a9b1985 100644--- a/libs/core/langchain_core/vectorstores/in_memory.py+++ b/libs/core/langchain_core/vectorstores/in_memory.py@@ -257,7 +257,7 @@ class InMemoryVectorStore(VectorStore):"""Get documents by their ids.Args:- ids: The ids of the documents to get.+ ids: The IDs of the documents to get.Returns:A list of `Document` objects.@@ -281,7 +281,7 @@ class InMemoryVectorStore(VectorStore):"""Async get documents by their ids.Args:- ids: The ids of the documents to get.+ ids: The IDs of the documents to get.Returns:A list of `Document` objects.diff --git a/libs/core/tests/unit_tests/indexing/test_indexing.py b/libs/core/tests/unit_tests/indexing/test_indexing.pyindex a4baef198d..f598048a98 100644--- a/libs/core/tests/unit_tests/indexing/test_indexing.py+++ b/libs/core/tests/unit_tests/indexing/test_indexing.py@@ -604,7 +604,7 @@ def test_incremental_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedindex(@@ -654,7 +654,7 @@ async def test_aincremental_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedawait aindex(@@ -956,7 +956,7 @@ def test_scoped_full_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedindex(@@ -1006,7 +1006,7 @@ async def test_ascoped_full_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedawait aindex(@@ -2801,7 +2801,7 @@ def test_index_with_upsert_kwargs(]assert [doc.metadata for doc in args[0]] == [{"source": "1"}, {"source": "2"}]- # Check that ids are present+ # Check that IDs are presentassert "ids" in kwargsassert isinstance(kwargs["ids"], list)assert len(kwargs["ids"]) == 2@@ -2932,7 +2932,7 @@ async def test_aindex_with_upsert_kwargs(]assert [doc.metadata for doc in args[0]] == [{"source": "1"}, {"source": "2"}]- # Check that ids are present+ # Check that IDs are presentassert "ids" in kwargsassert isinstance(kwargs["ids"], list)assert len(kwargs["ids"]) == 2diff --git a/libs/core/tests/unit_tests/runnables/test_runnable.py b/libs/core/tests/unit_tests/runnables/test_runnable.pyindex c8afa1eea5..e04bf4e75b 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable.py@@ -94,7 +94,7 @@ PYDANTIC_VERSION_AT_LEAST_210 = version.parse("2.10") <= PYDANTIC_VERSIONclass FakeTracer(BaseTracer):"""Fake tracer that records LangChain execution.- It replaces run ids with deterministic UUIDs for snapshotting.+ It replaces run IDs with deterministic UUIDs for snapshotting."""def __init__(self) -> None:@@ -2073,7 +2073,7 @@ async def test_prompt_with_llm(part async for part in chain.astream_log({"question": "What is your name?"})]- # remove ids from logs+ # Remove IDs from logsfor part in stream_log:for op in part.ops:if (@@ -2284,7 +2284,7 @@ async def test_prompt_with_llm_parser(part async for part in chain.astream_log({"question": "What is your name?"})]- # remove ids from logs+ # Remove IDs from logsfor part in stream_log:for op in part.ops:if (@@ -2472,7 +2472,7 @@ async def test_stream_log_retriever() -> None:part async for part in chain.astream_log({"question": "What is your name?"})]- # remove ids from logs+ # Remove IDs from logsfor part in stream_log:for op in part.ops:if (@@ -2505,7 +2505,7 @@ async def test_stream_log_lists() -> None:part async for part in chain.astream_log({"question": "What is your name?"})]- # remove ids from logs+ # Remove IDs from logsfor part in stream_log:for op in part.ops:if (diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.pyindex 8efd5aea9a..0b30aa58be 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py@@ -36,10 +36,10 @@ from tests.unit_tests.stubs import _any_id_ai_message, _any_id_ai_message_chunkdef _with_nulled_run_id(events: Sequence[StreamEvent]) -> list[StreamEvent]:- """Removes the run ids from events."""+ """Removes the run IDs from events."""for event in events:- assert "parent_ids" in event, "Parent ids should be present in the event."- assert event["parent_ids"] == [], "Parent ids should be empty."+ assert "parent_ids" in event, "Parent IDs should be present in the event."+ assert event["parent_ids"] == [], "Parent IDs should be empty."return cast("list[StreamEvent]", [{**event, "run_id": ""} for event in events])diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.pyindex de6c4030ca..42e95d6b16 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py@@ -56,7 +56,7 @@ from tests.unit_tests.stubs import _any_id_ai_message, _any_id_ai_message_chunkdef _with_nulled_run_id(events: Sequence[StreamEvent]) -> list[StreamEvent]:- """Removes the run ids from events."""+ """Removes the run IDs from events."""for event in events:assert "run_id" in event, f"Event {event} does not have a run_id."assert "parent_ids" in event, f"Event {event} does not have parent_ids."diff --git a/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py b/libs/core/tests/unit_tests/vectorstores/test_vectorstore.pyindex e3904b7ad6..f8af00ee79 100644--- a/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py+++ b/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py@@ -21,7 +21,7 @@ if TYPE_CHECKING:class CustomAddTextsVectorstore(VectorStore):- """A vectorstore that only implements add texts."""+ """A VectorStore that only implements add texts."""def __init__(self) -> None:self.store: dict[str, Document] = {}@@ -72,7 +72,7 @@ class CustomAddTextsVectorstore(VectorStore):class CustomAddDocumentsVectorstore(VectorStore):- """A vectorstore that only implements add documents."""+ """A VectorStore that only implements add documents."""def __init__(self) -> None:self.store: dict[str, Document] = {}@@ -249,7 +249,7 @@ def test_default_from_documents(vs_class: type[VectorStore]) -> None:Document(id="1", page_content="hello", metadata={"foo": "bar"})]- # from_documents with ids in args+ # from_documents with IDs in argsstore = vs_class.from_documents([Document(page_content="hello", metadata={"foo": "bar"})], embeddings, ids=["1"])@@ -278,7 +278,7 @@ async def test_default_afrom_documents(vs_class: type[VectorStore]) -> None:Document(id="1", page_content="hello", metadata={"foo": "bar"})]- # from_documents with ids in args+ # from_documents with IDs in argsstore = await vs_class.afrom_documents([Document(page_content="hello", metadata={"foo": "bar"})], embeddings, ids=["1"])@@ -287,7 +287,7 @@ async def test_default_afrom_documents(vs_class: type[VectorStore]) -> None:Document(id="1", page_content="hello", metadata={"foo": "bar"})]- # Test afrom_documents with id specified in both document and ids+ # Test afrom_documents with id specified in both document and IDsoriginal_document = Document(id="7", page_content="baz")store = await vs_class.afrom_documents([original_document], embeddings, ids=["6"])assert original_document.id == "7" # original document should not be modifieddiff --git a/libs/langchain/langchain_classic/agents/chat/base.py b/libs/langchain/langchain_classic/agents/chat/base.pyindex d56cab5894..c2f5f9576f 100644--- a/libs/langchain/langchain_classic/agents/chat/base.py+++ b/libs/langchain/langchain_classic/agents/chat/base.py@@ -95,7 +95,7 @@ class ChatAgent(Agent):tools: A list of tools.system_message_prefix: The system message prefix.system_message_suffix: The system message suffix.- human_message: The human message.+ human_message: The `HumanMessage`.format_instructions: The format instructions.input_variables: The input variables.@@ -142,7 +142,7 @@ class ChatAgent(Agent):output_parser: The output parser.system_message_prefix: The system message prefix.system_message_suffix: The system message suffix.- human_message: The human message.+ human_message: The `HumanMessage`.format_instructions: The format instructions.input_variables: The input variables.kwargs: Additional keyword arguments.diff --git a/libs/langchain/langchain_classic/agents/conversational_chat/base.py b/libs/langchain/langchain_classic/agents/conversational_chat/base.pyindex 0630ebba99..d0f1770701 100644--- a/libs/langchain/langchain_classic/agents/conversational_chat/base.py+++ b/libs/langchain/langchain_classic/agents/conversational_chat/base.py@@ -87,8 +87,8 @@ class ConversationalChatAgent(Agent):Args:tools: The tools to use.- system_message: The system message to use.- human_message: The human message to use.+ system_message: The `SystemMessage` to use.+ human_message: The `HumanMessage` to use.input_variables: The input variables to use.output_parser: The output parser to use.@@ -150,8 +150,8 @@ class ConversationalChatAgent(Agent):tools: A list of tools to use.callback_manager: The callback manager to use.output_parser: The output parser to use.- system_message: The system message to use.- human_message: The human message to use.+ system_message: The `SystemMessage` to use.+ human_message: The `HumanMessage` to use.input_variables: The input variables to use.**kwargs: Any additional arguments.diff --git a/libs/langchain/langchain_classic/indexes/vectorstore.py b/libs/langchain/langchain_classic/indexes/vectorstore.pyindex 040e895529..073091c2b2 100644--- a/libs/langchain/langchain_classic/indexes/vectorstore.py+++ b/libs/langchain/langchain_classic/indexes/vectorstore.py@@ -22,7 +22,7 @@ def _get_default_text_splitter() -> TextSplitter:class VectorStoreIndexWrapper(BaseModel):- """Wrapper around a vectorstore for easy access."""+ """Wrapper around a `VectorStore` for easy access."""vectorstore: VectorStore@@ -38,11 +38,11 @@ class VectorStoreIndexWrapper(BaseModel):retriever_kwargs: dict[str, Any] | None = None,**kwargs: Any,) -> str:- """Query the vectorstore using the provided LLM.+ """Query the `VectorStore` using the provided LLM.Args:question: The question or prompt to query.- llm: The language model to use. Must not be None.+ llm: The language model to use. Must not be `None`.retriever_kwargs: Optional keyword arguments for the retriever.**kwargs: Additional keyword arguments forwarded to the chain.@@ -73,11 +73,11 @@ class VectorStoreIndexWrapper(BaseModel):retriever_kwargs: dict[str, Any] | None = None,**kwargs: Any,) -> str:- """Asynchronously query the vectorstore using the provided LLM.+ """Asynchronously query the `VectorStore` using the provided LLM.Args:question: The question or prompt to query.- llm: The language model to use. Must not be None.+ llm: The language model to use. Must not be `None`.retriever_kwargs: Optional keyword arguments for the retriever.**kwargs: Additional keyword arguments forwarded to the chain.@@ -108,11 +108,11 @@ class VectorStoreIndexWrapper(BaseModel):retriever_kwargs: dict[str, Any] | None = None,**kwargs: Any,) -> dict:- """Query the vectorstore and retrieve the answer along with sources.+ """Query the `VectorStore` and retrieve the answer along with sources.Args:question: The question or prompt to query.- llm: The language model to use. Must not be None.+ llm: The language model to use. Must not be `None`.retriever_kwargs: Optional keyword arguments for the retriever.**kwargs: Additional keyword arguments forwarded to the chain.@@ -143,11 +143,11 @@ class VectorStoreIndexWrapper(BaseModel):retriever_kwargs: dict[str, Any] | None = None,**kwargs: Any,) -> dict:- """Asynchronously query the vectorstore and retrieve the answer and sources.+ """Asynchronously query the `VectorStore` and retrieve the answer and sources.Args:question: The question or prompt to query.- llm: The language model to use. Must not be None.+ llm: The language model to use. Must not be `None`.retriever_kwargs: Optional keyword arguments for the retriever.**kwargs: Additional keyword arguments forwarded to the chain.@@ -173,7 +173,7 @@ class VectorStoreIndexWrapper(BaseModel):def _get_in_memory_vectorstore() -> type[VectorStore]:- """Get the InMemoryVectorStore."""+ """Get the `InMemoryVectorStore`."""import warningstry:@@ -184,7 +184,7 @@ def _get_in_memory_vectorstore() -> type[VectorStore]:warnings.warn("Using InMemoryVectorStore as the default vectorstore.""This memory store won't persist data. You should explicitly"- "specify a vectorstore when using VectorstoreIndexCreator",+ "specify a VectorStore when using VectorstoreIndexCreator",stacklevel=3,)return InMemoryVectorStore@@ -206,7 +206,7 @@ class VectorstoreIndexCreator(BaseModel):)def from_loaders(self, loaders: list[BaseLoader]) -> VectorStoreIndexWrapper:- """Create a vectorstore index from a list of loaders.+ """Create a `VectorStore` index from a list of loaders.Args:loaders: A list of `BaseLoader` instances to load documents.@@ -220,7 +220,7 @@ class VectorstoreIndexCreator(BaseModel):return self.from_documents(docs)async def afrom_loaders(self, loaders: list[BaseLoader]) -> VectorStoreIndexWrapper:- """Asynchronously create a vectorstore index from a list of loaders.+ """Asynchronously create a `VectorStore` index from a list of loaders.Args:loaders: A list of `BaseLoader` instances to load documents.@@ -234,7 +234,7 @@ class VectorstoreIndexCreator(BaseModel):return await self.afrom_documents(docs)def from_documents(self, documents: list[Document]) -> VectorStoreIndexWrapper:- """Create a vectorstore index from a list of documents.+ """Create a `VectorStore` index from a list of documents.Args:documents: A list of `Document` objects.@@ -254,7 +254,7 @@ class VectorstoreIndexCreator(BaseModel):self,documents: list[Document],) -> VectorStoreIndexWrapper:- """Asynchronously create a vectorstore index from a list of documents.+ """Asynchronously create a `VectorStore` index from a list of documents.Args:documents: A list of `Document` objects.diff --git a/libs/langchain/langchain_classic/memory/vectorstore_token_buffer_memory.py b/libs/langchain/langchain_classic/memory/vectorstore_token_buffer_memory.pyindex dbbdc01c81..dcf97ac4fe 100644--- a/libs/langchain/langchain_classic/memory/vectorstore_token_buffer_memory.py+++ b/libs/langchain/langchain_classic/memory/vectorstore_token_buffer_memory.py@@ -2,8 +2,8 @@This implements a conversation memory in which the messages are stored in a memorybuffer up to a specified token limit. When the limit is exceeded, older messages are-saved to a vectorstore backing database. The vectorstore can be made persistent across-sessions.+saved to a `VectorStore` backing database. The `VectorStore` can be made persistent+across sessions."""import warnings@@ -53,13 +53,13 @@ class ConversationVectorStoreTokenBufferMemory(ConversationTokenBufferMemory):accepts the following additional argumentsretriever: (required) A VectorStoreRetriever object to use- as the vector backing store+ as the vector backing storesplit_chunk_size: (optional, 1000) Token chunk split size- for long messages generated by the AI+ for long messages generated by the AIprevious_history_template: (optional) Template used to format- the contents of the prompt history+ the contents of the prompt historyExample using ChromaDB:@@ -157,7 +157,7 @@ class ConversationVectorStoreTokenBufferMemory(ConversationTokenBufferMemory):def save_remainder(self) -> None:"""Save the remainder of the conversation buffer to the vector store.- Useful if you have made the vectorstore persistent, in which+ Useful if you have made the VectorStore persistent, in whichcase this can be called before the end of the session to store theremainder of the conversation."""diff --git a/libs/langchain/langchain_classic/retrievers/multi_vector.py b/libs/langchain/langchain_classic/retrievers/multi_vector.pyindex d603424f7a..1a569b7e13 100644--- a/libs/langchain/langchain_classic/retrievers/multi_vector.py+++ b/libs/langchain/langchain_classic/retrievers/multi_vector.py@@ -30,7 +30,7 @@ class MultiVectorRetriever(BaseRetriever):"""Retrieve from a set of multiple embeddings for the same document."""vectorstore: VectorStore- """The underlying vectorstore to use to store small chunks+ """The underlying `VectorStore` to use to store small chunksand their embedding vectors"""byte_store: ByteStore | None = None"""The lower-level backing storage layer for the parent documents"""@@ -86,7 +86,7 @@ class MultiVectorRetriever(BaseRetriever):else:sub_docs = self.vectorstore.similarity_search(query, **self.search_kwargs)- # We do this to maintain the order of the ids that are returned+ # We do this to maintain the order of the IDs that are returnedids = []for d in sub_docs:if self.id_key in d.metadata and d.metadata[self.id_key] not in ids:@@ -128,7 +128,7 @@ class MultiVectorRetriever(BaseRetriever):**self.search_kwargs,)- # We do this to maintain the order of the ids that are returned+ # We do this to maintain the order of the IDs that are returnedids = []for d in sub_docs:if self.id_key in d.metadata and d.metadata[self.id_key] not in ids:diff --git a/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py b/libs/langchain/langchain_classic/retrievers/parent_document_retriever.pyindex c7d57961ae..635f320f21 100644--- a/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py+++ b/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py@@ -21,7 +21,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):The ParentDocumentRetriever strikes that balance by splitting and storingsmall chunks of data. During retrieval, it first fetches the small chunks- but then looks up the parent ids for those chunks and returns those larger+ but then looks up the parent IDs for those chunks and returns those largerdocuments.Note that "parent document" refers to the document that a small chunk@@ -44,7 +44,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):child_splitter = RecursiveCharacterTextSplitter(chunk_size=400, add_start_index=True)- # The vectorstore to use to index the child chunks+ # The VectorStore to use to index the child chunksvectorstore = Chroma(embedding_function=OpenAIEmbeddings())# The storage layer for the parent documentsstore = InMemoryStore()@@ -85,7 +85,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):if ids is None:doc_ids = [str(uuid.uuid4()) for _ in documents]if not add_to_docstore:- msg = "If ids are not passed in, `add_to_docstore` MUST be True"+ msg = "If IDs are not passed in, `add_to_docstore` MUST be True"raise ValueError(msg)else:if len(documents) != len(ids):@@ -124,11 +124,11 @@ class ParentDocumentRetriever(MultiVectorRetriever):Args:documents: List of documents to add- ids: Optional list of ids for documents. If provided should be the same+ ids: Optional list of IDs for documents. If provided should be the samelength as the list of documents. Can be provided if parent documentsare already in the document store and you don't want to re-addto the docstore. If not provided, random UUIDs will be used as- ids.+ IDs.add_to_docstore: Boolean of whether to add documents to docstore.This can be false if and only if `ids` are provided. You may wantto set this to False if the documents are already in the docstore@@ -155,11 +155,11 @@ class ParentDocumentRetriever(MultiVectorRetriever):Args:documents: List of documents to add- ids: Optional list of ids for documents. If provided should be the same+ ids: Optional list of IDs for documents. If provided should be the samelength as the list of documents. Can be provided if parent documentsare already in the document store and you don't want to re-addto the docstore. If not provided, random UUIDs will be used as- ids.+ idIDss.add_to_docstore: Boolean of whether to add documents to docstore.This can be false if and only if `ids` are provided. You may wantto set this to False if the documents are already in the docstorediff --git a/libs/langchain/langchain_classic/retrievers/self_query/base.py b/libs/langchain/langchain_classic/retrievers/self_query/base.pyindex 624143dd18..152a7de694 100644--- a/libs/langchain/langchain_classic/retrievers/self_query/base.py+++ b/libs/langchain/langchain_classic/retrievers/self_query/base.py@@ -251,7 +251,7 @@ class SelfQueryRetriever(BaseRetriever):search_kwargs: dict = Field(default_factory=dict)"""Keyword arguments to pass in to the vector store search."""structured_query_translator: Visitor- """Translator for turning internal query language into vectorstore search params."""+ """Translator for turning internal query language into `VectorStore` search params.""" # noqa: E501verbose: bool = Falseuse_original_query: bool = False@@ -360,7 +360,7 @@ class SelfQueryRetriever(BaseRetriever):queried.metadata_field_info: Metadata field information for the documents.structured_query_translator: Optional translator for turning internal query- language into vectorstore search params.+ language into `VectorStore` search params.chain_kwargs: Additional keyword arguments for the query constructor.enable_limit: Whether to enable the limit operator.use_original_query: Whether to use the original query instead of the reviseddiff --git a/libs/langchain/langchain_classic/retrievers/time_weighted_retriever.py b/libs/langchain/langchain_classic/retrievers/time_weighted_retriever.pyindex ffed2d17e4..7cba23e4bd 100644--- a/libs/langchain/langchain_classic/retrievers/time_weighted_retriever.py+++ b/libs/langchain/langchain_classic/retrievers/time_weighted_retriever.py@@ -25,7 +25,7 @@ class TimeWeightedVectorStoreRetriever(BaseRetriever):"""vectorstore: VectorStore- """The vectorstore to store documents and determine salience."""+ """The `VectorStore` to store documents and determine salience."""search_kwargs: dict = Field(default_factory=lambda: {"k": 100})"""Keyword arguments to pass to the `VectorStore` similarity search."""@@ -35,7 +35,7 @@ class TimeWeightedVectorStoreRetriever(BaseRetriever):"""The memory_stream of documents to search through."""decay_rate: float = Field(default=0.01)- """The exponential decay factor used as (1.0-decay_rate)**(hrs_passed)."""+ """The exponential decay factor used as `(1.0-decay_rate)**(hrs_passed)`."""k: int = 4"""The maximum number of documents to retrieve in a given call."""diff --git a/libs/langchain/tests/unit_tests/indexes/test_indexing.py b/libs/langchain/tests/unit_tests/indexes/test_indexing.pyindex ebc87aee00..e3d5c85c37 100644--- a/libs/langchain/tests/unit_tests/indexes/test_indexing.py+++ b/libs/langchain/tests/unit_tests/indexes/test_indexing.py@@ -446,7 +446,7 @@ def test_incremental_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedindex(@@ -496,7 +496,7 @@ async def test_aincremental_fails_with_bad_source_ids(with pytest.raises(ValueError,- match="Source ids are required when cleanup mode is incremental or scoped_full",+ match="Source IDs are required when cleanup mode is incremental or scoped_full",):# Should raise an error because no source id function was specifiedawait aindex(diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.pyindex 80674bcd6b..67810e00a9 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.py@@ -392,7 +392,7 @@ class TestStateAndRuntime:result = agent.invoke({"messages": [HumanMessage("Test")]})assert len(state_values) == 1- assert state_values[0]["messages_count"] == 1 # Just the human message+ assert state_values[0]["messages_count"] == 1 # Just The HumanMessageassert result["messages"][1].content == "Response"def test_retry_with_state_tracking(self) -> None:diff --git a/libs/partners/mistralai/tests/unit_tests/test_chat_models.py b/libs/partners/mistralai/tests/unit_tests/test_chat_models.pyindex e70dfd5f75..724531694b 100644--- a/libs/partners/mistralai/tests/unit_tests/test_chat_models.py+++ b/libs/partners/mistralai/tests/unit_tests/test_chat_models.py@@ -349,4 +349,4 @@ def test_no_duplicate_tool_calls_when_multiple_tools() -> None:# Ensure there are no duplicate idsids = [tc.get("id") for tc in tool_calls if isinstance(tc, dict)]assert len(ids) == 2- assert len(set(ids)) == 2, f"Duplicate tool call ids found: {ids}"+ assert len(set(ids)) == 2, f"Duplicate tool call IDs found: {ids}"diff --git a/libs/standard-tests/langchain_tests/integration_tests/indexer.py b/libs/standard-tests/langchain_tests/integration_tests/indexer.pyindex a4b94c1ae8..7eddc450f7 100644--- a/libs/standard-tests/langchain_tests/integration_tests/indexer.py+++ b/libs/standard-tests/langchain_tests/integration_tests/indexer.py@@ -29,7 +29,7 @@ class DocumentIndexerTestSuite(ABC):"""Get the index."""def test_upsert_documents_has_no_ids(self, index: DocumentIndex) -> None:- """Verify that there is no parameter called ids in upsert."""+ """Verify that there is no parameter called IDs in upsert."""signature = inspect.signature(index.upsert)assert "ids" not in signature.parameters@@ -65,7 +65,7 @@ class DocumentIndexerTestSuite(ABC):)def test_upsert_some_ids(self, index: DocumentIndex) -> None:- """Test an upsert where some docs have ids and some don't."""+ """Test an upsert where some docs have IDs and some don't."""foo_uuid = str(uuid.UUID(int=7))documents = [Document(id=foo_uuid, page_content="foo", metadata={"id": 1}),@@ -219,7 +219,7 @@ class AsyncDocumentIndexTestSuite(ABC):"""Get the index."""async def test_upsert_documents_has_no_ids(self, index: DocumentIndex) -> None:- """Verify that there is not parameter called ids in upsert."""+ """Verify that there is not parameter called IDs in upsert."""signature = inspect.signature(index.upsert)assert "ids" not in signature.parameters@@ -255,7 +255,7 @@ class AsyncDocumentIndexTestSuite(ABC):)async def test_upsert_some_ids(self, index: DocumentIndex) -> None:- """Test an upsert where some docs have ids and some don't."""+ """Test an upsert where some docs have IDs and some don't."""foo_uuid = str(uuid.UUID(int=7))documents = [Document(id=foo_uuid, page_content="foo", metadata={"id": 1}),diff --git a/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py b/libs/standard-tests/langchain_tests/integration_tests/vectorstores.pyindex 786376550f..490648e565 100644--- a/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py+++ b/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py@@ -69,7 +69,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):class TestChromaStandard(VectorStoreIntegrationTests):@pytest.fixture()def vectorstore(self) -> Generator[VectorStore, None, None]: # type: ignore- \"\"\"Get an empty vectorstore for unit tests.\"\"\"+ \"\"\"Get an empty VectorStore for unit tests.\"\"\"store = Chroma(embedding_function=self.get_embeddings())try:yield store@@ -101,9 +101,9 @@ class VectorStoreIntegrationTests(BaseStandardTests):@abstractmethod@pytest.fixturedef vectorstore(self) -> VectorStore:- """Get the vectorstore class to test.+ """Get the VectorStore class to test.- The returned vectorstore should be empty.+ The returned VectorStore should be empty."""@property@@ -137,7 +137,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):)def test_vectorstore_is_empty(self, vectorstore: VectorStore) -> None:- """Test that the vectorstore is empty.+ """Test that the VectorStore is empty.??? note "Troubleshooting"@@ -185,7 +185,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):]def test_vectorstore_still_empty(self, vectorstore: VectorStore) -> None:- """Test that the vectorstore is still empty.+ """Test that the VectorStore is still empty.This test should follow a test that adds documents.@@ -204,7 +204,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):assert vectorstore.similarity_search("foo", k=1) == []def test_deleting_documents(self, vectorstore: VectorStore) -> None:- """Test deleting documents from the vectorstore.+ """Test deleting documents from the `VectorStore`.??? note "Troubleshooting"@@ -485,7 +485,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):)async def test_vectorstore_is_empty_async(self, vectorstore: VectorStore) -> None:- """Test that the vectorstore is empty.+ """Test that the VectorStore is empty.??? note "Troubleshooting"@@ -536,7 +536,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):async def test_vectorstore_still_empty_async(self, vectorstore: VectorStore) -> None:- """Test that the vectorstore is still empty.+ """Test that the VectorStore is still empty.This test should follow a test that adds documents.@@ -555,7 +555,7 @@ class VectorStoreIntegrationTests(BaseStandardTests):assert await vectorstore.asimilarity_search("foo", k=1) == []async def test_deleting_documents_async(self, vectorstore: VectorStore) -> None:- """Test deleting documents from the vectorstore.+ """Test deleting documents from the `VectorStore`.??? note "Troubleshooting"diff --git a/libs/text-splitters/langchain_text_splitters/base.py b/libs/text-splitters/langchain_text_splitters/base.pyindex 28a8004413..ed06b78a49 100644--- a/libs/text-splitters/langchain_text_splitters/base.py+++ b/libs/text-splitters/langchain_text_splitters/base.py@@ -341,9 +341,9 @@ class Tokenizer:tokens_per_chunk: int"""Maximum number of tokens per chunk"""decode: Callable[[list[int]], str]- """ Function to decode a list of token ids to a string"""+ """ Function to decode a list of token IDs to a string"""encode: Callable[[str], list[int]]- """ Function to encode a string to a list of token ids"""+ """ Function to encode a string to a list of token IDs"""def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> list[str]: