From d13823043d84754f9136137ab71ef5569d792102 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 8 Oct 2025 18:41:39 -0400 Subject: [PATCH] style: monorepo pass for refs (#33359) * Delete some double backticks previously used by Sphinx (not done everywhere yet) * Fix some code blocks / dropdowns Ignoring CLI CI for now --- libs/cli/langchain_cli/utils/packages.py | 2 +- libs/core/langchain_core/__init__.py | 2 +- .../langchain_core/_api/beta_decorator.py | 16 +- libs/core/langchain_core/_api/deprecation.py | 22 +- libs/core/langchain_core/_import_utils.py | 2 +- libs/core/langchain_core/agents.py | 2 +- libs/core/langchain_core/caches.py | 2 +- libs/core/langchain_core/callbacks/file.py | 40 +- libs/core/langchain_core/callbacks/manager.py | 145 +-- libs/core/langchain_core/callbacks/stdout.py | 14 +- .../document_loaders/langsmith.py | 20 +- libs/core/langchain_core/documents/base.py | 2 +- libs/core/langchain_core/exceptions.py | 6 +- libs/core/langchain_core/indexing/api.py | 22 +- libs/core/langchain_core/indexing/base.py | 24 +- .../langchain_core/language_models/_utils.py | 16 +- .../langchain_core/language_models/base.py | 22 +- .../language_models/chat_models.py | 45 +- .../langchain_core/language_models/llms.py | 2 +- libs/core/langchain_core/load/load.py | 30 +- libs/core/langchain_core/load/serializable.py | 5 +- libs/core/langchain_core/messages/ai.py | 10 +- libs/core/langchain_core/messages/base.py | 10 +- .../messages/block_translators/__init__.py | 20 +- libs/core/langchain_core/messages/content.py | 30 +- libs/core/langchain_core/messages/function.py | 6 +- libs/core/langchain_core/messages/human.py | 2 +- libs/core/langchain_core/messages/tool.py | 12 +- libs/core/langchain_core/messages/utils.py | 70 +- .../langchain_core/output_parsers/json.py | 6 +- .../output_parsers/openai_tools.py | 14 +- .../langchain_core/output_parsers/pydantic.py | 4 +- .../langchain_core/outputs/chat_generation.py | 20 +- .../core/langchain_core/outputs/llm_result.py | 4 +- libs/core/langchain_core/prompts/chat.py | 30 +- libs/core/langchain_core/prompts/dict.py | 2 +- libs/core/langchain_core/prompts/loading.py | 2 +- libs/core/langchain_core/prompts/message.py | 2 +- libs/core/langchain_core/prompts/prompt.py | 2 +- .../core/langchain_core/prompts/structured.py | 2 +- libs/core/langchain_core/rate_limiters.py | 24 +- libs/core/langchain_core/retrievers.py | 22 +- libs/core/langchain_core/runnables/base.py | 862 +++++++++--------- libs/core/langchain_core/runnables/branch.py | 6 +- libs/core/langchain_core/runnables/config.py | 18 +- .../langchain_core/runnables/configurable.py | 8 +- .../langchain_core/runnables/fallbacks.py | 2 +- libs/core/langchain_core/runnables/graph.py | 49 +- .../langchain_core/runnables/graph_mermaid.py | 12 +- .../langchain_core/runnables/graph_png.py | 8 +- libs/core/langchain_core/runnables/history.py | 22 +- libs/core/langchain_core/runnables/utils.py | 32 +- libs/core/langchain_core/stores.py | 4 +- libs/core/langchain_core/tools/base.py | 50 +- libs/core/langchain_core/tools/convert.py | 18 +- libs/core/langchain_core/tools/retriever.py | 2 +- libs/core/langchain_core/tools/simple.py | 6 +- libs/core/langchain_core/tools/structured.py | 12 +- libs/core/langchain_core/tracers/base.py | 40 +- libs/core/langchain_core/tracers/context.py | 12 +- libs/core/langchain_core/tracers/langchain.py | 8 +- .../core/langchain_core/tracers/log_stream.py | 2 +- libs/core/langchain_core/utils/aiter.py | 2 +- libs/core/langchain_core/utils/env.py | 4 +- .../langchain_core/utils/function_calling.py | 30 +- libs/core/langchain_core/utils/html.py | 4 +- libs/core/langchain_core/utils/input.py | 4 +- libs/core/langchain_core/utils/iter.py | 4 +- libs/core/langchain_core/utils/json.py | 2 +- libs/core/langchain_core/utils/json_schema.py | 4 +- libs/core/langchain_core/utils/pydantic.py | 6 +- libs/core/langchain_core/utils/utils.py | 12 +- libs/core/langchain_core/vectorstores/base.py | 4 +- .../langchain_core/vectorstores/in_memory.py | 2 +- .../prompts/__snapshots__/test_chat.ambr | 40 +- .../runnables/__snapshots__/test_graph.ambr | 20 +- .../__snapshots__/test_runnable.ambr | 160 ++-- .../langchain_classic/agents/agent.py | 10 +- .../agents/agent_iterator.py | 14 +- .../agents/agent_toolkits/vectorstore/base.py | 14 +- .../agents/conversational_chat/base.py | 4 +- .../agents/format_scratchpad/tools.py | 2 +- .../langchain_classic/agents/initialize.py | 14 +- .../agents/json_chat/base.py | 4 +- .../langchain_classic/agents/mrkl/base.py | 8 +- .../agents/openai_assistant/base.py | 4 +- .../agents/openai_functions_agent/base.py | 10 +- .../langchain_classic/agents/react/agent.py | 4 +- .../agents/structured_chat/base.py | 4 +- .../langchain_classic/agents/xml/base.py | 4 +- .../callbacks/streamlit/__init__.py | 8 +- .../langchain_classic/chains/base.py | 28 +- .../chains/combine_documents/reduce.py | 4 +- .../chains/constitutional_ai/base.py | 2 +- .../chains/conversational_retrieval/base.py | 6 +- .../langchain/langchain_classic/chains/llm.py | 2 +- .../chains/openai_functions/base.py | 2 +- .../chains/query_constructor/base.py | 6 +- .../langchain_classic/chains/router/base.py | 4 +- .../chains/sql_database/query.py | 4 +- .../chains/structured_output/base.py | 10 +- .../chains/summarize/chain.py | 14 +- .../langchain_classic/chat_models/base.py | 12 +- .../langchain_classic/embeddings/cache.py | 6 +- .../evaluation/exact_match/base.py | 6 +- .../output_parsers/structured.py | 4 +- .../document_compressors/cohere_rerank.py | 2 +- .../document_compressors/embeddings_filter.py | 2 +- .../document_compressors/listwise_rerank.py | 2 +- .../retrievers/parent_document_retriever.py | 2 +- .../tests/unit_tests/chat_models/test_base.py | 6 +- libs/langchain_v1/langchain/agents/factory.py | 10 +- .../agents/middleware/human_in_the_loop.py | 4 +- .../agents/middleware/model_call_limit.py | 4 +- .../langchain/agents/middleware/pii.py | 6 +- .../agents/middleware/summarization.py | 2 +- .../agents/middleware/tool_call_limit.py | 10 +- .../langchain/chat_models/base.py | 4 +- .../langchain/embeddings/cache.py | 6 +- .../langchain_v1/langchain/tools/tool_node.py | 8 +- .../chat_models/test_chat_models.py | 6 +- .../unit_tests/tools/test_on_tool_call.py | 4 +- .../langchain_anthropic/chat_models.py | 28 +- .../langchain_anthropic/output_parsers.py | 2 +- .../chroma/langchain_chroma/vectorstores.py | 36 +- .../langchain_deepseek/chat_models.py | 8 +- libs/partners/exa/langchain_exa/tools.py | 2 +- .../langchain_fireworks/chat_models.py | 12 +- .../groq/langchain_groq/chat_models.py | 8 +- .../chat_models/huggingface.py | 4 +- .../llms/huggingface_endpoint.py | 2 +- .../langchain_mistralai/chat_models.py | 12 +- .../ollama/langchain_ollama/__init__.py | 2 +- .../ollama/langchain_ollama/chat_models.py | 50 +- .../ollama/langchain_ollama/embeddings.py | 14 +- libs/partners/ollama/langchain_ollama/llms.py | 20 +- .../langchain_openai/chat_models/azure.py | 2 +- .../langchain_openai/chat_models/base.py | 136 ++- .../chat_models/test_responses_standard.py | 2 +- .../langchain_perplexity/chat_models.py | 6 +- .../prompty/langchain_prompty/utils.py | 20 +- .../langchain_qdrant/fastembed_sparse.py | 2 +- .../qdrant/langchain_qdrant/qdrant.py | 2 +- .../qdrant/langchain_qdrant/vectorstores.py | 28 +- .../partners/xai/langchain_xai/chat_models.py | 26 +- .../integration_tests/chat_models.py | 460 +++++----- .../integration_tests/retrievers.py | 28 +- .../integration_tests/vectorstores.py | 146 +-- .../langchain_tests/unit_tests/chat_models.py | 178 ++-- .../langchain_tests/unit_tests/embeddings.py | 6 +- libs/standard-tests/uv.lock | 2 +- .../langchain_text_splitters/html.py | 4 +- .../langchain_text_splitters/json.py | 2 +- .../langchain_text_splitters/markdown.py | 6 +- 154 files changed, 1871 insertions(+), 1883 deletions(-) diff --git a/libs/cli/langchain_cli/utils/packages.py b/libs/cli/langchain_cli/utils/packages.py index 4c61ed0f0fc..e649ffbed0f 100644 --- a/libs/cli/langchain_cli/utils/packages.py +++ b/libs/cli/langchain_cli/utils/packages.py @@ -13,7 +13,7 @@ def get_package_root(cwd: Path | None = None) -> Path: Args: cwd: The current working directory to start the search from. - If None, uses the current working directory of the process. + If `None`, uses the current working directory of the process. Returns: The path to the package root directory. diff --git a/libs/core/langchain_core/__init__.py b/libs/core/langchain_core/__init__.py index 22a3df95f1e..6694d36c3d7 100644 --- a/libs/core/langchain_core/__init__.py +++ b/libs/core/langchain_core/__init__.py @@ -1,4 +1,4 @@ -"""``langchain-core`` defines the base abstractions for the LangChain ecosystem. +"""`langchain-core` defines the base abstractions for the LangChain ecosystem. The interfaces for core components like chat models, LLMs, vector stores, retrievers, and more are defined here. The universal invocation protocol (Runnables) along with diff --git a/libs/core/langchain_core/_api/beta_decorator.py b/libs/core/langchain_core/_api/beta_decorator.py index 8d7a6b31f01..6c801f672ac 100644 --- a/libs/core/langchain_core/_api/beta_decorator.py +++ b/libs/core/langchain_core/_api/beta_decorator.py @@ -40,15 +40,15 @@ def beta( """Decorator to mark a function, a class, or a property as beta. When marking a classmethod, a staticmethod, or a property, the - ``@beta`` decorator should go *under* ``@classmethod`` and - ``@staticmethod`` (i.e., `beta` should directly decorate the - underlying callable), but *over* ``@property``. + `@beta` decorator should go *under* `@classmethod` and + `@staticmethod` (i.e., `beta` should directly decorate the + underlying callable), but *over* `@property`. - When marking a class ``C`` intended to be used as a base class in a - multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method - (if ``C`` instead inherited its ``__init__`` from its own base class, then - ``@beta`` would mess up ``__init__`` inheritance when installing its - own (annotation-emitting) ``C.__init__``). + When marking a class `C` intended to be used as a base class in a + multiple inheritance hierarchy, `C` *must* define an `__init__` method + (if `C` instead inherited its `__init__` from its own base class, then + `@beta` would mess up `__init__` inheritance when installing its + own (annotation-emitting) `C.__init__`). Args: message : str, optional diff --git a/libs/core/langchain_core/_api/deprecation.py b/libs/core/langchain_core/_api/deprecation.py index 55cc493f154..6abcc7a3965 100644 --- a/libs/core/langchain_core/_api/deprecation.py +++ b/libs/core/langchain_core/_api/deprecation.py @@ -82,15 +82,15 @@ def deprecated( """Decorator to mark a function, a class, or a property as deprecated. When deprecating a classmethod, a staticmethod, or a property, the - ``@deprecated`` decorator should go *under* ``@classmethod`` and - ``@staticmethod`` (i.e., `deprecated` should directly decorate the - underlying callable), but *over* ``@property``. + `@deprecated` decorator should go *under* `@classmethod` and + `@staticmethod` (i.e., `deprecated` should directly decorate the + underlying callable), but *over* `@property`. - When deprecating a class ``C`` intended to be used as a base class in a - multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method - (if ``C`` instead inherited its ``__init__`` from its own base class, then - ``@deprecated`` would mess up ``__init__`` inheritance when installing its - own (deprecation-emitting) ``C.__init__``). + When deprecating a class `C` intended to be used as a base class in a + multiple inheritance hierarchy, `C` *must* define an `__init__` method + (if `C` instead inherited its `__init__` from its own base class, then + `@deprecated` would mess up `__init__` inheritance when installing its + own (deprecation-emitting) `C.__init__`). Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to 'class' if decorating a class, 'attribute' if decorating a @@ -113,7 +113,7 @@ def deprecated( alternative_import: str, optional An alternative import that the user may use instead. pending : bool, optional - If True, uses a PendingDeprecationWarning instead of a + If `True`, uses a `PendingDeprecationWarning` instead of a DeprecationWarning. Cannot be used together with removal. obj_type : str, optional The object type being deprecated. @@ -372,7 +372,7 @@ def deprecated( components = [ _message, f"Use {_alternative} instead." if _alternative else "", - f"Use ``{_alternative_import}`` instead." if _alternative_import else "", + f"Use `{_alternative_import}` instead." if _alternative_import else "", _addendum, ] details = " ".join([component.strip() for component in components if component]) @@ -440,7 +440,7 @@ def warn_deprecated( alternative_import: An alternative import that the user may use instead. pending: - If True, uses a PendingDeprecationWarning instead of a + If `True`, uses a `PendingDeprecationWarning` instead of a DeprecationWarning. Cannot be used together with removal. obj_type: The object type being deprecated. diff --git a/libs/core/langchain_core/_import_utils.py b/libs/core/langchain_core/_import_utils.py index 01c2e97f42b..6225a655e1c 100644 --- a/libs/core/langchain_core/_import_utils.py +++ b/libs/core/langchain_core/_import_utils.py @@ -13,7 +13,7 @@ def import_attr( Args: attr_name: The name of the attribute to import. - module_name: The name of the module to import from. If None, the attribute + module_name: The name of the module to import from. If `None`, the attribute is imported from the package itself. package: The name of the package where the module is located. diff --git a/libs/core/langchain_core/agents.py b/libs/core/langchain_core/agents.py index dcd64c0f601..2d99d64150f 100644 --- a/libs/core/langchain_core/agents.py +++ b/libs/core/langchain_core/agents.py @@ -2,7 +2,7 @@ **ATTENTION** The schema definitions are provided for backwards compatibility. -!!! important +!!! warning New agents should be built using the [langgraph library](https://github.com/langchain-ai/langgraph), which provides a simpler and more flexible way to define agents. diff --git a/libs/core/langchain_core/caches.py b/libs/core/langchain_core/caches.py index 12bb1bd6fb2..7e8e03e0389 100644 --- a/libs/core/langchain_core/caches.py +++ b/libs/core/langchain_core/caches.py @@ -154,7 +154,7 @@ class InMemoryCache(BaseCache): Args: maxsize: The maximum number of items to store in the cache. - If None, the cache has no maximum size. + If `None`, the cache has no maximum size. If the cache exceeds the maximum size, the oldest items are removed. Default is None. diff --git a/libs/core/langchain_core/callbacks/file.py b/libs/core/langchain_core/callbacks/file.py index bdc12f5f548..f51f92c0e14 100644 --- a/libs/core/langchain_core/callbacks/file.py +++ b/libs/core/langchain_core/callbacks/file.py @@ -46,13 +46,13 @@ class FileCallbackHandler(BaseCallbackHandler): Args: filename: The file path to write to. - mode: The file open mode. Defaults to ``'a'`` (append). - color: Default color for text output. Defaults to ``None``. + mode: The file open mode. Defaults to `'a'` (append). + color: Default color for text output. Defaults to `None`. !!! note When not used as a context manager, a deprecation warning will be issued - on first use. The file will be opened immediately in ``__init__`` and closed - in ``__del__`` or when ``close()`` is called explicitly. + on first use. The file will be opened immediately in `__init__` and closed + in `__del__` or when `close()` is called explicitly. """ @@ -63,8 +63,8 @@ class FileCallbackHandler(BaseCallbackHandler): Args: filename: Path to the output file. - mode: File open mode (e.g., ``'w'``, ``'a'``, ``'x'``). Defaults to ``'a'``. - color: Default text color for output. Defaults to ``None``. + mode: File open mode (e.g., `'w'`, `'a'`, `'x'`). Defaults to `'a'`. + color: Default text color for output. Defaults to `None`. """ self.filename = filename @@ -84,7 +84,7 @@ class FileCallbackHandler(BaseCallbackHandler): The FileCallbackHandler instance. !!! note - The file is already opened in ``__init__``, so this just marks that + The file is already opened in `__init__`, so this just marks that the handler is being used as a context manager. """ @@ -131,9 +131,9 @@ class FileCallbackHandler(BaseCallbackHandler): Args: text: The text to write to the file. - color: Optional color for the text. Defaults to ``self.color``. - end: String appended after the text. Defaults to ``""``. - file: Optional file to write to. Defaults to ``self.file``. + color: Optional color for the text. Defaults to `self.color`. + end: String appended after the text. Defaults to `""`. + file: Optional file to write to. Defaults to `self.file`. Raises: RuntimeError: If the file is closed or not available. @@ -167,7 +167,7 @@ class FileCallbackHandler(BaseCallbackHandler): Args: serialized: The serialized chain information. inputs: The inputs to the chain. - **kwargs: Additional keyword arguments that may contain ``'name'``. + **kwargs: Additional keyword arguments that may contain `'name'`. """ name = ( @@ -196,8 +196,8 @@ class FileCallbackHandler(BaseCallbackHandler): Args: action: The agent action containing the log to write. - color: Color override for this specific output. If ``None``, uses - ``self.color``. + color: Color override for this specific output. If `None`, uses + `self.color`. **kwargs: Additional keyword arguments. """ @@ -216,8 +216,8 @@ class FileCallbackHandler(BaseCallbackHandler): Args: output: The tool output to write. - color: Color override for this specific output. If ``None``, uses - ``self.color``. + color: Color override for this specific output. If `None`, uses + `self.color`. observation_prefix: Optional prefix to write before the output. llm_prefix: Optional prefix to write after the output. **kwargs: Additional keyword arguments. @@ -237,9 +237,9 @@ class FileCallbackHandler(BaseCallbackHandler): Args: text: The text to write. - color: Color override for this specific output. If ``None``, uses - ``self.color``. - end: String appended after the text. Defaults to ``""``. + color: Color override for this specific output. If `None`, uses + `self.color`. + end: String appended after the text. Defaults to `""`. **kwargs: Additional keyword arguments. """ @@ -253,8 +253,8 @@ class FileCallbackHandler(BaseCallbackHandler): Args: finish: The agent finish object containing the log to write. - color: Color override for this specific output. If ``None``, uses - ``self.color``. + color: Color override for this specific output. If `None`, uses + `self.color`. **kwargs: Additional keyword arguments. """ diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.py index 72d4e5a79cd..d2e4754b633 100644 --- a/libs/core/langchain_core/callbacks/manager.py +++ b/libs/core/langchain_core/callbacks/manager.py @@ -80,21 +80,21 @@ def trace_as_chain_group( Args: group_name (str): The name of the chain group. callback_manager (CallbackManager, optional): The callback manager to use. - Defaults to None. + Defaults to `None`. inputs (dict[str, Any], optional): The inputs to the chain group. - Defaults to None. + Defaults to `None`. project_name (str, optional): The name of the project. - Defaults to None. + Defaults to `None`. example_id (str or UUID, optional): The ID of the example. - Defaults to None. + Defaults to `None`. run_id (UUID, optional): The ID of the run. tags (list[str], optional): The inheritable tags to apply to all runs. - Defaults to None. + Defaults to `None`. metadata (dict[str, Any], optional): The metadata to apply to all runs. - Defaults to None. + Defaults to `None`. !!! note - Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in + Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in LangSmith. Yields: @@ -164,24 +164,25 @@ async def atrace_as_chain_group( Args: group_name (str): The name of the chain group. callback_manager (AsyncCallbackManager, optional): The async callback manager - to use, which manages tracing and other callback behavior. Defaults to None. + to use, which manages tracing and other callback behavior. Defaults to + `None`. inputs (dict[str, Any], optional): The inputs to the chain group. - Defaults to None. + Defaults to `None`. project_name (str, optional): The name of the project. - Defaults to None. + Defaults to `None`. example_id (str or UUID, optional): The ID of the example. - Defaults to None. + Defaults to `None`. run_id (UUID, optional): The ID of the run. tags (list[str], optional): The inheritable tags to apply to all runs. - Defaults to None. + Defaults to `None`. metadata (dict[str, Any], optional): The metadata to apply to all runs. - Defaults to None. + Defaults to `None`. Yields: The async callback manager for the chain group. !!! note - Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in + Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in LangSmith. Example: @@ -259,11 +260,11 @@ def handle_event( """Generic event handler for CallbackManager. !!! note - This function is used by ``LangServe`` to handle events. + This function is used by `LangServe` to handle events. Args: handlers: The list of handlers that will handle the event. - event_name: The name of the event (e.g., ``'on_llm_start'``). + event_name: The name of the event (e.g., `'on_llm_start'`). ignore_condition_name: Name of the attribute defined on handler that if True will cause the handler to be skipped for the given event. *args: The arguments to pass to the event handler. @@ -423,14 +424,14 @@ async def ahandle_event( *args: Any, **kwargs: Any, ) -> None: - """Async generic event handler for ``AsyncCallbackManager``. + """Async generic event handler for `AsyncCallbackManager`. !!! note - This function is used by ``LangServe`` to handle events. + This function is used by `LangServe` to handle events. Args: handlers: The list of handlers that will handle the event. - event_name: The name of the event (e.g., ``'on_llm_start'``). + event_name: The name of the event (e.g., `'on_llm_start'`). ignore_condition_name: Name of the attribute defined on handler that if True will cause the handler to be skipped for the given event. *args: The arguments to pass to the event handler. @@ -479,14 +480,14 @@ class BaseRunManager(RunManagerMixin): inheritable_handlers (list[BaseCallbackHandler]): The list of inheritable handlers. parent_run_id (UUID, optional): The ID of the parent run. - Defaults to None. - tags (Optional[list[str]]): The list of tags. Defaults to None. + Defaults to `None`. + tags (Optional[list[str]]): The list of tags. Defaults to `None`. inheritable_tags (Optional[list[str]]): The list of inheritable tags. - Defaults to None. + Defaults to `None`. metadata (Optional[dict[str, Any]]): The metadata. - Defaults to None. + Defaults to `None`. inheritable_metadata (Optional[dict[str, Any]]): The inheritable metadata. - Defaults to None. + Defaults to `None`. """ self.run_id = run_id @@ -578,7 +579,7 @@ class ParentRunManager(RunManager): Args: tag (str, optional): The tag for the child callback manager. - Defaults to None. + Defaults to `None`. Returns: CallbackManager: The child callback manager. @@ -663,7 +664,7 @@ class AsyncParentRunManager(AsyncRunManager): Args: tag (str, optional): The tag for the child callback manager. - Defaults to None. + Defaults to `None`. Returns: AsyncCallbackManager: The child callback manager. @@ -693,7 +694,7 @@ class CallbackManagerForLLMRun(RunManager, LLMManagerMixin): Args: token (str): The new token. chunk (Optional[Union[GenerationChunk, ChatGenerationChunk]], optional): - The chunk. Defaults to None. + The chunk. Defaults to `None`. **kwargs (Any): Additional keyword arguments. """ @@ -792,7 +793,7 @@ class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin): Args: token (str): The new token. chunk (Optional[Union[GenerationChunk, ChatGenerationChunk]], optional): - The chunk. Defaults to None. + The chunk. Defaults to `None`. **kwargs (Any): Additional keyword arguments. """ @@ -1327,7 +1328,7 @@ class CallbackManager(BaseCallbackManager): Args: serialized (dict[str, Any]): The serialized LLM. prompts (list[str]): The list of prompts. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1379,7 +1380,7 @@ class CallbackManager(BaseCallbackManager): Args: serialized (dict[str, Any]): The serialized LLM. messages (list[list[BaseMessage]]): The list of messages. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1434,7 +1435,7 @@ class CallbackManager(BaseCallbackManager): Args: serialized (Optional[dict[str, Any]]): The serialized chain. inputs (Union[dict[str, Any], Any]): The inputs to the chain. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1483,8 +1484,8 @@ class CallbackManager(BaseCallbackManager): serialized: Serialized representation of the tool. input_str: The input to the tool as a string. Non-string inputs are cast to strings. - run_id: ID for the run. Defaults to None. - parent_run_id: The ID of the parent run. Defaults to None. + run_id: ID for the run. Defaults to `None`. + parent_run_id: The ID of the parent run. Defaults to `None`. inputs: The original input to the tool if provided. Recommended for usage instead of input_str when the original input is needed. @@ -1538,8 +1539,9 @@ class CallbackManager(BaseCallbackManager): Args: serialized (Optional[dict[str, Any]]): The serialized retriever. query (str): The query. - run_id (UUID, optional): The ID of the run. Defaults to None. - parent_run_id (UUID, optional): The ID of the parent run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. + parent_run_id (UUID, optional): The ID of the parent run. Defaults to + `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1588,7 +1590,7 @@ class CallbackManager(BaseCallbackManager): Args: name: The name of the adhoc event. data: The data for the adhoc event. - run_id: The ID of the run. Defaults to None. + run_id: The ID of the run. Defaults to `None`. Raises: ValueError: If additional keyword arguments are passed. @@ -1634,18 +1636,19 @@ class CallbackManager(BaseCallbackManager): Args: inheritable_callbacks (Optional[Callbacks], optional): The inheritable - callbacks. Defaults to None. + callbacks. Defaults to `None`. local_callbacks (Optional[Callbacks], optional): The local callbacks. - Defaults to None. - verbose (bool, optional): Whether to enable verbose mode. Defaults to False. + Defaults to `None`. + verbose (bool, optional): Whether to enable verbose mode. Defaults to + `False`. inheritable_tags (Optional[list[str]], optional): The inheritable tags. - Defaults to None. + Defaults to `None`. local_tags (Optional[list[str]], optional): The local tags. - Defaults to None. + Defaults to `None`. inheritable_metadata (Optional[dict[str, Any]], optional): The inheritable - metadata. Defaults to None. + metadata. Defaults to `None`. local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to None. + Defaults to `None`. Returns: CallbackManager: The configured callback manager. @@ -1680,8 +1683,9 @@ class CallbackManagerForChainGroup(CallbackManager): Args: handlers (list[BaseCallbackHandler]): The list of handlers. inheritable_handlers (Optional[list[BaseCallbackHandler]]): The list of - inheritable handlers. Defaults to None. - parent_run_id (Optional[UUID]): The ID of the parent run. Defaults to None. + inheritable handlers. Defaults to `None`. + parent_run_id (Optional[UUID]): The ID of the parent run. Defaults to + `None`. parent_run_manager (CallbackManagerForChainRun): The parent run manager. **kwargs (Any): Additional keyword arguments. @@ -1821,7 +1825,7 @@ class AsyncCallbackManager(BaseCallbackManager): Args: serialized (dict[str, Any]): The serialized LLM. prompts (list[str]): The list of prompts. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1910,7 +1914,7 @@ class AsyncCallbackManager(BaseCallbackManager): Args: serialized (dict[str, Any]): The serialized LLM. messages (list[list[BaseMessage]]): The list of messages. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -1982,7 +1986,7 @@ class AsyncCallbackManager(BaseCallbackManager): Args: serialized (Optional[dict[str, Any]]): The serialized chain. inputs (Union[dict[str, Any], Any]): The inputs to the chain. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -2030,9 +2034,9 @@ class AsyncCallbackManager(BaseCallbackManager): Args: serialized (Optional[dict[str, Any]]): The serialized tool. input_str (str): The input to the tool. - run_id (UUID, optional): The ID of the run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. parent_run_id (UUID, optional): The ID of the parent run. - Defaults to None. + Defaults to `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -2082,7 +2086,7 @@ class AsyncCallbackManager(BaseCallbackManager): Args: name: The name of the adhoc event. data: The data for the adhoc event. - run_id: The ID of the run. Defaults to None. + run_id: The ID of the run. Defaults to `None`. Raises: ValueError: If additional keyword arguments are passed. @@ -2126,8 +2130,9 @@ class AsyncCallbackManager(BaseCallbackManager): Args: serialized (Optional[dict[str, Any]]): The serialized retriever. query (str): The query. - run_id (UUID, optional): The ID of the run. Defaults to None. - parent_run_id (UUID, optional): The ID of the parent run. Defaults to None. + run_id (UUID, optional): The ID of the run. Defaults to `None`. + parent_run_id (UUID, optional): The ID of the parent run. Defaults to + `None`. **kwargs (Any): Additional keyword arguments. Returns: @@ -2176,18 +2181,19 @@ class AsyncCallbackManager(BaseCallbackManager): Args: inheritable_callbacks (Optional[Callbacks], optional): The inheritable - callbacks. Defaults to None. + callbacks. Defaults to `None`. local_callbacks (Optional[Callbacks], optional): The local callbacks. - Defaults to None. - verbose (bool, optional): Whether to enable verbose mode. Defaults to False. + Defaults to `None`. + verbose (bool, optional): Whether to enable verbose mode. Defaults to + `False`. inheritable_tags (Optional[list[str]], optional): The inheritable tags. - Defaults to None. + Defaults to `None`. local_tags (Optional[list[str]], optional): The local tags. - Defaults to None. + Defaults to `None`. inheritable_metadata (Optional[dict[str, Any]], optional): The inheritable - metadata. Defaults to None. + metadata. Defaults to `None`. local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to None. + Defaults to `None`. Returns: AsyncCallbackManager: The configured async callback manager. @@ -2221,8 +2227,9 @@ class AsyncCallbackManagerForChainGroup(AsyncCallbackManager): Args: handlers (list[BaseCallbackHandler]): The list of handlers. inheritable_handlers (Optional[list[BaseCallbackHandler]]): The list of - inheritable handlers. Defaults to None. - parent_run_id (Optional[UUID]): The ID of the parent run. Defaults to None. + inheritable handlers. Defaults to `None`. + parent_run_id (Optional[UUID]): The ID of the parent run. Defaults to + `None`. parent_run_manager (AsyncCallbackManagerForChainRun): The parent run manager. **kwargs (Any): Additional keyword arguments. @@ -2359,17 +2366,17 @@ def _configure( Args: callback_manager_cls (Type[T]): The callback manager class. inheritable_callbacks (Optional[Callbacks], optional): The inheritable - callbacks. Defaults to None. + callbacks. Defaults to `None`. local_callbacks (Optional[Callbacks], optional): The local callbacks. - Defaults to None. - verbose (bool, optional): Whether to enable verbose mode. Defaults to False. + Defaults to `None`. + verbose (bool, optional): Whether to enable verbose mode. Defaults to `False`. inheritable_tags (Optional[list[str]], optional): The inheritable tags. - Defaults to None. - local_tags (Optional[list[str]], optional): The local tags. Defaults to None. + Defaults to `None`. + local_tags (Optional[list[str]], optional): The local tags. Defaults to `None`. inheritable_metadata (Optional[dict[str, Any]], optional): The inheritable - metadata. Defaults to None. + metadata. Defaults to `None`. local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to None. + Defaults to `None`. Raises: RuntimeError: If `LANGCHAIN_TRACING` is set but `LANGCHAIN_TRACING_V2` is not. diff --git a/libs/core/langchain_core/callbacks/stdout.py b/libs/core/langchain_core/callbacks/stdout.py index e240cd9f245..c2b4b973ff5 100644 --- a/libs/core/langchain_core/callbacks/stdout.py +++ b/libs/core/langchain_core/callbacks/stdout.py @@ -20,7 +20,7 @@ class StdOutCallbackHandler(BaseCallbackHandler): """Initialize callback handler. Args: - color: The color to use for the text. Defaults to None. + color: The color to use for the text. Defaults to `None`. """ self.color = color @@ -61,7 +61,7 @@ class StdOutCallbackHandler(BaseCallbackHandler): Args: action (AgentAction): The agent action. - color (Optional[str]): The color to use for the text. Defaults to None. + color (Optional[str]): The color to use for the text. Defaults to `None`. **kwargs (Any): Additional keyword arguments. """ print_text(action.log, color=color or self.color) @@ -79,10 +79,10 @@ class StdOutCallbackHandler(BaseCallbackHandler): Args: output (Any): The output to print. - color (Optional[str]): The color to use for the text. Defaults to None. + color (Optional[str]): The color to use for the text. Defaults to `None`. observation_prefix (Optional[str]): The observation prefix. - Defaults to None. - llm_prefix (Optional[str]): The LLM prefix. Defaults to None. + Defaults to `None`. + llm_prefix (Optional[str]): The LLM prefix. Defaults to `None`. **kwargs (Any): Additional keyword arguments. """ output = str(output) @@ -104,7 +104,7 @@ class StdOutCallbackHandler(BaseCallbackHandler): Args: text (str): The text to print. - color (Optional[str]): The color to use for the text. Defaults to None. + color (Optional[str]): The color to use for the text. Defaults to `None`. end (str): The end character to use. Defaults to "". **kwargs (Any): Additional keyword arguments. """ @@ -118,7 +118,7 @@ class StdOutCallbackHandler(BaseCallbackHandler): Args: finish (AgentFinish): The agent finish. - color (Optional[str]): The color to use for the text. Defaults to None. + color (Optional[str]): The color to use for the text. Defaults to `None`. **kwargs (Any): Additional keyword arguments. """ print_text(finish.log, color=color or self.color, end="\n") diff --git a/libs/core/langchain_core/document_loaders/langsmith.py b/libs/core/langchain_core/document_loaders/langsmith.py index 0c55791dc7c..9cdacb7aeb8 100644 --- a/libs/core/langchain_core/document_loaders/langsmith.py +++ b/libs/core/langchain_core/document_loaders/langsmith.py @@ -60,15 +60,15 @@ class LangSmithLoader(BaseLoader): """Create a LangSmith loader. Args: - dataset_id: The ID of the dataset to filter by. Defaults to None. - dataset_name: The name of the dataset to filter by. Defaults to None. - content_key: The inputs key to set as Document page content. ``'.'`` characters - are interpreted as nested keys. E.g. ``content_key="first.second"`` will + dataset_id: The ID of the dataset to filter by. Defaults to `None`. + dataset_name: The name of the dataset to filter by. Defaults to `None`. + content_key: The inputs key to set as Document page content. `'.'` characters + are interpreted as nested keys. E.g. `content_key="first.second"` will result in - ``Document(page_content=format_content(example.inputs["first"]["second"]))`` + `Document(page_content=format_content(example.inputs["first"]["second"]))` format_content: Function for converting the content extracted from the example inputs into a string. Defaults to JSON-encoding the contents. - example_ids: The IDs of the examples to filter by. Defaults to None. + example_ids: The IDs of the examples to filter by. Defaults to `None`. as_of: The dataset version tag OR timestamp to retrieve the examples as of. Response examples will only be those that were present at the time @@ -76,17 +76,17 @@ class LangSmithLoader(BaseLoader): splits: A list of dataset splits, which are divisions of your dataset such as 'train', 'test', or 'validation'. Returns examples only from the specified splits. - inline_s3_urls: Whether to inline S3 URLs. Defaults to True. + inline_s3_urls: Whether to inline S3 URLs. Defaults to `True`. offset: The offset to start from. Defaults to 0. limit: The maximum number of examples to return. - metadata: Metadata to filter by. Defaults to None. + metadata: Metadata to filter by. Defaults to `None`. filter: A structured filter string to apply to the examples. client: LangSmith Client. If not provided will be initialized from below args. client_kwargs: Keyword args to pass to LangSmith client init. Should only be - specified if ``client`` isn't. + specified if `client` isn't. Raises: - ValueError: If both ``client`` and ``client_kwargs`` are provided. + ValueError: If both `client` and `client_kwargs` are provided. """ # noqa: E501 if client and client_kwargs: raise ValueError diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.py index 1a14218ca42..347076f114f 100644 --- a/libs/core/langchain_core/documents/base.py +++ b/libs/core/langchain_core/documents/base.py @@ -215,7 +215,7 @@ class Blob(BaseMedia): path: path like object to file to be read encoding: Encoding to use if decoding the bytes into a string mime_type: if provided, will be set as the mime-type of the data - guess_type: If True, the mimetype will be guessed from the file extension, + guess_type: If `True`, the mimetype will be guessed from the file extension, if a mime-type was not provided metadata: Metadata to associate with the blob diff --git a/libs/core/langchain_core/exceptions.py b/libs/core/langchain_core/exceptions.py index 6816a395dc7..30260ca12b4 100644 --- a/libs/core/langchain_core/exceptions.py +++ b/libs/core/langchain_core/exceptions.py @@ -33,15 +33,15 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818 Args: error: The error that's being re-raised or an error message. observation: String explanation of error which can be passed to a - model to try and remediate the issue. Defaults to None. + model to try and remediate the issue. Defaults to `None`. llm_output: String model output which is error-ing. - Defaults to None. + Defaults to `None`. send_to_llm: Whether to send the observation and llm_output back to an Agent after an OutputParserException has been raised. This gives the underlying model driving the agent the context that the previous output was improperly structured, in the hopes that it will update the output to the correct format. - Defaults to False. + Defaults to `False`. Raises: ValueError: If ``send_to_llm`` is True but either observation or diff --git a/libs/core/langchain_core/indexing/api.py b/libs/core/langchain_core/indexing/api.py index 2b5fe719ae6..4ef3776d123 100644 --- a/libs/core/langchain_core/indexing/api.py +++ b/libs/core/langchain_core/indexing/api.py @@ -299,9 +299,9 @@ def index( are not able to specify the uid of the document. !!! warning "Behavior changed in 0.3.25" - Added ``scoped_full`` cleanup mode. + Added `scoped_full` cleanup mode. - !!! important + !!! warning * In full mode, the loader should be returning the entire dataset, and not just a subset of the dataset. @@ -315,7 +315,7 @@ def index( 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 + * 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 @@ -381,8 +381,8 @@ def index( ValueError: If vectorstore does not have "delete" and "add_documents" required methods. ValueError: If source_id_key is not None, but is not a string or callable. - TypeError: If ``vectorstore`` is not a VectorStore or a DocumentIndex. - AssertionError: If ``source_id`` is None when cleanup mode is incremental. + TypeError: If `vectorstore` is not a VectorStore or a DocumentIndex. + AssertionError: If `source_id` is None when cleanup mode is incremental. (should be unreachable code). """ # Behavior is deprecated, but we keep it for backwards compatibility. @@ -640,9 +640,9 @@ async def aindex( are not able to specify the uid of the document. !!! warning "Behavior changed in 0.3.25" - Added ``scoped_full`` cleanup mode. + Added `scoped_full` cleanup mode. - !!! important + !!! warning * In full mode, the loader should be returning the entire dataset, and not just a subset of the dataset. @@ -656,7 +656,7 @@ async def aindex( 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 + * 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 @@ -722,9 +722,9 @@ async def aindex( ValueError: If vectorstore does not have "adelete" and "aadd_documents" required methods. ValueError: If source_id_key is not None, but is not a string or callable. - TypeError: If ``vector_store`` is not a VectorStore or DocumentIndex. - AssertionError: If ``source_id_key`` is None when cleanup mode is - incremental or ``scoped_full`` (should be unreachable). + TypeError: If `vector_store` is not a VectorStore or DocumentIndex. + AssertionError: If `source_id_key` is None when cleanup mode is + incremental or `scoped_full` (should be unreachable). """ # Behavior is deprecated, but we keep it for backwards compatibility. # # Warn only once per process. diff --git a/libs/core/langchain_core/indexing/base.py b/libs/core/langchain_core/indexing/base.py index 8fd56170e5d..ad9aecb7d90 100644 --- a/libs/core/langchain_core/indexing/base.py +++ b/libs/core/langchain_core/indexing/base.py @@ -278,10 +278,10 @@ class InMemoryRecordManager(RecordManager): Args: keys: A list of record keys to upsert. group_ids: A list of group IDs corresponding to the keys. - Defaults to None. + Defaults to `None`. time_at_least: Optional timestamp. Implementation can use this to optionally verify that the timestamp IS at least this time - in the system that stores. Defaults to None. + in the system that stores. Defaults to `None`. E.g., use to validate that the time in the postgres database is equal to or larger than the given timestamp, if not raise an error. @@ -315,10 +315,10 @@ class InMemoryRecordManager(RecordManager): Args: keys: A list of record keys to upsert. group_ids: A list of group IDs corresponding to the keys. - Defaults to None. + Defaults to `None`. time_at_least: Optional timestamp. Implementation can use this to optionally verify that the timestamp IS at least this time - in the system that stores. Defaults to None. + in the system that stores. Defaults to `None`. E.g., use to validate that the time in the postgres database is equal to or larger than the given timestamp, if not raise an error. @@ -361,13 +361,13 @@ class InMemoryRecordManager(RecordManager): Args: before: Filter to list records updated before this time. - Defaults to None. + Defaults to `None`. after: Filter to list records updated after this time. - Defaults to None. + Defaults to `None`. group_ids: Filter to list records with specific group IDs. - Defaults to None. + Defaults to `None`. limit: optional limit on the number of records to return. - Defaults to None. + Defaults to `None`. Returns: A list of keys for the matching records. @@ -397,13 +397,13 @@ class InMemoryRecordManager(RecordManager): Args: before: Filter to list records updated before this time. - Defaults to None. + Defaults to `None`. after: Filter to list records updated after this time. - Defaults to None. + Defaults to `None`. group_ids: Filter to list records with specific group IDs. - Defaults to None. + Defaults to `None`. limit: optional limit on the number of records to return. - Defaults to None. + Defaults to `None`. Returns: A list of keys for the matching records. diff --git a/libs/core/langchain_core/language_models/_utils.py b/libs/core/langchain_core/language_models/_utils.py index d7e7ebffc4b..8f66693a412 100644 --- a/libs/core/langchain_core/language_models/_utils.py +++ b/libs/core/langchain_core/language_models/_utils.py @@ -19,7 +19,7 @@ def is_openai_data_block( ) -> bool: """Check whether a block contains multimodal data in OpenAI Chat Completions format. - Supports both data and ID-style blocks (e.g. ``'file_data'`` and ``'file_id'``) + Supports both data and ID-style blocks (e.g. `'file_data'` and `'file_id'`) If additional keys are present, they are ignored / will not affect outcome as long as the required keys are present and valid. @@ -30,7 +30,7 @@ def is_openai_data_block( - "image": Only match image_url blocks - "audio": Only match input_audio blocks - "file": Only match file blocks - If None, match any valid OpenAI data block type. Note that this means that + If `None`, match any valid OpenAI data block type. Note that this means that if the block has a valid OpenAI data type but the filter_ is set to a different type, this function will return False. @@ -133,8 +133,8 @@ def _normalize_messages( - LangChain v1 standard content blocks This function extends support to: - - `Audio `__ and - `file `__ data in OpenAI + - `[Audio](https://platform.openai.com/docs/api-reference/chat/create) and + `[file](https://platform.openai.com/docs/api-reference/files) data in OpenAI Chat Completions format - Images are technically supported but we expect chat models to handle them directly; this may change in the future @@ -148,7 +148,7 @@ def _normalize_messages( ??? note "v0 Content Block Schemas" - ``URLContentBlock``: + `URLContentBlock`: .. codeblock:: @@ -159,7 +159,7 @@ def _normalize_messages( url: str, } - ``Base64ContentBlock``: + `Base64ContentBlock`: .. codeblock:: @@ -170,7 +170,7 @@ def _normalize_messages( data: str, } - ``IDContentBlock``: + `IDContentBlock`: (In practice, this was never used) @@ -182,7 +182,7 @@ def _normalize_messages( id: str, } - ``PlainTextContentBlock``: + `PlainTextContentBlock`: .. codeblock:: diff --git a/libs/core/langchain_core/language_models/base.py b/libs/core/langchain_core/language_models/base.py index 460716c1a43..726c7aee6b0 100644 --- a/libs/core/langchain_core/language_models/base.py +++ b/libs/core/langchain_core/language_models/base.py @@ -110,17 +110,17 @@ class BaseLanguageModel( ): """Abstract base class for interfacing with language models. - All language model wrappers inherited from ``BaseLanguageModel``. + All language model wrappers inherited from `BaseLanguageModel`. """ cache: BaseCache | bool | None = Field(default=None, exclude=True) """Whether to cache the response. - * If true, will use the global cache. - * If false, will not use a cache - * If None, will use the global cache if it's set, otherwise no cache. - * If instance of ``BaseCache``, will use the provided cache. + * If `True`, will use the global cache. + * If `False`, will not use a cache + * If `None`, will use the global cache if it's set, otherwise no cache. + * If instance of `BaseCache`, will use the provided cache. Caching is not currently supported for streaming methods of models. @@ -144,7 +144,7 @@ class BaseLanguageModel( @field_validator("verbose", mode="before") def set_verbose(cls, verbose: bool | None) -> bool: # noqa: FBT001 - """If verbose is None, set it. + """If verbose is `None`, set it. This allows users to pass in None as verbose to access the global setting. @@ -162,7 +162,7 @@ class BaseLanguageModel( @property @override def InputType(self) -> TypeAlias: - """Get the input type for this runnable.""" + """Get the input type for this `Runnable`.""" # This is a version of LanguageModelInput which replaces the abstract # base class BaseMessage with a union of its subclasses, which makes # for a much better schema. @@ -237,7 +237,7 @@ class BaseLanguageModel( to the model provider API call. Returns: - An ``LLMResult``, which contains a list of candidate Generations for each + An `LLMResult`, which contains a list of candidate Generations for each input prompt and additional model provider-specific output. """ @@ -294,13 +294,13 @@ class BaseLanguageModel( Useful for checking if an input fits in a model's context window. !!! note - The base implementation of ``get_num_tokens_from_messages`` ignores tool + The base implementation of `get_num_tokens_from_messages` ignores tool schemas. Args: messages: The message inputs to tokenize. - tools: If provided, sequence of dict, ``BaseModel``, function, or - ``BaseTools`` to be converted to tool schemas. + tools: If provided, sequence of dict, `BaseModel`, function, or + `BaseTool` objects to be converted to tool schemas. Returns: The sum of the number of tokens across the messages. diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py index 817d34caaae..6994fa41cc2 100644 --- a/libs/core/langchain_core/language_models/chat_models.py +++ b/libs/core/langchain_core/language_models/chat_models.py @@ -112,7 +112,7 @@ def _format_for_tracing(messages: list[BaseMessage]) -> list[BaseMessage]: - Update image content blocks to OpenAI Chat Completions format (backward compatibility). - - Add ``type`` key to content blocks that have a single key. + - Add `type` key to content blocks that have a single key. Args: messages: List of messages to format. @@ -179,7 +179,7 @@ def generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult: """Generate from a stream. Args: - stream: Iterator of ``ChatGenerationChunk``. + stream: Iterator of `ChatGenerationChunk`. Raises: ValueError: If no generations are found in the stream. @@ -210,7 +210,7 @@ async def agenerate_from_stream( """Async generate from a stream. Args: - stream: Iterator of ``ChatGenerationChunk``. + stream: Iterator of `ChatGenerationChunk`. Returns: ChatResult: Chat result. @@ -322,38 +322,37 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): disable_streaming: bool | Literal["tool_calling"] = False """Whether to disable streaming for this model. - If streaming is bypassed, then ``stream()``/``astream()``/``astream_events()`` will - defer to ``invoke()``/``ainvoke()``. + If streaming is bypassed, then `stream`/`astream`/`astream_events` will + defer to `invoke`/`ainvoke`. - - If True, will always bypass streaming case. - - If ``'tool_calling'``, will bypass streaming case only when the model is called - with a ``tools`` keyword argument. In other words, LangChain will automatically - switch to non-streaming behavior (``invoke()``) only when the tools argument is + - If `True`, will always bypass streaming case. + - If `'tool_calling'`, will bypass streaming case only when the model is called + with a `tools` keyword argument. In other words, LangChain will automatically + switch to non-streaming behavior (`invoke`) only when the tools argument is provided. This offers the best of both worlds. - - If False (default), will always use streaming case if available. + - If `False` (Default), will always use streaming case if available. - The main reason for this flag is that code might be written using ``stream()`` and + The main reason for this flag is that code might be written using `stream` and a user may want to swap out a given model for another model whose the implementation does not properly support streaming. - """ output_version: str | None = Field( default_factory=from_env("LC_OUTPUT_VERSION", default=None) ) - """Version of ``AIMessage`` output format to store in message content. + """Version of `AIMessage` output format to store in message content. - ``AIMessage.content_blocks`` will lazily parse the contents of ``content`` into a + `AIMessage.content_blocks` will lazily parse the contents of ``content`` into a standard format. This flag can be used to additionally store the standard format in message content, e.g., for serialization purposes. Supported values: - - ``"v0"``: provider-specific format in content (can lazily-parse with - ``.content_blocks``) - - ``"v1"``: standardized format in content (consistent with ``.content_blocks``) + - `'v0'`: provider-specific format in content (can lazily-parse with + `.content_blocks`) + - `'v1'`: standardized format in content (consistent with `.content_blocks`) - Partner packages (e.g., ``langchain-openai``) can also use this field to roll out + Partner packages (e.g., `langchain-openai`) can also use this field to roll out new content formats in a backward-compatible way. !!! version-added "Added in version 1.0" @@ -373,7 +372,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): @property @override def OutputType(self) -> Any: - """Get the output type for this runnable.""" + """Get the output type for this `Runnable`.""" return AnyMessage def _convert_input(self, model_input: LanguageModelInput) -> PromptValue: @@ -1529,7 +1528,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class, + - a `TypedDict` class, - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -1537,11 +1536,11 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.py index 26ca47b74a0..61654405748 100644 --- a/libs/core/langchain_core/language_models/llms.py +++ b/libs/core/langchain_core/language_models/llms.py @@ -299,7 +299,7 @@ class BaseLLM(BaseLanguageModel[str], ABC): @property @override def OutputType(self) -> type[str]: - """Get the input type for this runnable.""" + """Get the input type for this `Runnable`.""" return str def _convert_input(self, model_input: LanguageModelInput) -> PromptValue: diff --git a/libs/core/langchain_core/load/load.py b/libs/core/langchain_core/load/load.py index c288c4e8977..c31af9ae55f 100644 --- a/libs/core/langchain_core/load/load.py +++ b/libs/core/langchain_core/load/load.py @@ -63,16 +63,16 @@ class Reviver: Args: secrets_map: A map of secrets to load. If a secret is not found in the map, it will be loaded from the environment if `secrets_from_env` - is True. Defaults to None. + is True. Defaults to `None`. valid_namespaces: A list of additional namespaces (modules) - to allow to be deserialized. Defaults to None. + to allow to be deserialized. Defaults to `None`. secrets_from_env: Whether to load secrets from the environment. - Defaults to True. + Defaults to `True`. additional_import_mappings: A dictionary of additional namespace mappings You can use this to override default mappings or add new mappings. - Defaults to None. + Defaults to `None`. ignore_unserializable_fields: Whether to ignore unserializable fields. - Defaults to False. + Defaults to `False`. """ self.secrets_from_env = secrets_from_env self.secrets_map = secrets_map or {} @@ -200,16 +200,16 @@ def loads( text: The string to load. secrets_map: A map of secrets to load. If a secret is not found in the map, it will be loaded from the environment if `secrets_from_env` - is True. Defaults to None. + is True. Defaults to `None`. valid_namespaces: A list of additional namespaces (modules) - to allow to be deserialized. Defaults to None. + to allow to be deserialized. Defaults to `None`. secrets_from_env: Whether to load secrets from the environment. - Defaults to True. + Defaults to `True`. additional_import_mappings: A dictionary of additional namespace mappings You can use this to override default mappings or add new mappings. - Defaults to None. + Defaults to `None`. ignore_unserializable_fields: Whether to ignore unserializable fields. - Defaults to False. + Defaults to `False`. Returns: Revived LangChain objects. @@ -245,16 +245,16 @@ def load( obj: The object to load. secrets_map: A map of secrets to load. If a secret is not found in the map, it will be loaded from the environment if `secrets_from_env` - is True. Defaults to None. + is True. Defaults to `None`. valid_namespaces: A list of additional namespaces (modules) - to allow to be deserialized. Defaults to None. + to allow to be deserialized. Defaults to `None`. secrets_from_env: Whether to load secrets from the environment. - Defaults to True. + Defaults to `True`. additional_import_mappings: A dictionary of additional namespace mappings You can use this to override default mappings or add new mappings. - Defaults to None. + Defaults to `None`. ignore_unserializable_fields: Whether to ignore unserializable fields. - Defaults to False. + Defaults to `False`. Returns: Revived LangChain objects. diff --git a/libs/core/langchain_core/load/serializable.py b/libs/core/langchain_core/load/serializable.py index 55c7ce927a5..2d7dab470a0 100644 --- a/libs/core/langchain_core/load/serializable.py +++ b/libs/core/langchain_core/load/serializable.py @@ -92,7 +92,7 @@ class Serializable(BaseModel, ABC): It relies on the following methods and properties: - - ``is_lc_serializable``: Is this class serializable? + - `is_lc_serializable`: Is this class serializable? By design, even if a class inherits from Serializable, it is not serializable by default. This is to prevent accidental serialization of objects that should not be serialized. @@ -161,8 +161,9 @@ class Serializable(BaseModel, ABC): The unique identifier is a list of strings that describes the path to the object. + For example, for the class `langchain.llms.openai.OpenAI`, the id is - ["langchain", "llms", "openai", "OpenAI"]. + `["langchain", "llms", "openai", "OpenAI"]`. """ # Pydantic generics change the class name. So we need to do the following if ( diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.py index c96f4586775..39187e34ecc 100644 --- a/libs/core/langchain_core/messages/ai.py +++ b/libs/core/langchain_core/messages/ai.py @@ -122,7 +122,7 @@ class UsageMetadata(TypedDict): } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. """ @@ -191,7 +191,7 @@ class AIMessage(BaseMessage): content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: - """Initialize ``AIMessage``. + """Initialize `AIMessage`. Specify ``content`` as positional arg or ``content_blocks`` for typing. @@ -229,7 +229,7 @@ class AIMessage(BaseMessage): If the message has a known model provider, use the provider-specific translator first before falling back to best-effort parsing. For details, see the property - on ``BaseMessage``. + on `BaseMessage`. """ if self.response_metadata.get("output_version") == "v1": return cast("list[types.ContentBlock]", self.content) @@ -335,7 +335,7 @@ class AIMessage(BaseMessage): Args: html: Whether to return an HTML-formatted string. - Defaults to False. + Defaults to `False`. Returns: A pretty representation of the message. @@ -391,7 +391,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk): """Optional span represented by an aggregated AIMessageChunk. If a chunk with ``chunk_position="last"`` is aggregated into a stream, - ``tool_call_chunks`` in message content will be parsed into ``tool_calls``. + ``tool_call_chunks`` in message content will be parsed into `tool_calls`. """ @property diff --git a/libs/core/langchain_core/messages/base.py b/libs/core/langchain_core/messages/base.py index 1df5b375b47..8d45f89a88d 100644 --- a/libs/core/langchain_core/messages/base.py +++ b/libs/core/langchain_core/messages/base.py @@ -159,7 +159,7 @@ class BaseMessage(Serializable): content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: - """Initialize ``BaseMessage``. + """Initialize `BaseMessage`. Specify ``content`` as positional arg or ``content_blocks`` for typing. @@ -175,7 +175,7 @@ class BaseMessage(Serializable): @classmethod def is_lc_serializable(cls) -> bool: - """``BaseMessage`` is serializable. + """`BaseMessage` is serializable. Returns: True @@ -306,7 +306,7 @@ class BaseMessage(Serializable): """Get a pretty representation of the message. Args: - html: Whether to format the message as HTML. If True, the message will be + html: Whether to format the message as HTML. If `True`, the message will be formatted with HTML tags. Default is False. Returns: @@ -439,7 +439,7 @@ def message_to_dict(message: BaseMessage) -> dict: message: Message to convert. Returns: - Message as a dict. The dict will have a ``type`` key with the message type + Message as a dict. The dict will have a `type` key with the message type and a ``data`` key with the message data as a dict. """ @@ -450,7 +450,7 @@ def messages_to_dict(messages: Sequence[BaseMessage]) -> list[dict]: """Convert a sequence of Messages to a list of dictionaries. Args: - messages: Sequence of messages (as ``BaseMessage``s) to convert. + messages: Sequence of messages (as `BaseMessage`s) to convert. Returns: List of messages as dicts. diff --git a/libs/core/langchain_core/messages/block_translators/__init__.py b/libs/core/langchain_core/messages/block_translators/__init__.py index 90156154e7a..4bbb95a4bf7 100644 --- a/libs/core/langchain_core/messages/block_translators/__init__.py +++ b/libs/core/langchain_core/messages/block_translators/__init__.py @@ -1,13 +1,13 @@ """Derivations of standard content blocks from provider content. -``AIMessage`` will first attempt to use a provider-specific translator if -``model_provider`` is set in ``response_metadata`` on the message. Consequently, each +`AIMessage` will first attempt to use a provider-specific translator if +``model_provider`` is set in `response_metadata` on the message. Consequently, each provider translator must handle all possible content response types from the provider, including text. If no provider is set, or if the provider does not have a registered translator, -``AIMessage`` will fall back to best-effort parsing of the content into blocks using -the implementation in ``BaseMessage``. +`AIMessage` will fall back to best-effort parsing of the content into blocks using +the implementation in `BaseMessage`. """ from __future__ import annotations @@ -25,13 +25,13 @@ PROVIDER_TRANSLATORS: dict[str, dict[str, Callable[..., list[types.ContentBlock] The dictionary maps provider names (e.g. ``'openai'``, ``'anthropic'``) to another dictionary with two keys: -- ``'translate_content'``: Function to translate ``AIMessage`` content. +- ``'translate_content'``: Function to translate `AIMessage` content. - ``'translate_content_chunk'``: Function to translate ``AIMessageChunk`` content. -When calling `.content_blocks` on an ``AIMessage`` or ``AIMessageChunk``, if -``model_provider`` is set in ``response_metadata``, the corresponding translator +When calling `.content_blocks` on an `AIMessage` or ``AIMessageChunk``, if +``model_provider`` is set in `response_metadata`, the corresponding translator functions will be used to parse the content into blocks. Otherwise, best-effort parsing -in ``BaseMessage`` will be used. +in `BaseMessage` will be used. """ @@ -44,7 +44,7 @@ def register_translator( Args: provider: The model provider name (e.g. ``'openai'``, ``'anthropic'``). - translate_content: Function to translate ``AIMessage`` content. + translate_content: Function to translate `AIMessage` content. translate_content_chunk: Function to translate ``AIMessageChunk`` content. """ PROVIDER_TRANSLATORS[provider] = { @@ -64,7 +64,7 @@ def get_translator( Returns: Dictionary with ``'translate_content'`` and ``'translate_content_chunk'`` functions, or None if no translator is registered for the provider. In such - case, best-effort parsing in ``BaseMessage`` will be used. + case, best-effort parsing in `BaseMessage` will be used. """ return PROVIDER_TRANSLATORS.get(provider) diff --git a/libs/core/langchain_core/messages/content.py b/libs/core/langchain_core/messages/content.py index abe633d9ab8..73af80721b4 100644 --- a/libs/core/langchain_core/messages/content.py +++ b/libs/core/langchain_core/messages/content.py @@ -125,7 +125,7 @@ The module defines several types of content blocks, including: Factory functions offer benefits such as: - Automatic ID generation (when not provided) -- No need to manually specify the ``type`` field +- No need to manually specify the `type` field """ @@ -305,7 +305,7 @@ class ToolCallChunk(TypedDict): When merging ``ToolCallChunks`` (e.g., via ``AIMessageChunk.__add__``), all string attributes are concatenated. Chunks are only merged if their - values of ``index`` are equal and not ``None``. + values of ``index`` are equal and not `None`. Example: @@ -350,7 +350,7 @@ class ToolCallChunk(TypedDict): class InvalidToolCall(TypedDict): """Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) """ @@ -641,8 +641,8 @@ class PlainTextContentBlock(TypedDict): !!! note A ``PlainTextContentBlock`` existed in ``langchain-core<1.0.0``. Although the name has carried over, the structure has changed significantly. The only shared - keys between the old and new versions are ``type`` and ``text``, though the - ``type`` value has changed from ``'text'`` to ``'text-plain'``. + keys between the old and new versions are `type` and ``text``, though the + `type` value has changed from ``'text'`` to ``'text-plain'``. !!! note Title and context are optional fields that may be passed to the model. See @@ -935,7 +935,7 @@ def create_text_block( A properly formatted ``TextContentBlock``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -984,7 +984,7 @@ def create_image_block( ``mime_type``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1040,7 +1040,7 @@ def create_video_block( ``mime_type``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1100,7 +1100,7 @@ def create_audio_block( ``mime_type``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1160,7 +1160,7 @@ def create_file_block( ``mime_type``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1219,7 +1219,7 @@ def create_plaintext_block( A properly formatted ``PlainTextContentBlock``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1271,7 +1271,7 @@ def create_tool_call( A properly formatted ``ToolCall``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1309,7 +1309,7 @@ def create_reasoning_block( A properly formatted ``ReasoningContentBlock``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1353,7 +1353,7 @@ def create_citation( A properly formatted ``Citation``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ @@ -1394,7 +1394,7 @@ def create_non_standard_block( A properly formatted ``NonStandardContentBlock``. !!! note - The ``id`` is generated automatically if not provided, using a UUID4 format + The `id` is generated automatically if not provided, using a UUID4 format prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID. """ diff --git a/libs/core/langchain_core/messages/function.py b/libs/core/langchain_core/messages/function.py index 770806ffb22..86406e7bc9e 100644 --- a/libs/core/langchain_core/messages/function.py +++ b/libs/core/langchain_core/messages/function.py @@ -15,10 +15,10 @@ from langchain_core.utils._merge import merge_dicts class FunctionMessage(BaseMessage): """Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. diff --git a/libs/core/langchain_core/messages/human.py b/libs/core/langchain_core/messages/human.py index aa7b71796d6..d3106a0f62b 100644 --- a/libs/core/langchain_core/messages/human.py +++ b/libs/core/langchain_core/messages/human.py @@ -9,7 +9,7 @@ from langchain_core.messages.base import BaseMessage, BaseMessageChunk class HumanMessage(BaseMessage): """Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: diff --git a/libs/core/langchain_core/messages/tool.py b/libs/core/langchain_core/messages/tool.py index 5d2ef8fe88b..0d0a2382b99 100644 --- a/libs/core/langchain_core/messages/tool.py +++ b/libs/core/langchain_core/messages/tool.py @@ -18,7 +18,7 @@ class ToolOutputMixin: If a custom BaseTool is invoked with a ``ToolCall`` and the output of custom code is not an instance of ``ToolOutputMixin``, the output will automatically be coerced to - a string and wrapped in a ``ToolMessage``. + a string and wrapped in a `ToolMessage`. """ @@ -26,10 +26,10 @@ class ToolOutputMixin: class ToolMessage(BaseMessage, ToolOutputMixin): """Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -38,7 +38,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin): ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -60,7 +60,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin): tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. @@ -165,7 +165,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin): content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: - """Initialize ``ToolMessage``. + """Initialize `ToolMessage`. Specify ``content`` as positional arg or ``content_blocks`` for typing. diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py index 422f6af3eca..304b12b4743 100644 --- a/libs/core/langchain_core/messages/utils.py +++ b/libs/core/langchain_core/messages/utils.py @@ -96,9 +96,9 @@ def get_buffer_string( Args: messages: Messages to be converted to strings. - human_prefix: The prefix to prepend to contents of ``HumanMessage``s. + human_prefix: The prefix to prepend to contents of `HumanMessage`s. Default is ``'Human'``. - ai_prefix: The prefix to prepend to contents of ``AIMessage``. Default is + ai_prefix: The prefix to prepend to contents of `AIMessage`. Default is ``'AI'``. Returns: @@ -312,7 +312,7 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage: The message format can be one of the following: - ``BaseMessagePromptTemplate`` - - ``BaseMessage`` + - `BaseMessage` - 2-tuple of (role string, template); e.g., (``'human'``, ``'{user_input}'``) - dict: a message dict with role and content keys - string: shorthand for (``'human'``, template); e.g., ``'{user_input}'`` @@ -423,31 +423,31 @@ def filter_messages( exclude_ids: Sequence[str] | None = None, exclude_tool_calls: Sequence[str] | bool | None = None, ) -> list[BaseMessage]: - """Filter messages based on ``name``, ``type`` or ``id``. + """Filter messages based on `name`, `type` or `id`. Args: messages: Sequence Message-like objects to filter. include_names: Message names to include. Default is None. exclude_names: Messages names to exclude. Default is None. include_types: Message types to include. Can be specified as string names - (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as ``BaseMessage`` - classes (e.g. ``SystemMessage``, ``HumanMessage``, ``AIMessage``, ...). + (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as `BaseMessage` + classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Default is None. exclude_types: Message types to exclude. Can be specified as string names - (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as ``BaseMessage`` - classes (e.g. ``SystemMessage``, ``HumanMessage``, ``AIMessage``, ...). + (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as `BaseMessage` + classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Default is None. include_ids: Message IDs to include. Default is None. exclude_ids: Message IDs to exclude. Default is None. exclude_tool_calls: Tool call IDs to exclude. Default is None. Can be one of the following: - - ``True``: all ``AIMessage``s with tool calls and all - ``ToolMessage``s will be excluded. + - `True`: all `AIMessage`s with tool calls and all + `ToolMessage` objects will be excluded. - a sequence of tool call IDs to exclude: - - ``ToolMessage``s with the corresponding tool call ID will be + - `ToolMessage` objects with the corresponding tool call ID will be excluded. - - The ``tool_calls`` in the AIMessage will be updated to exclude - matching tool calls. If all ``tool_calls`` are filtered from an + - The `tool_calls` in the AIMessage will be updated to exclude + matching tool calls. If all `tool_calls` are filtered from an AIMessage, the whole message is excluded. Returns: @@ -565,8 +565,8 @@ def merge_message_runs( r"""Merge consecutive Messages of the same type. !!! note - ToolMessages are not merged, as each has a distinct tool call id that can't be - merged. + `ToolMessage` objects are not merged, as each has a distinct tool call id that + can't be merged. Args: messages: Sequence Message-like objects to merge. @@ -714,17 +714,17 @@ def trim_messages( properties: 1. The resulting chat history should be valid. Most chat models expect that chat - history starts with either (1) a ``HumanMessage`` or (2) a ``SystemMessage`` - followed by a ``HumanMessage``. To achieve this, set ``start_on='human'``. - In addition, generally a ``ToolMessage`` can only appear after an ``AIMessage`` + history starts with either (1) a `HumanMessage` or (2) a `SystemMessage` + followed by a `HumanMessage`. To achieve this, set ``start_on='human'``. + In addition, generally a `ToolMessage` can only appear after an `AIMessage` that involved a tool call. Please see the following link for more information about messages: https://python.langchain.com/docs/concepts/#messages 2. It includes recent messages and drops old messages in the chat history. To achieve this set the ``strategy='last'``. - 3. Usually, the new chat history should include the ``SystemMessage`` if it - was present in the original chat history since the ``SystemMessage`` includes - special instructions to the chat model. The ``SystemMessage`` is almost always + 3. Usually, the new chat history should include the `SystemMessage` if it + was present in the original chat history since the `SystemMessage` includes + special instructions to the chat model. The `SystemMessage` is almost always the first message in the history if present. To achieve this set the ``include_system=True``. @@ -735,8 +735,8 @@ def trim_messages( Args: messages: Sequence of Message-like objects to trim. max_tokens: Max token count of trimmed messages. - token_counter: Function or llm for counting tokens in a ``BaseMessage`` or a - list of ``BaseMessage``. If a ``BaseLanguageModel`` is passed in then + token_counter: Function or llm for counting tokens in a `BaseMessage` or a + list of `BaseMessage`. If a `BaseLanguageModel` is passed in then ``BaseLanguageModel.get_num_tokens_from_messages()`` will be used. Set to ``len`` to count the number of **messages** in the chat history. @@ -760,18 +760,18 @@ def trim_messages( is done before we attempt to get the last ``max_tokens``. If ``strategy='first'`` then this is done after we get the first ``max_tokens``. Can be specified as string names (e.g. ``'system'``, - ``'human'``, ``'ai'``, ...) or as ``BaseMessage`` classes (e.g. - ``SystemMessage``, ``HumanMessage``, ``AIMessage``, ...). Can be a single + ``'human'``, ``'ai'``, ...) or as `BaseMessage` classes (e.g. + `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Can be a single type or a list of types. Default is None. start_on: The message type to start on. Should only be specified if ``strategy='last'``. If specified then every message before the first occurrence of this type is ignored. This is done after we trim the initial messages to the last ``max_tokens``. Does not - apply to a ``SystemMessage`` at index 0 if ``include_system=True``. Can be + apply to a `SystemMessage` at index 0 if ``include_system=True``. Can be specified as string names (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or - as ``BaseMessage`` classes (e.g. ``SystemMessage``, ``HumanMessage``, - ``AIMessage``, ...). Can be a single type or a list of types. + as `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`, + `AIMessage`, ...). Can be a single type or a list of types. Default is None. include_system: Whether to keep the SystemMessage if there is one at index 0. Should only be specified if ``strategy="last"``. @@ -786,16 +786,16 @@ def trim_messages( newlines. Returns: - list of trimmed ``BaseMessage``. + list of trimmed `BaseMessage`. Raises: ValueError: if two incompatible arguments are specified or an unrecognized ``strategy`` is specified. Example: - Trim chat history based on token count, keeping the ``SystemMessage`` if - present, and ensuring that the chat history starts with a ``HumanMessage`` ( - or a ``SystemMessage`` followed by a ``HumanMessage``). + Trim chat history based on token count, keeping the `SystemMessage` if + present, and ensuring that the chat history starts with a `HumanMessage` ( + or a `SystemMessage` followed by a `HumanMessage`). .. code-block:: python @@ -850,9 +850,9 @@ def trim_messages( HumanMessage(content="what do you call a speechless parrot"), ] - Trim chat history based on the message count, keeping the ``SystemMessage`` if - present, and ensuring that the chat history starts with a ``HumanMessage`` ( - or a ``SystemMessage`` followed by a ``HumanMessage``). + Trim chat history based on the message count, keeping the `SystemMessage` if + present, and ensuring that the chat history starts with a `HumanMessage` ( + or a `SystemMessage` followed by a `HumanMessage`). trim_messages( messages, diff --git a/libs/core/langchain_core/output_parsers/json.py b/libs/core/langchain_core/output_parsers/json.py index 3fb7499591b..d665c33b48f 100644 --- a/libs/core/langchain_core/output_parsers/json.py +++ b/libs/core/langchain_core/output_parsers/json.py @@ -40,7 +40,7 @@ class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]): pydantic_object: Annotated[type[TBaseModel] | None, SkipValidation()] = None # type: ignore[valid-type] """The Pydantic object to use for validation. - If None, no validation is performed.""" + If `None`, no validation is performed.""" @override def _diff(self, prev: Any | None, next: Any) -> Any: @@ -59,9 +59,9 @@ class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]): Args: result: The result of the LLM call. partial: Whether to parse partial JSON objects. - If True, the output will be a JSON object containing + If `True`, the output will be a JSON object containing all the keys that have been returned so far. - If False, the output will be the full JSON object. + If `False`, the output will be the full JSON object. Default is False. Returns: diff --git a/libs/core/langchain_core/output_parsers/openai_tools.py b/libs/core/langchain_core/output_parsers/openai_tools.py index 084b1273a3b..5f44b916ae2 100644 --- a/libs/core/langchain_core/output_parsers/openai_tools.py +++ b/libs/core/langchain_core/output_parsers/openai_tools.py @@ -148,7 +148,7 @@ class JsonOutputToolsParser(BaseCumulativeTransformOutputParser[Any]): first_tool_only: bool = False """Whether to return only the first tool call. - If False, the result will be a list of tool calls, or an empty list + If `False`, the result will be a list of tool calls, or an empty list if no tool calls are found. If true, and multiple tool calls are found, only the first one will be returned, @@ -162,9 +162,9 @@ class JsonOutputToolsParser(BaseCumulativeTransformOutputParser[Any]): Args: result: The result of the LLM call. partial: Whether to parse partial JSON. - If True, the output will be a JSON object containing + If `True`, the output will be a JSON object containing all the keys that have been returned so far. - If False, the output will be the full JSON object. + If `False`, the output will be the full JSON object. Default is False. Returns: @@ -226,9 +226,9 @@ class JsonOutputKeyToolsParser(JsonOutputToolsParser): Args: result: The result of the LLM call. partial: Whether to parse partial JSON. - If True, the output will be a JSON object containing + If `True`, the output will be a JSON object containing all the keys that have been returned so far. - If False, the output will be the full JSON object. + If `False`, the output will be the full JSON object. Default is False. Raises: @@ -310,9 +310,9 @@ class PydanticToolsParser(JsonOutputToolsParser): Args: result: The result of the LLM call. partial: Whether to parse partial JSON. - If True, the output will be a JSON object containing + If `True`, the output will be a JSON object containing all the keys that have been returned so far. - If False, the output will be the full JSON object. + If `False`, the output will be the full JSON object. Default is False. Returns: diff --git a/libs/core/langchain_core/output_parsers/pydantic.py b/libs/core/langchain_core/output_parsers/pydantic.py index cc6190eb7ba..13eee343cd2 100644 --- a/libs/core/langchain_core/output_parsers/pydantic.py +++ b/libs/core/langchain_core/output_parsers/pydantic.py @@ -50,9 +50,9 @@ class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]): Args: result: The result of the LLM call. partial: Whether to parse partial JSON objects. - If True, the output will be a JSON object containing + If `True`, the output will be a JSON object containing all the keys that have been returned so far. - Defaults to False. + Defaults to `False`. Raises: OutputParserException: If the result is not valid JSON diff --git a/libs/core/langchain_core/outputs/chat_generation.py b/libs/core/langchain_core/outputs/chat_generation.py index 9955d576593..a0887c65e3b 100644 --- a/libs/core/langchain_core/outputs/chat_generation.py +++ b/libs/core/langchain_core/outputs/chat_generation.py @@ -19,10 +19,10 @@ class ChatGeneration(Generation): that generates chat messages. The ``message`` attribute is a structured representation of the chat message. - Most of the time, the message will be of type ``AIMessage``. + Most of the time, the message will be of type `AIMessage`. Users working with chat models will usually access information via either - ``AIMessage`` (returned from runnable interfaces) or ``LLMResult`` (available + `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via callbacks). """ @@ -84,18 +84,18 @@ class ChatGenerationChunk(ChatGeneration): def __add__( self, other: ChatGenerationChunk | list[ChatGenerationChunk] ) -> ChatGenerationChunk: - """Concatenate two ``ChatGenerationChunk``s. + """Concatenate two `ChatGenerationChunk`s. Args: - other: The other ``ChatGenerationChunk`` or list of ``ChatGenerationChunk`` + other: The other `ChatGenerationChunk` or list of `ChatGenerationChunk` to concatenate. Raises: - TypeError: If other is not a ``ChatGenerationChunk`` or list of - ``ChatGenerationChunk``. + TypeError: If other is not a `ChatGenerationChunk` or list of + `ChatGenerationChunk`. Returns: - A new ``ChatGenerationChunk`` concatenated from self and other. + A new `ChatGenerationChunk` concatenated from self and other. """ if isinstance(other, ChatGenerationChunk): generation_info = merge_dicts( @@ -124,13 +124,13 @@ class ChatGenerationChunk(ChatGeneration): def merge_chat_generation_chunks( chunks: list[ChatGenerationChunk], ) -> ChatGenerationChunk | None: - """Merge a list of ``ChatGenerationChunk``s into a single ``ChatGenerationChunk``. + """Merge a list of `ChatGenerationChunk`s into a single `ChatGenerationChunk`. Args: - chunks: A list of ``ChatGenerationChunk`` to merge. + chunks: A list of `ChatGenerationChunk` to merge. Returns: - A merged ``ChatGenerationChunk``, or None if the input list is empty. + A merged `ChatGenerationChunk`, or None if the input list is empty. """ if not chunks: return None diff --git a/libs/core/langchain_core/outputs/llm_result.py b/libs/core/langchain_core/outputs/llm_result.py index b0bfad33d01..fa6782a5a5e 100644 --- a/libs/core/langchain_core/outputs/llm_result.py +++ b/libs/core/langchain_core/outputs/llm_result.py @@ -91,10 +91,10 @@ class LLMResult(BaseModel): return llm_results def __eq__(self, other: object) -> bool: - """Check for ``LLMResult`` equality by ignoring any metadata related to runs. + """Check for `LLMResult` equality by ignoring any metadata related to runs. Args: - other: Another ``LLMResult`` object to compare against. + other: Another `LLMResult` object to compare against. Returns: True if the generations and ``llm_output`` are equal, False otherwise. diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.py index 3ff97de2fbb..ef89fde2043 100644 --- a/libs/core/langchain_core/prompts/chat.py +++ b/libs/core/langchain_core/prompts/chat.py @@ -130,13 +130,13 @@ class MessagesPlaceholder(BaseMessagePromptTemplate): """Name of variable to use as messages.""" optional: bool = False - """If True format_messages can be called with no arguments and will return an empty - list. If False then a named argument with name `variable_name` must be passed - in, even if the value is an empty list.""" + """If `True` format_messages can be called with no arguments and will return an + empty list. If `False` then a named argument with name `variable_name` must be + passed in, even if the value is an empty list.""" n_messages: PositiveInt | None = None - """Maximum number of messages to include. If None, then will include all. - Defaults to None.""" + """Maximum number of messages to include. If `None`, then will include all. + Defaults to `None`.""" def __init__( self, variable_name: str, *, optional: bool = False, **kwargs: Any @@ -145,10 +145,10 @@ class MessagesPlaceholder(BaseMessagePromptTemplate): Args: variable_name: Name of variable to use as messages. - optional: If True format_messages can be called with no arguments and will - return an empty list. If False then a named argument with name + optional: If `True` format_messages can be called with no arguments and will + return an empty list. If `False` then a named argument with name `variable_name` must be passed in, even if the value is an empty list. - Defaults to False.] + Defaults to `False`.] """ # mypy can't detect the init which is defined in the parent class # b/c these are BaseModel classes. @@ -196,7 +196,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. @@ -242,7 +242,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): `"{variable1} {variable2}"`, and `partial_variables` is `{"variable1": "foo"}`, then the final prompt will be `"foo {variable2}"`. - Defaults to None. + Defaults to `None`. **kwargs: keyword arguments to pass to the constructor. Returns: @@ -331,7 +331,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. @@ -415,7 +415,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate): template_format: format of the template. Options are: 'f-string', 'mustache', 'jinja2'. Defaults to "f-string". partial_variables: A dictionary of variables that can be used too partially. - Defaults to None. + Defaults to `None`. **kwargs: keyword arguments to pass to the constructor. Returns: @@ -638,7 +638,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. @@ -751,7 +751,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. @@ -1293,7 +1293,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. diff --git a/libs/core/langchain_core/prompts/dict.py b/libs/core/langchain_core/prompts/dict.py index 74fb4c335d8..40fc99ef700 100644 --- a/libs/core/langchain_core/prompts/dict.py +++ b/libs/core/langchain_core/prompts/dict.py @@ -85,7 +85,7 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. diff --git a/libs/core/langchain_core/prompts/loading.py b/libs/core/langchain_core/prompts/loading.py index 63e587c8ed2..0b9ec9eefa0 100644 --- a/libs/core/langchain_core/prompts/loading.py +++ b/libs/core/langchain_core/prompts/loading.py @@ -139,7 +139,7 @@ def load_prompt(path: str | Path, encoding: str | None = None) -> BasePromptTemp Args: path: Path to the prompt file. - encoding: Encoding of the file. Defaults to None. + encoding: Encoding of the file. Defaults to `None`. Returns: A PromptTemplate object. diff --git a/libs/core/langchain_core/prompts/message.py b/libs/core/langchain_core/prompts/message.py index b8642a53bca..0ae76370b77 100644 --- a/libs/core/langchain_core/prompts/message.py +++ b/libs/core/langchain_core/prompts/message.py @@ -68,7 +68,7 @@ class BaseMessagePromptTemplate(Serializable, ABC): """Human-readable representation. Args: - html: Whether to format as HTML. Defaults to False. + html: Whether to format as HTML. Defaults to `False`. Returns: Human-readable representation. diff --git a/libs/core/langchain_core/prompts/prompt.py b/libs/core/langchain_core/prompts/prompt.py index 5a16400c8db..5709fc73d1c 100644 --- a/libs/core/langchain_core/prompts/prompt.py +++ b/libs/core/langchain_core/prompts/prompt.py @@ -283,7 +283,7 @@ class PromptTemplate(StringPromptTemplate): fill in the template. For example, if the template is `"{variable1} {variable2}"`, and `partial_variables` is `{"variable1": "foo"}`, then the final prompt will be - `"foo {variable2}"`. Defaults to None. + `"foo {variable2}"`. Defaults to `None`. kwargs: Any other arguments to pass to the prompt template. Returns: diff --git a/libs/core/langchain_core/prompts/structured.py b/libs/core/langchain_core/prompts/structured.py index 8a4981147c4..22679020420 100644 --- a/libs/core/langchain_core/prompts/structured.py +++ b/libs/core/langchain_core/prompts/structured.py @@ -145,7 +145,7 @@ class StructuredPrompt(ChatPromptTemplate): Args: others: The language model to pipe the structured prompt to. - name: The name of the pipeline. Defaults to None. + name: The name of the pipeline. Defaults to `None`. Returns: A RunnableSequence object. diff --git a/libs/core/langchain_core/rate_limiters.py b/libs/core/langchain_core/rate_limiters.py index 5f4ae153f90..ff6129ef5c3 100644 --- a/libs/core/langchain_core/rate_limiters.py +++ b/libs/core/langchain_core/rate_limiters.py @@ -39,9 +39,9 @@ class BaseRateLimiter(abc.ABC): of the attempt to acquire the tokens. Args: - blocking: If True, the method will block until the tokens are available. - If False, the method will return immediately with the result of - the attempt. Defaults to True. + blocking: If `True`, the method will block until the tokens are available. + If `False`, the method will return immediately with the result of + the attempt. Defaults to `True`. Returns: True if the tokens were successfully acquired, False otherwise. @@ -58,9 +58,9 @@ class BaseRateLimiter(abc.ABC): of the attempt to acquire the tokens. Args: - blocking: If True, the method will block until the tokens are available. - If False, the method will return immediately with the result of - the attempt. Defaults to True. + blocking: If `True`, the method will block until the tokens are available. + If `False`, the method will return immediately with the result of + the attempt. Defaults to `True`. Returns: True if the tokens were successfully acquired, False otherwise. @@ -207,9 +207,9 @@ class InMemoryRateLimiter(BaseRateLimiter): of the attempt to acquire the tokens. Args: - blocking: If True, the method will block until the tokens are available. - If False, the method will return immediately with the result of - the attempt. Defaults to True. + blocking: If `True`, the method will block until the tokens are available. + If `False`, the method will return immediately with the result of + the attempt. Defaults to `True`. Returns: True if the tokens were successfully acquired, False otherwise. @@ -231,9 +231,9 @@ class InMemoryRateLimiter(BaseRateLimiter): of the attempt to acquire the tokens. Args: - blocking: If True, the method will block until the tokens are available. - If False, the method will return immediately with the result of - the attempt. Defaults to True. + blocking: If `True`, the method will block until the tokens are available. + If `False`, the method will return immediately with the result of + the attempt. Defaults to `True`. Returns: True if the tokens were successfully acquired, False otherwise. diff --git a/libs/core/langchain_core/retrievers.py b/libs/core/langchain_core/retrievers.py index ceb5eb84973..a0ad0ba876c 100644 --- a/libs/core/langchain_core/retrievers.py +++ b/libs/core/langchain_core/retrievers.py @@ -138,14 +138,14 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC): _new_arg_supported: bool = False _expects_other_args: bool = False tags: list[str] | None = None - """Optional list of tags associated with the retriever. Defaults to None. + """Optional list of tags associated with the retriever. Defaults to `None`. These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a retriever with its use case. """ metadata: dict[str, Any] | None = None - """Optional metadata associated with the retriever. Defaults to None. + """Optional metadata associated with the retriever. Defaults to `None`. This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a retriever with its @@ -224,7 +224,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC): Args: input: The query string. - config: Configuration for the retriever. Defaults to None. + config: Configuration for the retriever. Defaults to `None`. kwargs: Additional arguments to pass to the retriever. Returns: @@ -287,7 +287,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC): Args: input: The query string. - config: Configuration for the retriever. Defaults to None. + config: Configuration for the retriever. Defaults to `None`. kwargs: Additional arguments to pass to the retriever. Returns: @@ -388,16 +388,16 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC): Args: query: string to find relevant documents for. - callbacks: Callback manager or list of callbacks. Defaults to None. + callbacks: Callback manager or list of callbacks. Defaults to `None`. tags: Optional list of tags associated with the retriever. These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. - Defaults to None. + Defaults to `None`. metadata: Optional metadata associated with the retriever. This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. - Defaults to None. - run_name: Optional name for the run. Defaults to None. + Defaults to `None`. + run_name: Optional name for the run. Defaults to `None`. kwargs: Additional arguments to pass to the retriever. Returns: @@ -436,12 +436,12 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC): tags: Optional list of tags associated with the retriever. These tags will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. - Defaults to None. + Defaults to `None`. metadata: Optional metadata associated with the retriever. This metadata will be associated with each call to this retriever, and passed as arguments to the handlers defined in `callbacks`. - Defaults to None. - run_name: Optional name for the run. Defaults to None. + Defaults to `None`. + run_name: Optional name for the run. Defaults to `None`. kwargs: Additional arguments to pass to the retriever. Returns: diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py index de09a1be992..bec65321aa7 100644 --- a/libs/core/langchain_core/runnables/base.py +++ b/libs/core/langchain_core/runnables/base.py @@ -1,4 +1,4 @@ -"""Base classes and utilities for ``Runnable``s.""" +"""Base classes and utilities for `Runnable`s.""" from __future__ import annotations @@ -125,10 +125,10 @@ class Runnable(ABC, Generic[Input, Output]): Key Methods =========== - - **``invoke``/``ainvoke``**: Transforms a single input into an output. - - **``batch``/``abatch``**: Efficiently transforms multiple inputs into outputs. - - **``stream``/``astream``**: Streams output from a single input as it's produced. - - **``astream_log``**: Streams output and selected intermediate results from an + - **`invoke`/`ainvoke`**: Transforms a single input into an output. + - **`batch`/`abatch`**: Efficiently transforms multiple inputs into outputs. + - **`stream`/`astream`**: Streams output from a single input as it's produced. + - **`astream_log`**: Streams output and selected intermediate results from an input. Built-in optimizations: @@ -136,7 +136,7 @@ class Runnable(ABC, Generic[Input, Output]): - **Batch**: By default, batch runs invoke() in parallel using a thread pool executor. Override to optimize batching. - - **Async**: Methods with ``'a'`` suffix are asynchronous. By default, they execute + - **Async**: Methods with `'a'` suffix are asynchronous. By default, they execute the sync counterpart using asyncio's thread pool. Override for native async. @@ -151,15 +151,15 @@ class Runnable(ABC, Generic[Input, Output]): ==================== The LangChain Expression Language (LCEL) is a declarative way to compose - ``Runnables``into chains. + `Runnable` objectsinto chains. Any chain constructed this way will automatically have sync, async, batch, and streaming support. - The main composition primitives are ``RunnableSequence`` and ``RunnableParallel``. + The main composition primitives are `RunnableSequence` and ``RunnableParallel``. - **``RunnableSequence``** invokes a series of runnables sequentially, with + **`RunnableSequence`** invokes a series of runnables sequentially, with one Runnable's output serving as the next's input. Construct using - the ``|`` operator or by passing a list of runnables to ``RunnableSequence``. + the ``|`` operator or by passing a list of runnables to `RunnableSequence`. **``RunnableParallel``** invokes runnables concurrently, providing the same input to each. Construct it using a dict literal within a sequence or by passing a @@ -188,12 +188,12 @@ class Runnable(ABC, Generic[Input, Output]): Standard Methods ================ - All ``Runnable``s expose additional methods that can be used to modify their + All `Runnable`s expose additional methods that can be used to modify their behavior (e.g., add a retry policy, add lifecycle listeners, make them configurable, etc.). - These methods will work on any ``Runnable``, including ``Runnable`` chains - constructed by composing other ``Runnable``s. + These methods will work on any `Runnable`, including `Runnable` chains + constructed by composing other `Runnable`s. See the individual methods for details. For example, @@ -254,17 +254,17 @@ class Runnable(ABC, Generic[Input, Output]): """ name: str | None - """The name of the ``Runnable``. Used for debugging and tracing.""" + """The name of the `Runnable`. Used for debugging and tracing.""" def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str: - """Get the name of the ``Runnable``. + """Get the name of the `Runnable`. Args: suffix: An optional suffix to append to the name. - name: An optional name to use instead of the ``Runnable``'s name. + name: An optional name to use instead of the `Runnable`'s name. Returns: - The name of the ``Runnable``. + The name of the `Runnable`. """ if name: name_ = name @@ -298,7 +298,7 @@ class Runnable(ABC, Generic[Input, Output]): def InputType(self) -> type[Input]: # noqa: N802 """Input type. - The type of input this ``Runnable`` accepts specified as a type annotation. + The type of input this `Runnable` accepts specified as a type annotation. Raises: TypeError: If the input type cannot be inferred. @@ -330,7 +330,7 @@ class Runnable(ABC, Generic[Input, Output]): def OutputType(self) -> type[Output]: # noqa: N802 """Output Type. - The type of output this ``Runnable`` produces specified as a type annotation. + The type of output this `Runnable` produces specified as a type annotation. Raises: TypeError: If the output type cannot be inferred. @@ -356,18 +356,18 @@ class Runnable(ABC, Generic[Input, Output]): @property def input_schema(self) -> type[BaseModel]: - """The type of input this ``Runnable`` accepts specified as a pydantic model.""" + """The type of input this `Runnable` accepts specified as a Pydantic model.""" return self.get_input_schema() def get_input_schema( self, config: RunnableConfig | None = None, # noqa: ARG002 ) -> type[BaseModel]: - """Get a pydantic model that can be used to validate input to the Runnable. + """Get a Pydantic model that can be used to validate input to the `Runnable`. - ``Runnable``s that leverage the ``configurable_fields`` and - ``configurable_alternatives`` methods will have a dynamic input schema that - depends on which configuration the ``Runnable`` is invoked with. + `Runnable` objects that leverage the `configurable_fields` and + `configurable_alternatives` methods will have a dynamic input schema that + depends on which configuration the `Runnable` is invoked with. This method allows to get an input schema for a specific configuration. @@ -375,7 +375,7 @@ class Runnable(ABC, Generic[Input, Output]): config: A config to use when generating the schema. Returns: - A pydantic model that can be used to validate input. + A Pydantic model that can be used to validate input. """ root_type = self.InputType @@ -402,13 +402,13 @@ class Runnable(ABC, Generic[Input, Output]): def get_input_jsonschema( self, config: RunnableConfig | None = None ) -> dict[str, Any]: - """Get a JSON schema that represents the input to the ``Runnable``. + """Get a JSON schema that represents the input to the `Runnable`. Args: config: A config to use when generating the schema. Returns: - A JSON schema that represents the input to the ``Runnable``. + A JSON schema that represents the input to the `Runnable`. Example: ```python @@ -433,7 +433,7 @@ class Runnable(ABC, Generic[Input, Output]): def output_schema(self) -> type[BaseModel]: """Output schema. - The type of output this ``Runnable`` produces specified as a pydantic model. + The type of output this `Runnable` produces specified as a pydantic model. """ return self.get_output_schema() @@ -441,11 +441,11 @@ class Runnable(ABC, Generic[Input, Output]): self, config: RunnableConfig | None = None, # noqa: ARG002 ) -> type[BaseModel]: - """Get a pydantic model that can be used to validate output to the ``Runnable``. + """Get a Pydantic model that can be used to validate output to the `Runnable`. - ``Runnable``s that leverage the ``configurable_fields`` and - ``configurable_alternatives`` methods will have a dynamic output schema that - depends on which configuration the ``Runnable`` is invoked with. + `Runnable` objects that leverage the `configurable_fields` and + `configurable_alternatives` methods will have a dynamic output schema that + depends on which configuration the `Runnable` is invoked with. This method allows to get an output schema for a specific configuration. @@ -453,7 +453,7 @@ class Runnable(ABC, Generic[Input, Output]): config: A config to use when generating the schema. Returns: - A pydantic model that can be used to validate output. + A Pydantic model that can be used to validate output. """ root_type = self.OutputType @@ -480,13 +480,13 @@ class Runnable(ABC, Generic[Input, Output]): def get_output_jsonschema( self, config: RunnableConfig | None = None ) -> dict[str, Any]: - """Get a JSON schema that represents the output of the ``Runnable``. + """Get a JSON schema that represents the output of the `Runnable`. Args: config: A config to use when generating the schema. Returns: - A JSON schema that represents the output of the ``Runnable``. + A JSON schema that represents the output of the `Runnable`. Example: ```python @@ -509,20 +509,20 @@ class Runnable(ABC, Generic[Input, Output]): @property def config_specs(self) -> list[ConfigurableFieldSpec]: - """List configurable fields for this ``Runnable``.""" + """List configurable fields for this `Runnable`.""" return [] def config_schema(self, *, include: Sequence[str] | None = None) -> type[BaseModel]: - """The type of config this ``Runnable`` accepts specified as a pydantic model. + """The type of config this `Runnable` accepts specified as a Pydantic model. - To mark a field as configurable, see the ``configurable_fields`` - and ``configurable_alternatives`` methods. + To mark a field as configurable, see the `configurable_fields` + and `configurable_alternatives` methods. Args: include: A list of fields to include in the config schema. Returns: - A pydantic model that can be used to validate config. + A Pydantic model that can be used to validate config. """ include = include or [] @@ -558,13 +558,13 @@ class Runnable(ABC, Generic[Input, Output]): def get_config_jsonschema( self, *, include: Sequence[str] | None = None ) -> dict[str, Any]: - """Get a JSON schema that represents the config of the ``Runnable``. + """Get a JSON schema that represents the config of the `Runnable`. Args: include: A list of fields to include in the config schema. Returns: - A JSON schema that represents the config of the ``Runnable``. + A JSON schema that represents the config of the `Runnable`. !!! version-added "Added in version 0.3.0" @@ -572,7 +572,7 @@ class Runnable(ABC, Generic[Input, Output]): return self.config_schema(include=include).model_json_schema() def get_graph(self, config: RunnableConfig | None = None) -> Graph: - """Return a graph representation of this ``Runnable``.""" + """Return a graph representation of this `Runnable`.""" # Import locally to prevent circular import from langchain_core.runnables.graph import Graph # noqa: PLC0415 @@ -595,7 +595,7 @@ class Runnable(ABC, Generic[Input, Output]): def get_prompts( self, config: RunnableConfig | None = None ) -> list[BasePromptTemplate]: - """Return a list of prompts used by this ``Runnable``.""" + """Return a list of prompts used by this `Runnable`.""" # Import locally to prevent circular import from langchain_core.prompts.base import BasePromptTemplate # noqa: PLC0415 @@ -615,14 +615,14 @@ class Runnable(ABC, Generic[Input, Output]): ) -> RunnableSerializable[Input, Other]: """Runnable "or" operator. - Compose this ``Runnable`` with another object to create a - ``RunnableSequence``. + Compose this `Runnable` with another object to create a + `RunnableSequence`. Args: - other: Another ``Runnable`` or a ``Runnable``-like object. + other: Another `Runnable` or a `Runnable`-like object. Returns: - A new ``Runnable``. + A new `Runnable`. """ return RunnableSequence(self, coerce_to_runnable(other)) @@ -636,14 +636,14 @@ class Runnable(ABC, Generic[Input, Output]): ) -> RunnableSerializable[Other, Output]: """Runnable "reverse-or" operator. - Compose this ``Runnable`` with another object to create a - ``RunnableSequence``. + Compose this `Runnable` with another object to create a + `RunnableSequence`. Args: - other: Another ``Runnable`` or a ``Runnable``-like object. + other: Another `Runnable` or a `Runnable`-like object. Returns: - A new ``Runnable``. + A new `Runnable`. """ return RunnableSequence(coerce_to_runnable(other), self) @@ -652,12 +652,12 @@ class Runnable(ABC, Generic[Input, Output]): *others: Runnable[Any, Other] | Callable[[Any], Other], name: str | None = None, ) -> RunnableSerializable[Input, Other]: - """Pipe runnables. + """Pipe `Runnable` objects. - Compose this ``Runnable`` with ``Runnable``-like objects to make a - ``RunnableSequence``. + Compose this `Runnable` with `Runnable`-like objects to make a + `RunnableSequence`. - Equivalent to ``RunnableSequence(self, *others)`` or ``self | others[0] | ...`` + Equivalent to `RunnableSequence(self, *others)` or `self | others[0] | ...` Example: ```python @@ -688,70 +688,68 @@ class Runnable(ABC, Generic[Input, Output]): ``` Args: - *others: Other ``Runnable`` or ``Runnable``-like objects to compose - name: An optional name for the resulting ``RunnableSequence``. + *others: Other `Runnable` or `Runnable`-like objects to compose + name: An optional name for the resulting `RunnableSequence`. Returns: - A new ``Runnable``. + A new `Runnable`. """ return RunnableSequence(self, *others, name=name) def pick(self, keys: str | list[str]) -> RunnableSerializable[Any, Any]: - """Pick keys from the output dict of this ``Runnable``. + """Pick keys from the output `dict` of this `Runnable`. - Pick single key: + Pick a single key: - ```python - import json + ```python + import json - from langchain_core.runnables import RunnableLambda, RunnableMap + from langchain_core.runnables import RunnableLambda, RunnableMap - as_str = RunnableLambda(str) - as_json = RunnableLambda(json.loads) - chain = RunnableMap(str=as_str, json=as_json) + as_str = RunnableLambda(str) + as_json = RunnableLambda(json.loads) + chain = RunnableMap(str=as_str, json=as_json) - chain.invoke("[1, 2, 3]") - # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]} + chain.invoke("[1, 2, 3]") + # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]} - json_only_chain = chain.pick("json") - json_only_chain.invoke("[1, 2, 3]") - # -> [1, 2, 3] - ``` + json_only_chain = chain.pick("json") + json_only_chain.invoke("[1, 2, 3]") + # -> [1, 2, 3] + ``` - Pick list of keys: + Pick a list of keys: - ```python - from typing import Any + ```python + from typing import Any - import json + import json - from langchain_core.runnables import RunnableLambda, RunnableMap + from langchain_core.runnables import RunnableLambda, RunnableMap - as_str = RunnableLambda(str) - as_json = RunnableLambda(json.loads) + as_str = RunnableLambda(str) + as_json = RunnableLambda(json.loads) - def as_bytes(x: Any) -> bytes: - return bytes(x, "utf-8") + def as_bytes(x: Any) -> bytes: + return bytes(x, "utf-8") - chain = RunnableMap( - str=as_str, json=as_json, bytes=RunnableLambda(as_bytes) - ) + chain = RunnableMap(str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)) - chain.invoke("[1, 2, 3]") - # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"} + chain.invoke("[1, 2, 3]") + # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"} - json_and_bytes_chain = chain.pick(["json", "bytes"]) - json_and_bytes_chain.invoke("[1, 2, 3]") - # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"} - ``` + json_and_bytes_chain = chain.pick(["json", "bytes"]) + json_and_bytes_chain.invoke("[1, 2, 3]") + # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"} + ``` Args: keys: A key or list of keys to pick from the output dict. Returns: - a new ``Runnable``. + a new `Runnable`. """ # Import locally to prevent circular import @@ -765,7 +763,7 @@ class Runnable(ABC, Generic[Input, Output]): | Callable[[dict[str, Any]], Any] | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]], ) -> RunnableSerializable[Any, Any]: - """Assigns new fields to the dict output of this ``Runnable``. + """Assigns new fields to the `dict` output of this `Runnable`. ```python from langchain_community.llms.fake import FakeStreamingListLLM @@ -794,11 +792,11 @@ class Runnable(ABC, Generic[Input, Output]): ``` Args: - **kwargs: A mapping of keys to ``Runnable`` or ``Runnable``-like objects - that will be invoked with the entire output dict of this ``Runnable``. + **kwargs: A mapping of keys to `Runnable` or `Runnable`-like objects + that will be invoked with the entire output dict of this `Runnable`. Returns: - A new ``Runnable``. + A new `Runnable`. """ # Import locally to prevent circular import @@ -818,15 +816,15 @@ class Runnable(ABC, Generic[Input, Output]): """Transform a single input into an output. Args: - input: The input to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. + input: The input to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the ``RunnableConfig`` - for more details. Defaults to None. + for more details. Defaults to `None`. Returns: - The output of the ``Runnable``. + The output of the `Runnable`. """ async def ainvoke( @@ -838,15 +836,15 @@ class Runnable(ABC, Generic[Input, Output]): """Transform a single input into an output. Args: - input: The input to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. + input: The input to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the ``RunnableConfig`` - for more details. Defaults to None. + for more details. Defaults to `None`. Returns: - The output of the ``Runnable``. + The output of the `Runnable`. """ return await run_in_executor(config, self.invoke, input, config, **kwargs) @@ -863,21 +861,21 @@ class Runnable(ABC, Generic[Input, Output]): The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; - e.g., if the underlying ``Runnable`` uses an API which supports a batch mode. + e.g., if the underlying `Runnable` uses an API which supports a batch mode. Args: - inputs: A list of inputs to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. The config supports + inputs: A list of inputs to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the - ``RunnableConfig`` for more details. Defaults to None. + ``RunnableConfig`` for more details. Defaults to `None`. return_exceptions: Whether to return exceptions instead of raising them. - Defaults to False. - **kwargs: Additional keyword arguments to pass to the ``Runnable``. + Defaults to `False`. + **kwargs: Additional keyword arguments to pass to the `Runnable`. Returns: - A list of outputs from the ``Runnable``. + A list of outputs from the `Runnable`. """ if not inputs: return [] @@ -928,23 +926,23 @@ class Runnable(ABC, Generic[Input, Output]): return_exceptions: bool = False, **kwargs: Any | None, ) -> Iterator[tuple[int, Output | Exception]]: - """Run ``invoke`` in parallel on a list of inputs. + """Run `invoke` in parallel on a list of inputs. Yields results as they complete. Args: - inputs: A list of inputs to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. + inputs: A list of inputs to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the ``RunnableConfig`` - for more details. Defaults to None. + for more details. Defaults to `None`. return_exceptions: Whether to return exceptions instead of raising them. - Defaults to False. - **kwargs: Additional keyword arguments to pass to the ``Runnable``. + Defaults to `False`. + **kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - Tuples of the index of the input and the output from the ``Runnable``. + Tuples of the index of the input and the output from the `Runnable`. """ if not inputs: @@ -992,26 +990,26 @@ class Runnable(ABC, Generic[Input, Output]): return_exceptions: bool = False, **kwargs: Any | None, ) -> list[Output]: - """Default implementation runs ``ainvoke`` in parallel using ``asyncio.gather``. + """Default implementation runs `ainvoke` in parallel using ``asyncio.gather``. - The default implementation of ``batch`` works well for IO bound runnables. + The default implementation of `batch` works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; - e.g., if the underlying ``Runnable`` uses an API which supports a batch mode. + e.g., if the underlying `Runnable` uses an API which supports a batch mode. Args: - inputs: A list of inputs to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. + inputs: A list of inputs to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the ``RunnableConfig`` - for more details. Defaults to None. + for more details. Defaults to `None`. return_exceptions: Whether to return exceptions instead of raising them. - Defaults to False. - **kwargs: Additional keyword arguments to pass to the ``Runnable``. + Defaults to `False`. + **kwargs: Additional keyword arguments to pass to the `Runnable`. Returns: - A list of outputs from the ``Runnable``. + A list of outputs from the `Runnable`. """ if not inputs: @@ -1059,23 +1057,23 @@ class Runnable(ABC, Generic[Input, Output]): return_exceptions: bool = False, **kwargs: Any | None, ) -> AsyncIterator[tuple[int, Output | Exception]]: - """Run ``ainvoke`` in parallel on a list of inputs. + """Run `ainvoke` in parallel on a list of inputs. Yields results as they complete. Args: - inputs: A list of inputs to the ``Runnable``. - config: A config to use when invoking the ``Runnable``. + inputs: A list of inputs to the `Runnable`. + config: A config to use when invoking the `Runnable`. The config supports standard keys like ``'tags'``, ``'metadata'`` for tracing purposes, ``'max_concurrency'`` for controlling how much work to do in parallel, and other keys. Please refer to the ``RunnableConfig`` - for more details. Defaults to None. + for more details. Defaults to `None`. return_exceptions: Whether to return exceptions instead of raising them. - Defaults to False. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + Defaults to `False`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - A tuple of the index of the input and the output from the ``Runnable``. + A tuple of the index of the input and the output from the `Runnable`. """ if not inputs: @@ -1116,17 +1114,17 @@ class Runnable(ABC, Generic[Input, Output]): config: RunnableConfig | None = None, **kwargs: Any | None, ) -> Iterator[Output]: - """Default implementation of ``stream``, which calls ``invoke``. + """Default implementation of `stream`, which calls `invoke`. Subclasses should override this method if they support streaming output. Args: - input: The input to the ``Runnable``. - config: The config to use for the ``Runnable``. Defaults to None. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + input: The input to the `Runnable`. + config: The config to use for the `Runnable`. Defaults to `None`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - The output of the ``Runnable``. + The output of the `Runnable`. """ yield self.invoke(input, config, **kwargs) @@ -1137,17 +1135,17 @@ class Runnable(ABC, Generic[Input, Output]): config: RunnableConfig | None = None, **kwargs: Any | None, ) -> AsyncIterator[Output]: - """Default implementation of ``astream``, which calls ``ainvoke``. + """Default implementation of `astream`, which calls `ainvoke`. Subclasses should override this method if they support streaming output. Args: - input: The input to the ``Runnable``. - config: The config to use for the ``Runnable``. Defaults to None. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + input: The input to the `Runnable`. + config: The config to use for the `Runnable`. Defaults to `None`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - The output of the ``Runnable``. + The output of the `Runnable`. """ yield await self.ainvoke(input, config, **kwargs) @@ -1201,7 +1199,7 @@ class Runnable(ABC, Generic[Input, Output]): exclude_tags: Sequence[str] | None = None, **kwargs: Any, ) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]: - """Stream all output from a ``Runnable``, as reported to the callback system. + """Stream all output from a `Runnable`, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. @@ -1212,8 +1210,8 @@ class Runnable(ABC, Generic[Input, Output]): The Jsonpatch ops can be applied in order to construct state. Args: - input: The input to the ``Runnable``. - config: The config to use for the ``Runnable``. + input: The input to the `Runnable`. + config: The config to use for the `Runnable`. diff: Whether to yield diffs between each step or the current state. with_streamed_output_list: Whether to yield the ``streamed_output`` list. include_names: Only include logs with these names. @@ -1222,7 +1220,7 @@ class Runnable(ABC, Generic[Input, Output]): exclude_names: Exclude logs with these names. exclude_types: Exclude logs with these types. exclude_tags: Exclude logs with these tags. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: A ``RunLogPatch`` or ``RunLog`` object. @@ -1269,26 +1267,26 @@ class Runnable(ABC, Generic[Input, Output]): ) -> AsyncIterator[StreamEvent]: """Generate a stream of events. - Use to create an iterator over ``StreamEvents`` that provide real-time information - about the progress of the ``Runnable``, including ``StreamEvents`` from intermediate + Use to create an iterator over `StreamEvent` that provide real-time information + about the progress of the `Runnable`, including `StreamEvent` from intermediate results. A ``StreamEvent`` is a dictionary with the following schema: - ``event``: **str** - Event names are of the format: ``on_[runnable_type]_(start|stream|end)``. - - ``name``: **str** - The name of the ``Runnable`` that generated the event. + - `name`: **str** - The name of the `Runnable` that generated the event. - ``run_id``: **str** - randomly generated ID associated with the given - execution of the ``Runnable`` that emitted the event. A child ``Runnable`` that gets - invoked as part of the execution of a parent ``Runnable`` is assigned its own + execution of the `Runnable` that emitted the event. A child `Runnable` that gets + invoked as part of the execution of a parent `Runnable` is assigned its own unique ID. - ``parent_ids``: **list[str]** - The IDs of the parent runnables that generated - the event. The root ``Runnable`` will have an empty list. The order of the parent + the event. The root `Runnable` will have an empty list. The order of the parent IDs is from the root to the immediate parent. Only available for v2 version of the API. The v1 version of the API will return an empty list. - - ``tags``: **Optional[list[str]]** - The tags of the ``Runnable`` that generated + - ``tags``: **Optional[list[str]]** - The tags of the `Runnable` that generated the event. - - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the ``Runnable`` that + - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the `Runnable` that generated the event. - ``data``: **dict[str, Any]** @@ -1379,8 +1377,8 @@ class Runnable(ABC, Generic[Input, Output]): ] ).with_config({"run_name": "my_template", "tags": ["my_template"]}) ``` - Example: + Example: ```python from langchain_core.runnables import RunnableLambda @@ -1420,9 +1418,7 @@ class Runnable(ABC, Generic[Input, Output]): ] ``` - Example: Dispatch Custom Event - - ```python + ```python title="Example: Dispatch Custom Event" from langchain_core.callbacks.manager import ( adispatch_custom_event, ) @@ -1454,29 +1450,29 @@ class Runnable(ABC, Generic[Input, Output]): ``` Args: - input: The input to the ``Runnable``. - config: The config to use for the ``Runnable``. - version: The version of the schema to use either ``'v2'`` or ``'v1'``. - Users should use ``'v2'``. - ``'v1'`` is for backwards compatibility and will be deprecated - in 0.4.0. + input: The input to the `Runnable`. + config: The config to use for the `Runnable`. + version: The version of the schema to use either `'v2'` or `'v1'`. + Users should use `'v2'`. + `'v1'` is for backwards compatibility and will be deprecated + in `0.4.0`. No default will be assigned until the API is stabilized. - custom events will only be surfaced in ``'v2'``. - include_names: Only include events from ``Runnables`` with matching names. - include_types: Only include events from ``Runnables`` with matching types. - include_tags: Only include events from ``Runnables`` with matching tags. - exclude_names: Exclude events from ``Runnables`` with matching names. - exclude_types: Exclude events from ``Runnables`` with matching types. - exclude_tags: Exclude events from ``Runnables`` with matching tags. - kwargs: Additional keyword arguments to pass to the ``Runnable``. - These will be passed to ``astream_log`` as this implementation - of ``astream_events`` is built on top of ``astream_log``. + custom events will only be surfaced in `'v2'`. + include_names: Only include events from `Runnable` objects with matching names. + include_types: Only include events from `Runnable` objects with matching types. + include_tags: Only include events from `Runnable` objects with matching tags. + exclude_names: Exclude events from `Runnable` objects with matching names. + exclude_types: Exclude events from `Runnable` objects with matching types. + exclude_tags: Exclude events from `Runnable` objects with matching tags. + kwargs: Additional keyword arguments to pass to the `Runnable`. + These will be passed to `astream_log` as this implementation + of `astream_events` is built on top of `astream_log`. Yields: - An async stream of ``StreamEvents``. + An async stream of `StreamEvent`. Raises: - NotImplementedError: If the version is not ``'v1'`` or ``'v2'``. + NotImplementedError: If the version is not `'v1'` or `'v2'`. """ # noqa: E501 if version == "v2": @@ -1523,18 +1519,18 @@ class Runnable(ABC, Generic[Input, Output]): ) -> Iterator[Output]: """Transform inputs to outputs. - Default implementation of transform, which buffers input and calls ``astream``. + Default implementation of transform, which buffers input and calls `astream`. Subclasses should override this method if they can start producing output while input is still being generated. Args: - input: An iterator of inputs to the ``Runnable``. - config: The config to use for the ``Runnable``. Defaults to None. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + input: An iterator of inputs to the `Runnable`. + config: The config to use for the `Runnable`. Defaults to `None`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - The output of the ``Runnable``. + The output of the `Runnable`. """ final: Input @@ -1568,18 +1564,18 @@ class Runnable(ABC, Generic[Input, Output]): ) -> AsyncIterator[Output]: """Transform inputs to outputs. - Default implementation of atransform, which buffers input and calls ``astream``. + Default implementation of atransform, which buffers input and calls `astream`. Subclasses should override this method if they can start producing output while input is still being generated. Args: - input: An async iterator of inputs to the ``Runnable``. - config: The config to use for the ``Runnable``. Defaults to None. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + input: An async iterator of inputs to the `Runnable`. + config: The config to use for the `Runnable`. Defaults to `None`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Yields: - The output of the ``Runnable``. + The output of the `Runnable`. """ final: Input @@ -1607,16 +1603,16 @@ class Runnable(ABC, Generic[Input, Output]): yield output def bind(self, **kwargs: Any) -> Runnable[Input, Output]: - """Bind arguments to a ``Runnable``, returning a new ``Runnable``. + """Bind arguments to a `Runnable`, returning a new `Runnable`. - Useful when a ``Runnable`` in a chain requires an argument that is not - in the output of the previous ``Runnable`` or included in the user input. + Useful when a `Runnable` in a chain requires an argument that is not + in the output of the previous `Runnable` or included in the user input. Args: - kwargs: The arguments to bind to the ``Runnable``. + kwargs: The arguments to bind to the `Runnable`. Returns: - A new ``Runnable`` with the arguments bound. + A new `Runnable` with the arguments bound. Example: ```python @@ -1625,13 +1621,13 @@ class Runnable(ABC, Generic[Input, Output]): llm = ChatOllama(model="llama3.1") - # Without bind. + # Without bind chain = llm | StrOutputParser() chain.invoke("Repeat quoted words exactly: 'One two three four five.'") # Output is 'One two three four five.' - # With bind. + # With bind chain = llm.bind(stop=["three"]) | StrOutputParser() chain.invoke("Repeat quoted words exactly: 'One two three four five.'") @@ -1646,14 +1642,14 @@ class Runnable(ABC, Generic[Input, Output]): # Sadly Unpack is not well-supported by mypy so this will have to be untyped **kwargs: Any, ) -> Runnable[Input, Output]: - """Bind config to a ``Runnable``, returning a new ``Runnable``. + """Bind config to a `Runnable`, returning a new `Runnable`. Args: - config: The config to bind to the ``Runnable``. - kwargs: Additional keyword arguments to pass to the ``Runnable``. + config: The config to bind to the `Runnable`. + kwargs: Additional keyword arguments to pass to the `Runnable`. Returns: - A new ``Runnable`` with the config bound. + A new `Runnable` with the config bound. """ return RunnableBinding( @@ -1678,22 +1674,22 @@ class Runnable(ABC, Generic[Input, Output]): | Callable[[Run, RunnableConfig], None] | None = None, ) -> Runnable[Input, Output]: - """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``. + """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`. - The Run object contains information about the run, including its ``id``, - ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and + The Run object contains information about the run, including its `id`, + `type`, `input`, `output`, `error`, `start_time`, `end_time`, and any tags or metadata added to the run. Args: - on_start: Called before the ``Runnable`` starts running, with the ``Run`` - object. Defaults to None. - on_end: Called after the ``Runnable`` finishes running, with the ``Run`` - object. Defaults to None. - on_error: Called if the ``Runnable`` throws an error, with the ``Run`` - object. Defaults to None. + on_start: Called before the `Runnable` starts running, with the `Run` + object. Defaults to `None`. + on_end: Called after the `Runnable` finishes running, with the `Run` + object. Defaults to `None`. + on_error: Called if the `Runnable` throws an error, with the `Run` + object. Defaults to `None`. Returns: - A new ``Runnable`` with the listeners bound. + A new `Runnable` with the listeners bound. Example: ```python @@ -1744,24 +1740,24 @@ class Runnable(ABC, Generic[Input, Output]): on_end: AsyncListener | None = None, on_error: AsyncListener | None = None, ) -> Runnable[Input, Output]: - """Bind async lifecycle listeners to a ``Runnable``. + """Bind async lifecycle listeners to a `Runnable`. - Returns a new ``Runnable``. + Returns a new `Runnable`. - The Run object contains information about the run, including its ``id``, - ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and + The Run object contains information about the run, including its `id`, + `type`, `input`, `output`, `error`, `start_time`, `end_time`, and any tags or metadata added to the run. Args: - on_start: Called asynchronously before the ``Runnable`` starts running, - with the ``Run`` object. Defaults to None. - on_end: Called asynchronously after the ``Runnable`` finishes running, - with the ``Run`` object. Defaults to None. - on_error: Called asynchronously if the ``Runnable`` throws an error, - with the ``Run`` object. Defaults to None. + on_start: Called asynchronously before the `Runnable` starts running, + with the `Run` object. Defaults to `None`. + on_end: Called asynchronously after the `Runnable` finishes running, + with the `Run` object. Defaults to `None`. + on_error: Called asynchronously if the `Runnable` throws an error, + with the `Run` object. Defaults to `None`. Returns: - A new ``Runnable`` with the listeners bound. + A new `Runnable` with the listeners bound. Example: ```python @@ -1834,11 +1830,11 @@ class Runnable(ABC, Generic[Input, Output]): input_type: type[Input] | None = None, output_type: type[Output] | None = None, ) -> Runnable[Input, Output]: - """Bind input and output types to a ``Runnable``, returning a new ``Runnable``. + """Bind input and output types to a `Runnable`, returning a new `Runnable`. Args: - input_type: The input type to bind to the ``Runnable``. Defaults to None. - output_type: The output type to bind to the ``Runnable``. Defaults to None. + input_type: The input type to bind to the `Runnable`. Defaults to `None`. + output_type: The output type to bind to the `Runnable`. Defaults to `None`. Returns: A new Runnable with the types bound. @@ -1858,13 +1854,13 @@ class Runnable(ABC, Generic[Input, Output]): exponential_jitter_params: ExponentialJitterParams | None = None, stop_after_attempt: int = 3, ) -> Runnable[Input, Output]: - """Create a new Runnable that retries the original Runnable on exceptions. + """Create a new `Runnable` that retries the original `Runnable` on exceptions. Args: retry_if_exception_type: A tuple of exception types to retry on. Defaults to (Exception,). wait_exponential_jitter: Whether to add jitter to the wait - time between retries. Defaults to True. + time between retries. Defaults to `True`. stop_after_attempt: The maximum number of attempts to make before giving up. Defaults to 3. exponential_jitter_params: Parameters for @@ -1916,12 +1912,12 @@ class Runnable(ABC, Generic[Input, Output]): ) def map(self) -> Runnable[list[Input], list[Output]]: - """Return a new ``Runnable`` that maps a list of inputs to a list of outputs. + """Return a new `Runnable` that maps a list of inputs to a list of outputs. - Calls ``invoke`` with each input. + Calls `invoke` with each input. Returns: - A new ``Runnable`` that maps a list of inputs to a list of outputs. + A new `Runnable` that maps a list of inputs to a list of outputs. Example: ```python @@ -1945,25 +1941,25 @@ class Runnable(ABC, Generic[Input, Output]): exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,), exception_key: str | None = None, ) -> RunnableWithFallbacksT[Input, Output]: - """Add fallbacks to a ``Runnable``, returning a new ``Runnable``. + """Add fallbacks to a `Runnable`, returning a new `Runnable`. - The new ``Runnable`` will try the original ``Runnable``, and then each fallback + The new `Runnable` will try the original `Runnable`, and then each fallback in order, upon failures. Args: - fallbacks: A sequence of runnables to try if the original ``Runnable`` + fallbacks: A sequence of runnables to try if the original `Runnable` fails. exceptions_to_handle: A tuple of exception types to handle. Defaults to ``(Exception,)``. exception_key: If string is specified then handled exceptions will be passed to fallbacks as part of the input under the specified key. - If None, exceptions will not be passed to fallbacks. - If used, the base ``Runnable`` and its fallbacks must accept a - dictionary as input. Defaults to None. + If `None`, exceptions will not be passed to fallbacks. + If used, the base `Runnable` and its fallbacks must accept a + dictionary as input. Defaults to `None`. Returns: - A new ``Runnable`` that will try the original ``Runnable``, and then each - fallback in order, upon failures. + A new `Runnable` that will try the original `Runnable`, and then each + Fallback in order, upon failures. Example: ```python @@ -1988,18 +1984,18 @@ class Runnable(ABC, Generic[Input, Output]): ``` Args: - fallbacks: A sequence of runnables to try if the original ``Runnable`` + fallbacks: A sequence of runnables to try if the original `Runnable` fails. exceptions_to_handle: A tuple of exception types to handle. exception_key: If string is specified then handled exceptions will be passed to fallbacks as part of the input under the specified key. - If None, exceptions will not be passed to fallbacks. - If used, the base ``Runnable`` and its fallbacks must accept a + If `None`, exceptions will not be passed to fallbacks. + If used, the base `Runnable` and its fallbacks must accept a dictionary as input. Returns: - A new ``Runnable`` that will try the original ``Runnable``, and then each - fallback in order, upon failures. + A new `Runnable` that will try the original `Runnable`, and then each + Fallback in order, upon failures. """ # Import locally to prevent circular import @@ -2032,7 +2028,7 @@ class Runnable(ABC, Generic[Input, Output]): Helper method to transform an ``Input`` value to an ``Output`` value, with callbacks. - Use this method to implement ``invoke`` in subclasses. + Use this method to implement `invoke` in subclasses. """ config = ensure_config(config) @@ -2083,7 +2079,7 @@ class Runnable(ABC, Generic[Input, Output]): Helper method to transform an ``Input`` value to an ``Output`` value, with callbacks. - Use this method to implement ``ainvoke`` in subclasses. + Use this method to implement `ainvoke` in subclasses. """ config = ensure_config(config) callback_manager = get_async_callback_manager_for_config(config) @@ -2128,7 +2124,7 @@ class Runnable(ABC, Generic[Input, Output]): """Transform a list of inputs to a list of outputs, with callbacks. Helper method to transform an ``Input`` value to an ``Output`` value, - with callbacks. Use this method to implement ``invoke`` in subclasses. + with callbacks. Use this method to implement `invoke` in subclasses. """ if not inputs: @@ -2198,7 +2194,7 @@ class Runnable(ABC, Generic[Input, Output]): Helper method to transform an ``Input`` value to an ``Output`` value, with callbacks. - Use this method to implement ``invoke`` in subclasses. + Use this method to implement `invoke` in subclasses. """ if not inputs: @@ -2268,7 +2264,7 @@ class Runnable(ABC, Generic[Input, Output]): Helper method to transform an ``Iterator`` of ``Input`` values into an ``Iterator`` of ``Output`` values, with callbacks. - Use this to implement ``stream`` or ``transform`` in ``Runnable`` subclasses. + Use this to implement `stream` or ``transform`` in `Runnable` subclasses. """ # tee the input so we can iterate over it twice @@ -2365,7 +2361,7 @@ class Runnable(ABC, Generic[Input, Output]): Helper method to transform an Async ``Iterator`` of ``Input`` values into an Async ``Iterator`` of ``Output`` values, with callbacks. - Use this to implement ``astream`` or ``atransform`` in ``Runnable`` subclasses. + Use this to implement `astream` or ``atransform`` in `Runnable` subclasses. """ # tee the input so we can iterate over it twice @@ -2456,23 +2452,23 @@ class Runnable(ABC, Generic[Input, Output]): description: str | None = None, arg_types: dict[str, type] | None = None, ) -> BaseTool: - """Create a ``BaseTool`` from a ``Runnable``. + """Create a `BaseTool` from a `Runnable`. - ``as_tool`` will instantiate a ``BaseTool`` with a name, description, and - ``args_schema`` from a ``Runnable``. Where possible, schemas are inferred + ``as_tool`` will instantiate a `BaseTool` with a name, description, and + ``args_schema`` from a `Runnable`. Where possible, schemas are inferred from ``runnable.get_input_schema``. Alternatively (e.g., if the - ``Runnable`` takes a dict as input and the specific dict keys are not typed), + `Runnable` takes a dict as input and the specific dict keys are not typed), the schema can be specified directly with ``args_schema``. You can also pass ``arg_types`` to just specify the required arguments and their types. Args: - args_schema: The schema for the tool. Defaults to None. - name: The name of the tool. Defaults to None. - description: The description of the tool. Defaults to None. - arg_types: A dictionary of argument names to types. Defaults to None. + args_schema: The schema for the tool. Defaults to `None`. + name: The name of the tool. Defaults to `None`. + description: The description of the tool. Defaults to `None`. + arg_types: A dictionary of argument names to types. Defaults to `None`. Returns: - A ``BaseTool`` instance. + A `BaseTool` instance. Typed dict input: @@ -2495,7 +2491,7 @@ class Runnable(ABC, Generic[Input, Output]): as_tool.invoke({"a": 3, "b": [1, 2]}) ``` - ``dict`` input, specifying schema via ``args_schema``: + `dict` input, specifying schema via ``args_schema``: ```python from typing import Any @@ -2516,7 +2512,7 @@ class Runnable(ABC, Generic[Input, Output]): as_tool.invoke({"a": 3, "b": [1, 2]}) ``` - ``dict`` input, specifying schema via ``arg_types``: + `dict` input, specifying schema via ``arg_types``: ```python from typing import Any @@ -2579,10 +2575,10 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): @override def to_json(self) -> SerializedConstructor | SerializedNotImplemented: - """Serialize the ``Runnable`` to JSON. + """Serialize the `Runnable` to JSON. Returns: - A JSON-serializable representation of the ``Runnable``. + A JSON-serializable representation of the `Runnable`. """ dumped = super().to_json() @@ -2593,16 +2589,16 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): def configurable_fields( self, **kwargs: AnyConfigurableField ) -> RunnableSerializable[Input, Output]: - """Configure particular ``Runnable`` fields at runtime. + """Configure particular `Runnable` fields at runtime. Args: **kwargs: A dictionary of ``ConfigurableField`` instances to configure. Raises: - ValueError: If a configuration key is not found in the ``Runnable``. + ValueError: If a configuration key is not found in the `Runnable`. Returns: - A new ``Runnable`` with the fields configured. + A new `Runnable` with the fields configured. ```python from langchain_core.runnables import ConfigurableField @@ -2652,20 +2648,20 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): prefix_keys: bool = False, **kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]], ) -> RunnableSerializable[Input, Output]: - """Configure alternatives for ``Runnables`` that can be set at runtime. + """Configure alternatives for `Runnable` objects that can be set at runtime. Args: which: The ``ConfigurableField`` instance that will be used to select the alternative. default_key: The default key to use if no alternative is selected. - Defaults to ``'default'``. + Defaults to `'default'`. prefix_keys: Whether to prefix the keys with the ``ConfigurableField`` id. - Defaults to False. - **kwargs: A dictionary of keys to ``Runnable`` instances or callables that - return ``Runnable`` instances. + Defaults to `False`. + **kwargs: A dictionary of keys to `Runnable` instances or callables that + return `Runnable` instances. Returns: - A new ``Runnable`` with the alternatives configured. + A new `Runnable` with the alternatives configured. ```python from langchain_anthropic import ChatAnthropic @@ -2787,25 +2783,25 @@ def _seq_output_schema( class RunnableSequence(RunnableSerializable[Input, Output]): - """Sequence of ``Runnables``, where the output of each is the input of the next. + """Sequence of `Runnable` objects, where the output of one is the input of the next. - **``RunnableSequence``** is the most important composition operator in LangChain + **`RunnableSequence`** is the most important composition operator in LangChain as it is used in virtually every chain. - A ``RunnableSequence`` can be instantiated directly or more commonly by using the + A `RunnableSequence` can be instantiated directly or more commonly by using the ``|`` operator where either the left or right operands (or both) must be a - ``Runnable``. + `Runnable`. - Any ``RunnableSequence`` automatically supports sync, async, batch. + Any `RunnableSequence` automatically supports sync, async, batch. - The default implementations of ``batch`` and ``abatch`` utilize threadpools and - asyncio gather and will be faster than naive invocation of ``invoke`` or ``ainvoke`` - for IO bound ``Runnable``s. + The default implementations of `batch` and `abatch` utilize threadpools and + asyncio gather and will be faster than naive invocation of `invoke` or `ainvoke` + for IO bound `Runnable`s. Batching is implemented by invoking the batch method on each component of the - ``RunnableSequence`` in order. + `RunnableSequence` in order. - A ``RunnableSequence`` preserves the streaming properties of its components, so if + A `RunnableSequence` preserves the streaming properties of its components, so if all components of the sequence implement a ``transform`` method -- which is the method that implements the logic to map a streaming input to a streaming output -- then the sequence will be able to stream input to output! @@ -2817,13 +2813,13 @@ class RunnableSequence(RunnableSerializable[Input, Output]): !!! note ``RunnableLambdas`` do not support ``transform`` by default! So if you need to use a ``RunnableLambdas`` be careful about where you place them in a - ``RunnableSequence`` (if you need to use the ``stream``/``astream`` methods). + `RunnableSequence` (if you need to use the `stream`/`astream` methods). If you need arbitrary logic and need streaming, you can subclass Runnable, and implement ``transform`` for whatever logic you need. Here is a simple example that uses simple functions to illustrate the use of - ``RunnableSequence``: + `RunnableSequence`: ```python from langchain_core.runnables import RunnableLambda @@ -2874,11 +2870,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]): # purposes. It allows specifying the `Input` on the first type, the `Output` of # the last type. first: Runnable[Input, Any] - """The first ``Runnable`` in the sequence.""" + """The first `Runnable` in the sequence.""" middle: list[Runnable[Any, Any]] = Field(default_factory=list) - """The middle ``Runnable`` in the sequence.""" + """The middle `Runnable` in the sequence.""" last: Runnable[Any, Output] - """The last ``Runnable`` in the sequence.""" + """The last `Runnable` in the sequence.""" def __init__( self, @@ -2888,14 +2884,14 @@ class RunnableSequence(RunnableSerializable[Input, Output]): middle: list[Runnable[Any, Any]] | None = None, last: Runnable[Any, Any] | None = None, ) -> None: - """Create a new ``RunnableSequence``. + """Create a new `RunnableSequence`. Args: steps: The steps to include in the sequence. - name: The name of the ``Runnable``. Defaults to None. - first: The first ``Runnable`` in the sequence. Defaults to None. - middle: The middle ``Runnables`` in the sequence. Defaults to None. - last: The last Runnable in the sequence. Defaults to None. + name: The name of the `Runnable`. Defaults to `None`. + first: The first `Runnable` in the sequence. Defaults to `None`. + middle: The middle `Runnable` objects in the sequence. Defaults to `None`. + last: The last Runnable in the sequence. Defaults to `None`. Raises: ValueError: If the sequence has less than 2 steps. @@ -2930,10 +2926,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @property def steps(self) -> list[Runnable[Any, Any]]: - """All the ``Runnable``s that make up the sequence in order. + """All the `Runnable`s that make up the sequence in order. Returns: - A list of ``Runnable``s. + A list of `Runnable`s. """ return [self.first, *self.middle, self.last] @@ -2950,24 +2946,24 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @property @override def InputType(self) -> type[Input]: - """The type of the input to the ``Runnable``.""" + """The type of the input to the `Runnable`.""" return self.first.InputType @property @override def OutputType(self) -> type[Output]: - """The type of the output of the ``Runnable``.""" + """The type of the output of the `Runnable`.""" return self.last.OutputType @override def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]: - """Get the input schema of the ``Runnable``. + """Get the input schema of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The input schema of the ``Runnable``. + The input schema of the `Runnable`. """ return _seq_input_schema(self.steps, config) @@ -2976,13 +2972,13 @@ class RunnableSequence(RunnableSerializable[Input, Output]): def get_output_schema( self, config: RunnableConfig | None = None ) -> type[BaseModel]: - """Get the output schema of the ``Runnable``. + """Get the output schema of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The output schema of the ``Runnable``. + The output schema of the `Runnable`. """ return _seq_output_schema(self.steps, config) @@ -2990,10 +2986,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @property @override def config_specs(self) -> list[ConfigurableFieldSpec]: - """Get the config specs of the ``Runnable``. + """Get the config specs of the `Runnable`. Returns: - The config specs of the ``Runnable``. + The config specs of the `Runnable`. """ # Import locally to prevent circular import @@ -3003,16 +2999,16 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @override def get_graph(self, config: RunnableConfig | None = None) -> Graph: - """Get the graph representation of the ``Runnable``. + """Get the graph representation of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The graph representation of the ``Runnable``. + The graph representation of the `Runnable`. Raises: - ValueError: If a ``Runnable`` has no first or last node. + ValueError: If a `Runnable` has no first or last node. """ # Import locally to prevent circular import @@ -3532,12 +3528,12 @@ class RunnableSequence(RunnableSerializable[Input, Output]): class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): - """Runnable that runs a mapping of ``Runnable``s in parallel. + """Runnable that runs a mapping of `Runnable`s in parallel. Returns a mapping of their outputs. ``RunnableParallel`` is one of the two main composition primitives for the LCEL, - alongside ``RunnableSequence``. It invokes ``Runnable``s concurrently, providing the + alongside `RunnableSequence`. It invokes `Runnable`s concurrently, providing the same input to each. A ``RunnableParallel`` can be instantiated directly or by using a dict literal @@ -3587,8 +3583,8 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): await sequence.abatch([1, 2, 3]) ``` - ``RunnableParallel`` makes it easy to run ``Runnable``s in parallel. In the below - example, we simultaneously stream output from two different ``Runnables``: + ``RunnableParallel`` makes it easy to run `Runnable`s in parallel. In the below + example, we simultaneously stream output from two different `Runnable` objects: ```python from langchain_core.prompts import ChatPromptTemplate @@ -3633,7 +3629,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): """Create a ``RunnableParallel``. Args: - steps__: The steps to include. Defaults to None. + steps__: The steps to include. Defaults to `None`. **kwargs: Additional steps to include. """ @@ -3665,14 +3661,14 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): @override def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str: - """Get the name of the ``Runnable``. + """Get the name of the `Runnable`. Args: - suffix: The suffix to use. Defaults to None. - name: The name to use. Defaults to None. + suffix: The suffix to use. Defaults to `None`. + name: The name to use. Defaults to `None`. Returns: - The name of the ``Runnable``. + The name of the `Runnable`. """ name = name or self.name or f"RunnableParallel<{','.join(self.steps__.keys())}>" @@ -3681,7 +3677,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): @property @override def InputType(self) -> Any: - """The type of the input to the ``Runnable``.""" + """The type of the input to the `Runnable`.""" for step in self.steps__.values(): if step.InputType: return step.InputType @@ -3690,13 +3686,13 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): @override def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]: - """Get the input schema of the ``Runnable``. + """Get the input schema of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The input schema of the ``Runnable``. + The input schema of the `Runnable`. """ if all( @@ -3721,13 +3717,13 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): def get_output_schema( self, config: RunnableConfig | None = None ) -> type[BaseModel]: - """Get the output schema of the ``Runnable``. + """Get the output schema of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The output schema of the ``Runnable``. + The output schema of the `Runnable`. """ fields = {k: (v.OutputType, ...) for k, v in self.steps__.items()} @@ -3736,10 +3732,10 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): @property @override def config_specs(self) -> list[ConfigurableFieldSpec]: - """Get the config specs of the ``Runnable``. + """Get the config specs of the `Runnable`. Returns: - The config specs of the ``Runnable``. + The config specs of the `Runnable`. """ return get_unique_config_specs( @@ -3748,16 +3744,16 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]): @override def get_graph(self, config: RunnableConfig | None = None) -> Graph: - """Get the graph representation of the ``Runnable``. + """Get the graph representation of the `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The graph representation of the ``Runnable``. + The graph representation of the `Runnable`. Raises: - ValueError: If a ``Runnable`` has no first or last node. + ValueError: If a `Runnable` has no first or last node. """ # Import locally to prevent circular import @@ -4057,7 +4053,7 @@ RunnableMap = RunnableParallel class RunnableGenerator(Runnable[Input, Output]): - """``Runnable`` that runs a generator function. + """`Runnable` that runs a generator function. ``RunnableGenerator``s can be instantiated directly or by using a generator within a sequence. @@ -4161,8 +4157,8 @@ class RunnableGenerator(Runnable[Input, Output]): Args: transform: The transform function. - atransform: The async transform function. Defaults to None. - name: The name of the ``Runnable``. Defaults to None. + atransform: The async transform function. Defaults to `None`. + name: The name of the `Runnable`. Defaults to `None`. Raises: TypeError: If the transform is not a generator function. @@ -4359,12 +4355,12 @@ class RunnableGenerator(Runnable[Input, Output]): class RunnableLambda(Runnable[Input, Output]): - """``RunnableLambda`` converts a python callable into a ``Runnable``. + """``RunnableLambda`` converts a python callable into a `Runnable`. Wrapping a callable in a ``RunnableLambda`` makes the callable usable within either a sync or async context. - ``RunnableLambda`` can be composed as any other ``Runnable`` and provides + ``RunnableLambda`` can be composed as any other `Runnable` and provides seamless integration with LangChain tracing. ``RunnableLambda`` is best suited for code that does not need to support @@ -4372,7 +4368,7 @@ class RunnableLambda(Runnable[Input, Output]): on chunks of inputs and yield chunks of outputs), use ``RunnableGenerator`` instead. - Note that if a ``RunnableLambda`` returns an instance of ``Runnable``, that + Note that if a ``RunnableLambda`` returns an instance of `Runnable`, that instance is invoked (or streamed) during execution. Examples: @@ -4439,8 +4435,8 @@ class RunnableLambda(Runnable[Input, Output]): Args: func: Either sync or async callable afunc: An async callable that takes an input and returns an output. - Defaults to None. - name: The name of the ``Runnable``. Defaults to None. + Defaults to `None`. + name: The name of the `Runnable`. Defaults to `None`. Raises: TypeError: If the ``func`` is not a callable type. @@ -4484,7 +4480,7 @@ class RunnableLambda(Runnable[Input, Output]): @property @override def InputType(self) -> Any: - """The type of the input to this ``Runnable``.""" + """The type of the input to this `Runnable`.""" func = getattr(self, "func", None) or self.afunc try: params = inspect.signature(func).parameters @@ -4497,13 +4493,13 @@ class RunnableLambda(Runnable[Input, Output]): @override def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]: - """The pydantic schema for the input to this ``Runnable``. + """The pydantic schema for the input to this `Runnable`. Args: - config: The config to use. Defaults to None. + config: The config to use. Defaults to `None`. Returns: - The input schema for this ``Runnable``. + The input schema for this `Runnable`. """ func = getattr(self, "func", None) or self.afunc @@ -4542,10 +4538,10 @@ class RunnableLambda(Runnable[Input, Output]): @property @override def OutputType(self) -> Any: - """The type of the output of this ``Runnable`` as a type annotation. + """The type of the output of this `Runnable` as a type annotation. Returns: - The type of the output of this ``Runnable``. + The type of the output of this `Runnable`. """ func = getattr(self, "func", None) or self.afunc @@ -4592,11 +4588,11 @@ class RunnableLambda(Runnable[Input, Output]): @functools.cached_property def deps(self) -> list[Runnable]: - """The dependencies of this ``Runnable``. + """The dependencies of this `Runnable`. Returns: - The dependencies of this ``Runnable``. If the function has nonlocal - variables that are ``Runnable``s, they are considered dependencies. + The dependencies of this `Runnable`. If the function has nonlocal + variables that are `Runnable`s, they are considered dependencies. """ if hasattr(self, "func"): @@ -4664,7 +4660,7 @@ class RunnableLambda(Runnable[Input, Output]): __hash__ = None # type: ignore[assignment] def __repr__(self) -> str: - """Return a string representation of this ``Runnable``.""" + """Return a string representation of this `Runnable`.""" if self._repr is None: if hasattr(self, "func") and isinstance(self.func, itemgetter): self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})" @@ -4830,18 +4826,18 @@ class RunnableLambda(Runnable[Input, Output]): config: RunnableConfig | None = None, **kwargs: Any | None, ) -> Output: - """Invoke this ``Runnable`` synchronously. + """Invoke this `Runnable` synchronously. Args: - input: The input to this ``Runnable``. - config: The config to use. Defaults to None. + input: The input to this `Runnable`. + config: The config to use. Defaults to `None`. kwargs: Additional keyword arguments. Returns: - The output of this ``Runnable``. + The output of this `Runnable`. Raises: - TypeError: If the ``Runnable`` is a coroutine function. + TypeError: If the `Runnable` is a coroutine function. """ if hasattr(self, "func"): @@ -4861,15 +4857,15 @@ class RunnableLambda(Runnable[Input, Output]): config: RunnableConfig | None = None, **kwargs: Any | None, ) -> Output: - """Invoke this ``Runnable`` asynchronously. + """Invoke this `Runnable` asynchronously. Args: - input: The input to this ``Runnable``. - config: The config to use. Defaults to None. + input: The input to this `Runnable`. + config: The config to use. Defaults to `None`. kwargs: Additional keyword arguments. Returns: - The output of this ``Runnable``. + The output of this `Runnable`. """ return await self._acall_with_config( @@ -5102,9 +5098,9 @@ class RunnableLambda(Runnable[Input, Output]): class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]): """RunnableEachBase class. - ``Runnable`` that calls another ``Runnable`` for each element of the input sequence. + `Runnable` that calls another `Runnable` for each element of the input sequence. - Use only if creating a new ``RunnableEach`` subclass with different ``__init__`` + Use only if creating a new ``RunnableEach`` subclass with different `__init__` args. See documentation for ``RunnableEach`` for more details. @@ -5243,13 +5239,13 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]): class RunnableEach(RunnableEachBase[Input, Output]): """RunnableEach class. - ``Runnable`` that calls another ``Runnable`` for each element of the input sequence. + `Runnable` that calls another `Runnable` for each element of the input sequence. - It allows you to call multiple inputs with the bounded ``Runnable``. + It allows you to call multiple inputs with the bounded `Runnable`. - ``RunnableEach`` makes it easy to run multiple inputs for the ``Runnable``. + ``RunnableEach`` makes it easy to run multiple inputs for the `Runnable`. In the below example, we associate and run three inputs - with a ``Runnable``: + with a `Runnable`: ```python from langchain_core.runnables.base import RunnableEach @@ -5299,22 +5295,22 @@ class RunnableEach(RunnableEachBase[Input, Output]): | Callable[[Run, RunnableConfig], None] | None = None, ) -> RunnableEach[Input, Output]: - """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``. + """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`. - The ``Run`` object contains information about the run, including its ``id``, - ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and + The `Run` object contains information about the run, including its `id`, + `type`, `input`, `output`, `error`, `start_time`, `end_time`, and any tags or metadata added to the run. Args: - on_start: Called before the ``Runnable`` starts running, with the ``Run`` - object. Defaults to None. - on_end: Called after the ``Runnable`` finishes running, with the ``Run`` - object. Defaults to None. - on_error: Called if the ``Runnable`` throws an error, with the ``Run`` - object. Defaults to None. + on_start: Called before the `Runnable` starts running, with the `Run` + object. Defaults to `None`. + on_end: Called after the `Runnable` finishes running, with the `Run` + object. Defaults to `None`. + on_error: Called if the `Runnable` throws an error, with the `Run` + object. Defaults to `None`. Returns: - A new ``Runnable`` with the listeners bound. + A new `Runnable` with the listeners bound. """ return RunnableEach( @@ -5330,24 +5326,24 @@ class RunnableEach(RunnableEachBase[Input, Output]): on_end: AsyncListener | None = None, on_error: AsyncListener | None = None, ) -> RunnableEach[Input, Output]: - """Bind async lifecycle listeners to a ``Runnable``. + """Bind async lifecycle listeners to a `Runnable`. - Returns a new ``Runnable``. + Returns a new `Runnable`. - The ``Run`` object contains information about the run, including its ``id``, - ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and + The `Run` object contains information about the run, including its `id`, + `type`, `input`, `output`, `error`, `start_time`, `end_time`, and any tags or metadata added to the run. Args: - on_start: Called asynchronously before the ``Runnable`` starts running, - with the ``Run`` object. Defaults to None. - on_end: Called asynchronously after the ``Runnable`` finishes running, - with the ``Run`` object. Defaults to None. - on_error: Called asynchronously if the ``Runnable`` throws an error, - with the ``Run`` object. Defaults to None. + on_start: Called asynchronously before the `Runnable` starts running, + with the `Run` object. Defaults to `None`. + on_end: Called asynchronously after the `Runnable` finishes running, + with the `Run` object. Defaults to `None`. + on_error: Called asynchronously if the `Runnable` throws an error, + with the `Run` object. Defaults to `None`. Returns: - A new ``Runnable`` with the listeners bound. + A new `Runnable` with the listeners bound. """ return RunnableEach( @@ -5358,9 +5354,9 @@ class RunnableEach(RunnableEachBase[Input, Output]): class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[no-redef] - """``Runnable`` that delegates calls to another ``Runnable`` with a set of kwargs. + """`Runnable` that delegates calls to another `Runnable` with a set of kwargs. - Use only if creating a new ``RunnableBinding`` subclass with different ``__init__`` + Use only if creating a new ``RunnableBinding`` subclass with different `__init__` args. See documentation for ``RunnableBinding`` for more details. @@ -5368,34 +5364,34 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[ """ bound: Runnable[Input, Output] - """The underlying ``Runnable`` that this ``Runnable`` delegates to.""" + """The underlying `Runnable` that this `Runnable` delegates to.""" kwargs: Mapping[str, Any] = Field(default_factory=dict) - """kwargs to pass to the underlying ``Runnable`` when running. + """kwargs to pass to the underlying `Runnable` when running. - For example, when the ``Runnable`` binding is invoked the underlying - ``Runnable`` will be invoked with the same input but with these additional + For example, when the `Runnable` binding is invoked the underlying + `Runnable` will be invoked with the same input but with these additional kwargs. """ config: RunnableConfig = Field(default_factory=RunnableConfig) - """The config to bind to the underlying ``Runnable``.""" + """The config to bind to the underlying `Runnable`.""" config_factories: list[Callable[[RunnableConfig], RunnableConfig]] = Field( default_factory=list ) - """The config factories to bind to the underlying ``Runnable``.""" + """The config factories to bind to the underlying `Runnable`.""" # Union[Type[Input], BaseModel] + things like list[str] custom_input_type: Any | None = None - """Override the input type of the underlying ``Runnable`` with a custom type. + """Override the input type of the underlying `Runnable` with a custom type. The type can be a pydantic model, or a type annotation (e.g., ``list[str]``). """ # Union[Type[Output], BaseModel] + things like list[str] custom_output_type: Any | None = None - """Override the output type of the underlying ``Runnable`` with a custom type. + """Override the output type of the underlying `Runnable` with a custom type. The type can be a pydantic model, or a type annotation (e.g., ``list[str]``). """ @@ -5416,24 +5412,24 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[ custom_output_type: type[Output] | BaseModel | None = None, **other_kwargs: Any, ) -> None: - """Create a ``RunnableBinding`` from a ``Runnable`` and kwargs. + """Create a ``RunnableBinding`` from a `Runnable` and kwargs. Args: - bound: The underlying ``Runnable`` that this ``Runnable`` delegates calls + bound: The underlying `Runnable` that this `Runnable` delegates calls to. - kwargs: optional kwargs to pass to the underlying ``Runnable``, when running - the underlying ``Runnable`` (e.g., via ``invoke``, ``batch``, - ``transform``, or ``stream`` or async variants) - Defaults to None. - config: optional config to bind to the underlying ``Runnable``. - Defaults to None. + kwargs: optional kwargs to pass to the underlying `Runnable`, when running + the underlying `Runnable` (e.g., via `invoke`, `batch`, + ``transform``, or `stream` or async variants) + Defaults to `None`. + config: optional config to bind to the underlying `Runnable`. + Defaults to `None`. config_factories: optional list of config factories to apply to the - config before binding to the underlying ``Runnable``. - Defaults to None. + config before binding to the underlying `Runnable`. + Defaults to `None`. custom_input_type: Specify to override the input type of the underlying - ``Runnable`` with a custom type. Defaults to None. + `Runnable` with a custom type. Defaults to `None`. custom_output_type: Specify to override the output type of the underlying - ``Runnable`` with a custom type. Defaults to None. + `Runnable` with a custom type. Defaults to `None`. **other_kwargs: Unpacked into the base class. """ super().__init__( @@ -5760,30 +5756,30 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-redef] - """Wrap a ``Runnable`` with additional functionality. + """Wrap a `Runnable` with additional functionality. A ``RunnableBinding`` can be thought of as a "runnable decorator" that - preserves the essential features of ``Runnable``; i.e., batching, streaming, + preserves the essential features of `Runnable`; i.e., batching, streaming, and async support, while adding additional functionality. - Any class that inherits from ``Runnable`` can be bound to a ``RunnableBinding``. + Any class that inherits from `Runnable` can be bound to a ``RunnableBinding``. Runnables expose a standard set of methods for creating ``RunnableBindings`` or sub-classes of ``RunnableBindings`` (e.g., ``RunnableRetry``, ``RunnableWithFallbacks``) that add additional functionality. These methods include: - - ``bind``: Bind kwargs to pass to the underlying ``Runnable`` when running it. - - ``with_config``: Bind config to pass to the underlying ``Runnable`` when running + - ``bind``: Bind kwargs to pass to the underlying `Runnable` when running it. + - ``with_config``: Bind config to pass to the underlying `Runnable` when running it. - - ``with_listeners``: Bind lifecycle listeners to the underlying ``Runnable``. + - ``with_listeners``: Bind lifecycle listeners to the underlying `Runnable`. - ``with_types``: Override the input and output types of the underlying - ``Runnable``. - - ``with_retry``: Bind a retry policy to the underlying ``Runnable``. - - ``with_fallbacks``: Bind a fallback policy to the underlying ``Runnable``. + `Runnable`. + - ``with_retry``: Bind a retry policy to the underlying `Runnable`. + - ``with_fallbacks``: Bind a fallback policy to the underlying `Runnable`. Example: - `bind`: Bind kwargs to pass to the underlying ``Runnable`` when running it. + `bind`: Bind kwargs to pass to the underlying `Runnable` when running it. ```python # Create a Runnable binding that invokes the ChatModel with the @@ -5813,13 +5809,13 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re @override def bind(self, **kwargs: Any) -> Runnable[Input, Output]: - """Bind additional kwargs to a ``Runnable``, returning a new ``Runnable``. + """Bind additional kwargs to a `Runnable`, returning a new `Runnable`. Args: - **kwargs: The kwargs to bind to the ``Runnable``. + **kwargs: The kwargs to bind to the `Runnable`. Returns: - A new ``Runnable`` with the same type and config as the original, + A new `Runnable` with the same type and config as the original, but with the additional kwargs bound. """ @@ -5862,22 +5858,22 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re | Callable[[Run, RunnableConfig], None] | None = None, ) -> Runnable[Input, Output]: - """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``. + """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`. - The ``Run`` object contains information about the run, including its ``id``, - ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and + The `Run` object contains information about the run, including its `id`, + `type`, `input`, `output`, `error`, `start_time`, `end_time`, and any tags or metadata added to the run. Args: - on_start: Called before the ``Runnable`` starts running, with the ``Run`` - object. Defaults to None. - on_end: Called after the ``Runnable`` finishes running, with the ``Run`` - object. Defaults to None. - on_error: Called if the ``Runnable`` throws an error, with the ``Run`` - object. Defaults to None. + on_start: Called before the `Runnable` starts running, with the `Run` + object. Defaults to `None`. + on_end: Called after the `Runnable` finishes running, with the `Run` + object. Defaults to `None`. + on_error: Called if the `Runnable` throws an error, with the `Run` + object. Defaults to `None`. Returns: - A new ``Runnable`` with the listeners bound. + A new `Runnable` with the listeners bound. """ def listener_config_factory(config: RunnableConfig) -> RunnableConfig: @@ -6004,16 +6000,16 @@ RunnableLike = ( def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]: - """Coerce a ``Runnable``-like object into a ``Runnable``. + """Coerce a `Runnable`-like object into a `Runnable`. Args: - thing: A ``Runnable``-like object. + thing: A `Runnable`-like object. Returns: - A ``Runnable``. + A `Runnable`. Raises: - TypeError: If the object is not ``Runnable``-like. + TypeError: If the object is not `Runnable`-like. """ if isinstance(thing, Runnable): return thing @@ -6060,16 +6056,16 @@ def chain( | Callable[[Input], Coroutine[Any, Any, Output]] | Callable[[Input], AsyncIterator[Output]], ) -> Runnable[Input, Output]: - """Decorate a function to make it a ``Runnable``. + """Decorate a function to make it a `Runnable`. - Sets the name of the ``Runnable`` to the name of the function. + Sets the name of the `Runnable` to the name of the function. Any runnables called by the function will be traced as dependencies. Args: func: A ``Callable``. Returns: - A ``Runnable``. + A `Runnable`. Example: ```python diff --git a/libs/core/langchain_core/runnables/branch.py b/libs/core/langchain_core/runnables/branch.py index 1adb42a8d48..4b433c56b4f 100644 --- a/libs/core/langchain_core/runnables/branch.py +++ b/libs/core/langchain_core/runnables/branch.py @@ -191,7 +191,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]): Args: input: The input to the Runnable. - config: The configuration for the Runnable. Defaults to None. + config: The configuration for the Runnable. Defaults to `None`. kwargs: Additional keyword arguments to pass to the Runnable. Returns: @@ -301,7 +301,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]): Args: input: The input to the Runnable. - config: The configuration for the Runnable. Defaults to None. + config: The configuration for the Runnable. Defaults to `None`. kwargs: Additional keyword arguments to pass to the Runnable. Yields: @@ -385,7 +385,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]): Args: input: The input to the Runnable. - config: The configuration for the Runnable. Defaults to None. + config: The configuration for the Runnable. Defaults to `None`. kwargs: Additional keyword arguments to pass to the Runnable. Yields: diff --git a/libs/core/langchain_core/runnables/config.py b/libs/core/langchain_core/runnables/config.py index a8ffcd7bf12..c14b114a5ad 100644 --- a/libs/core/langchain_core/runnables/config.py +++ b/libs/core/langchain_core/runnables/config.py @@ -194,7 +194,7 @@ def ensure_config(config: RunnableConfig | None = None) -> RunnableConfig: Args: config (Optional[RunnableConfig], optional): The config to ensure. - Defaults to None. + Defaults to `None`. Returns: RunnableConfig: The ensured config. @@ -304,14 +304,14 @@ def patch_config( Args: config (Optional[RunnableConfig]): The config to patch. callbacks (Optional[BaseCallbackManager], optional): The callbacks to set. - Defaults to None. + Defaults to `None`. recursion_limit (Optional[int], optional): The recursion limit to set. - Defaults to None. + Defaults to `None`. max_concurrency (Optional[int], optional): The max concurrency to set. - Defaults to None. - run_name (Optional[str], optional): The run name to set. Defaults to None. + Defaults to `None`. + run_name (Optional[str], optional): The run name to set. Defaults to `None`. configurable (Optional[dict[str, Any]], optional): The configurable to set. - Defaults to None. + Defaults to `None`. Returns: RunnableConfig: The patched config. @@ -418,7 +418,7 @@ def call_func_with_variable_args( func: The function to call. input: The input to the function. config: The config to pass to the function. - run_manager: The run manager to pass to the function. Defaults to None. + run_manager: The run manager to pass to the function. Defaults to `None`. **kwargs: The keyword arguments to pass to the function. Returns: @@ -452,7 +452,7 @@ def acall_func_with_variable_args( func: The function to call. input: The input to the function. config: The config to pass to the function. - run_manager: The run manager to pass to the function. Defaults to None. + run_manager: The run manager to pass to the function. Defaults to `None`. **kwargs: The keyword arguments to pass to the function. Returns: @@ -542,7 +542,7 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor): fn (Callable[..., T]): The function to map. *iterables (Iterable[Any]): The iterables to map over. timeout (float | None, optional): The timeout for the map. - Defaults to None. + Defaults to `None`. chunksize (int, optional): The chunksize for the map. Defaults to 1. Returns: diff --git a/libs/core/langchain_core/runnables/configurable.py b/libs/core/langchain_core/runnables/configurable.py index 6f6cab8fa12..8983c71d0e4 100644 --- a/libs/core/langchain_core/runnables/configurable.py +++ b/libs/core/langchain_core/runnables/configurable.py @@ -49,8 +49,8 @@ if TYPE_CHECKING: class DynamicRunnable(RunnableSerializable[Input, Output]): """Serializable Runnable that can be dynamically configured. - A DynamicRunnable should be initiated using the ``configurable_fields`` or - ``configurable_alternatives`` method of a Runnable. + A DynamicRunnable should be initiated using the `configurable_fields` or + `configurable_alternatives` method of a Runnable. """ default: RunnableSerializable[Input, Output] @@ -123,7 +123,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]): """Prepare the Runnable for invocation. Args: - config: The configuration to use. Defaults to None. + config: The configuration to use. Defaults to `None`. Returns: tuple[Runnable[Input, Output], RunnableConfig]: The prepared Runnable and @@ -541,7 +541,7 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]): """The alternatives to choose from.""" default_key: str = "default" - """The enum value to use for the default option. Defaults to ``'default'``.""" + """The enum value to use for the default option. Defaults to `'default'`.""" prefix_keys: bool """Whether to prefix configurable fields of each alternative with a namespace diff --git a/libs/core/langchain_core/runnables/fallbacks.py b/libs/core/langchain_core/runnables/fallbacks.py index 7bb97745447..1082ecca588 100644 --- a/libs/core/langchain_core/runnables/fallbacks.py +++ b/libs/core/langchain_core/runnables/fallbacks.py @@ -97,7 +97,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]): """ exception_key: str | None = None """If string is specified then handled exceptions will be passed to fallbacks as - part of the input under the specified key. If None, exceptions + part of the input under the specified key. If `None`, exceptions will not be passed to fallbacks. If used, the base Runnable and its fallbacks must accept a dictionary as input.""" diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.py index 50e2535d83d..9088fd02433 100644 --- a/libs/core/langchain_core/runnables/graph.py +++ b/libs/core/langchain_core/runnables/graph.py @@ -69,16 +69,16 @@ class Edge(NamedTuple): target: str """The target node id.""" data: Stringifiable | None = None - """Optional data associated with the edge. Defaults to None.""" + """Optional data associated with the edge. Defaults to `None`.""" conditional: bool = False - """Whether the edge is conditional. Defaults to False.""" + """Whether the edge is conditional. Defaults to `False`.""" def copy(self, *, source: str | None = None, target: str | None = None) -> Edge: """Return a copy of the edge with optional new source and target nodes. Args: - source: The new source node id. Defaults to None. - target: The new target node id. Defaults to None. + source: The new source node id. Defaults to `None`. + target: The new target node id. Defaults to `None`. Returns: A copy of the edge with the new source and target nodes. @@ -101,7 +101,7 @@ class Node(NamedTuple): data: type[BaseModel] | RunnableType | None """The data of the node.""" metadata: dict[str, Any] | None - """Optional metadata for the node. Defaults to None.""" + """Optional metadata for the node. Defaults to `None`.""" def copy( self, @@ -112,8 +112,8 @@ class Node(NamedTuple): """Return a copy of the node with optional new id and name. Args: - id: The new node id. Defaults to None. - name: The new node name. Defaults to None. + id: The new node id. Defaults to `None`. + name: The new node name. Defaults to `None`. Returns: A copy of the node with the new id and name. @@ -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. Defaults to None.""" + """Optional dictionary of end node ids for the branches. Defaults to `None`.""" class CurveStyle(Enum): @@ -203,7 +203,7 @@ def node_data_json( Args: node: The node to convert. with_schemas: Whether to include the schema of the data if - it is a Pydantic model. Defaults to False. + it is a Pydantic model. Defaults to `False`. Returns: A dictionary with the type of the data and the data itself. @@ -267,7 +267,7 @@ class Graph: Args: with_schemas: Whether to include the schemas of the nodes if they are - Pydantic models. Defaults to False. + Pydantic models. Defaults to `False`. Returns: A dictionary with the nodes and edges of the graph. @@ -321,8 +321,8 @@ class Graph: Args: data: The data of the node. - id: The id of the node. Defaults to None. - metadata: Optional metadata for the node. Defaults to None. + id: The id of the node. Defaults to `None`. + metadata: Optional metadata for the node. Defaults to `None`. Returns: The node that was added to the graph. @@ -361,8 +361,8 @@ class Graph: Args: source: The source node of the edge. target: The target node of the edge. - data: Optional data associated with the edge. Defaults to None. - conditional: Whether the edge is conditional. Defaults to False. + data: Optional data associated with the edge. Defaults to `None`. + conditional: Whether the edge is conditional. Defaults to `False`. Returns: The edge that was added to the graph. @@ -548,10 +548,11 @@ class Graph: """Draw the graph as a PNG image. Args: - output_file_path: The path to save the image to. If None, the image - is not saved. Defaults to None. - fontname: The name of the font to use. Defaults to None. - labels: Optional labels for nodes and edges in the graph. Defaults to None. + output_file_path: The path to save the image to. If `None`, the image + is not saved. Defaults to `None`. + fontname: The name of the font to use. Defaults to `None`. + labels: Optional labels for nodes and edges in the graph. Defaults to + `None`. Returns: The PNG image as bytes if output_file_path is None, None otherwise. @@ -584,14 +585,14 @@ class Graph: """Draw the graph as a Mermaid syntax string. Args: - with_styles: Whether to include styles in the syntax. Defaults to True. + with_styles: Whether to include styles in the syntax. Defaults to `True`. curve_style: The style of the edges. Defaults to CurveStyle.LINEAR. node_colors: The colors of the nodes. Defaults to NodeStyles(). wrap_label_n_words: The number of words to wrap the node labels at. Defaults to 9. frontmatter_config (dict[str, Any], optional): Mermaid frontmatter config. Can be used to customize theme and styles. Will be converted to YAML and - added to the beginning of the mermaid graph. Defaults to None. + added to the beginning of the mermaid graph. Defaults to `None`. See more here: https://mermaid.js.org/config/configuration.html. @@ -650,8 +651,8 @@ class Graph: node_colors: The colors of the nodes. Defaults to NodeStyles(). wrap_label_n_words: The number of words to wrap the node labels at. Defaults to 9. - output_file_path: The path to save the image to. If None, the image - is not saved. Defaults to None. + output_file_path: The path to save the image to. If `None`, the image + is not saved. Defaults to `None`. draw_method: The method to use to draw the graph. Defaults to MermaidDrawMethod.API. background_color: The color of the background. Defaults to "white". @@ -662,7 +663,7 @@ class Graph: Defaults to 1.0. frontmatter_config (dict[str, Any], optional): Mermaid frontmatter config. Can be used to customize theme and styles. Will be converted to YAML and - added to the beginning of the mermaid graph. Defaults to None. + added to the beginning of the mermaid graph. Defaults to `None`. See more here: https://mermaid.js.org/config/configuration.html. @@ -678,7 +679,7 @@ class Graph: } ``` base_url: The base URL of the Mermaid server for rendering via API. - Defaults to None. + Defaults to `None`. Returns: The PNG image as bytes. diff --git a/libs/core/langchain_core/runnables/graph_mermaid.py b/libs/core/langchain_core/runnables/graph_mermaid.py index ac70dee638b..07d508e5421 100644 --- a/libs/core/langchain_core/runnables/graph_mermaid.py +++ b/libs/core/langchain_core/runnables/graph_mermaid.py @@ -59,10 +59,10 @@ def draw_mermaid( nodes (dict[str, str]): List of node ids. edges (list[Edge]): List of edges, object with a source, target and data. - first_node (str, optional): Id of the first node. Defaults to None. - last_node (str, optional): Id of the last node. Defaults to None. + first_node (str, optional): Id of the first node. Defaults to `None`. + last_node (str, optional): Id of the last node. Defaults to `None`. with_styles (bool, optional): Whether to include styles in the graph. - Defaults to True. + Defaults to `True`. curve_style (CurveStyle, optional): Curve style for the edges. Defaults to CurveStyle.LINEAR. node_styles (NodeStyles, optional): Node colors for different types. @@ -71,7 +71,7 @@ def draw_mermaid( Defaults to 9. frontmatter_config (dict[str, Any], optional): Mermaid frontmatter config. Can be used to customize theme and styles. Will be converted to YAML and - added to the beginning of the mermaid graph. Defaults to None. + added to the beginning of the mermaid graph. Defaults to `None`. See more here: https://mermaid.js.org/config/configuration.html. @@ -292,7 +292,7 @@ def draw_mermaid_png( Args: mermaid_syntax (str): Mermaid graph syntax. output_file_path (str, optional): Path to save the PNG image. - Defaults to None. + Defaults to `None`. draw_method (MermaidDrawMethod, optional): Method to draw the graph. Defaults to MermaidDrawMethod.API. background_color (str, optional): Background color of the image. @@ -303,7 +303,7 @@ def draw_mermaid_png( retry_delay (float, optional): Delay between retries (MermaidDrawMethod.API). Defaults to 1.0. base_url (str, optional): Base URL for the Mermaid.ink API. - Defaults to None. + Defaults to `None`. Returns: bytes: PNG image bytes. diff --git a/libs/core/langchain_core/runnables/graph_png.py b/libs/core/langchain_core/runnables/graph_png.py index c23ae6a9e5e..73e8b495ef6 100644 --- a/libs/core/langchain_core/runnables/graph_png.py +++ b/libs/core/langchain_core/runnables/graph_png.py @@ -45,7 +45,7 @@ class PngDrawer: } } The keys are the original labels, and the values are the new labels. - Defaults to None. + Defaults to `None`. """ self.fontname = fontname or "arial" self.labels = labels or LabelsDict(nodes={}, edges={}) @@ -104,8 +104,8 @@ class PngDrawer: viz: The graphviz object. source: The source node. target: The target node. - label: The label for the edge. Defaults to None. - conditional: Whether the edge is conditional. Defaults to False. + label: The label for the edge. Defaults to `None`. + conditional: Whether the edge is conditional. Defaults to `False`. """ viz.add_edge( source, @@ -123,7 +123,7 @@ class PngDrawer: Args: graph: The graph to draw - output_path: The path to save the PNG. If None, PNG bytes are returned. + output_path: The path to save the PNG. If `None`, PNG bytes are returned. Raises: ImportError: If ``pygraphviz`` is not installed. diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.py index 439050d3927..96e92e8a897 100644 --- a/libs/core/langchain_core/runnables/history.py +++ b/libs/core/langchain_core/runnables/history.py @@ -260,18 +260,18 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef] runnable: The base Runnable to be wrapped. Must take as input one of: - 1. A list of ``BaseMessage`` + 1. A list of `BaseMessage` 2. A dict with one key for all messages 3. A dict with one key for the current input string/message(s) and a separate key for historical messages. If the input key points - to a string, it will be treated as a ``HumanMessage`` in history. + to a string, it will be treated as a `HumanMessage` in history. Must return as output one of: - 1. A string which can be treated as an ``AIMessage`` - 2. A ``BaseMessage`` or sequence of ``BaseMessage`` - 3. A dict with a key for a ``BaseMessage`` or sequence of - ``BaseMessage`` + 1. A string which can be treated as an `AIMessage` + 2. A `BaseMessage` or sequence of `BaseMessage` + 3. A dict with a key for a `BaseMessage` or sequence of + `BaseMessage` get_session_history: Function that returns a new BaseChatMessageHistory. This function should either take a single positional argument @@ -400,11 +400,11 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef] def get_output_schema( self, config: RunnableConfig | None = None ) -> type[BaseModel]: - """Get a pydantic model that can be used to validate output to the Runnable. + """Get a Pydantic model that can be used to validate output to the `Runnable`. - Runnables that leverage the configurable_fields and configurable_alternatives - methods will have a dynamic output schema that depends on which - configuration the Runnable is invoked with. + `Runnable` objects that leverage the `configurable_fields` and + `configurable_alternatives` methods will have a dynamic output schema that + depends on which configuration the `Runnable` is invoked with. This method allows to get an output schema for a specific configuration. @@ -412,7 +412,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef] config: A config to use when generating the schema. Returns: - A pydantic model that can be used to validate output. + A Pydantic model that can be used to validate output. """ root_type = self.OutputType diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.py index 1425239a589..017f4e1783a 100644 --- a/libs/core/langchain_core/runnables/utils.py +++ b/libs/core/langchain_core/runnables/utils.py @@ -137,7 +137,7 @@ def coro_with_context( Args: coro: The coroutine to await. context: The context to use. - create_task: Whether to create a task. Defaults to False. + create_task: Whether to create a task. Defaults to `False`. Returns: The coroutine with the context. @@ -554,13 +554,13 @@ class ConfigurableField(NamedTuple): id: str """The unique identifier of the field.""" name: str | None = None - """The name of the field. Defaults to None.""" + """The name of the field. Defaults to `None`.""" description: str | None = None - """The description of the field. Defaults to None.""" + """The description of the field. Defaults to `None`.""" annotation: Any | None = None - """The annotation of the field. Defaults to None.""" + """The annotation of the field. Defaults to `None`.""" is_shared: bool = False - """Whether the field is shared. Defaults to False.""" + """Whether the field is shared. Defaults to `False`.""" @override def __hash__(self) -> int: @@ -577,11 +577,11 @@ class ConfigurableFieldSingleOption(NamedTuple): default: str """The default value for the field.""" name: str | None = None - """The name of the field. Defaults to None.""" + """The name of the field. Defaults to `None`.""" description: str | None = None - """The description of the field. Defaults to None.""" + """The description of the field. Defaults to `None`.""" is_shared: bool = False - """Whether the field is shared. Defaults to False.""" + """Whether the field is shared. Defaults to `False`.""" @override def __hash__(self) -> int: @@ -598,11 +598,11 @@ class ConfigurableFieldMultiOption(NamedTuple): default: Sequence[str] """The default values for the field.""" name: str | None = None - """The name of the field. Defaults to None.""" + """The name of the field. Defaults to `None`.""" description: str | None = None - """The description of the field. Defaults to None.""" + """The description of the field. Defaults to `None`.""" is_shared: bool = False - """Whether the field is shared. Defaults to False.""" + """Whether the field is shared. Defaults to `False`.""" @override def __hash__(self) -> int: @@ -622,15 +622,15 @@ class ConfigurableFieldSpec(NamedTuple): annotation: Any """The annotation of the field.""" name: str | None = None - """The name of the field. Defaults to None.""" + """The name of the field. Defaults to `None`.""" description: str | None = None - """The description of the field. Defaults to None.""" + """The description of the field. Defaults to `None`.""" default: Any = None - """The default value for the field. Defaults to None.""" + """The default value for the field. Defaults to `None`.""" is_shared: bool = False - """Whether the field is shared. Defaults to False.""" + """Whether the field is shared. Defaults to `False`.""" dependencies: list[str] | None = None - """The dependencies of the field. Defaults to None.""" + """The dependencies of the field. Defaults to `None`.""" def get_unique_config_specs( diff --git a/libs/core/langchain_core/stores.py b/libs/core/langchain_core/stores.py index 0e5a25e6e6f..a1ee2b8afd2 100644 --- a/libs/core/langchain_core/stores.py +++ b/libs/core/langchain_core/stores.py @@ -235,7 +235,7 @@ class InMemoryBaseStore(BaseStore[str, V], Generic[V]): """Get an iterator over keys that match the given prefix. Args: - prefix (str, optional): The prefix to match. Defaults to None. + prefix (str, optional): The prefix to match. Defaults to `None`. Yields: Iterator[str]: An iterator over keys that match the given prefix. @@ -251,7 +251,7 @@ class InMemoryBaseStore(BaseStore[str, V], Generic[V]): """Async get an async iterator over keys that match the given prefix. Args: - prefix (str, optional): The prefix to match. Defaults to None. + prefix (str, optional): The prefix to match. Defaults to `None`. Yields: AsyncIterator[str]: An async iterator over keys that match the given prefix. diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py index d429b59cf29..ebe370bc303 100644 --- a/libs/core/langchain_core/tools/base.py +++ b/libs/core/langchain_core/tools/base.py @@ -293,16 +293,16 @@ def create_schema_from_function( filter_args: Optional list of arguments to exclude from the schema. Defaults to FILTERED_ARGS. parse_docstring: Whether to parse the function's docstring for descriptions - for each argument. Defaults to False. + for each argument. Defaults to `False`. error_on_invalid_docstring: if ``parse_docstring`` is provided, configure whether to raise ValueError on invalid Google Style docstrings. - Defaults to False. + Defaults to `False`. include_injected: Whether to include injected arguments in the schema. - Defaults to True, since we want to include them in the schema + Defaults to `True`, since we want to include them in the schema when *validating* tool inputs. Returns: - A pydantic model with the same arguments as the function. + A Pydantic model with the same arguments as the function. """ sig = inspect.signature(func) @@ -460,13 +460,13 @@ class ChildTool(BaseTool): """Callbacks to be called during tool execution.""" tags: list[str] | None = None - """Optional list of tags associated with the tool. Defaults to None. + """Optional list of tags associated with the tool. Defaults to `None`. These tags will be associated with each call to this tool, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a tool with its use case. """ metadata: dict[str, Any] | None = None - """Optional metadata associated with the tool. Defaults to None. + """Optional metadata associated with the tool. Defaults to `None`. This metadata will be associated with each call to this tool, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a tool with its use case. @@ -492,7 +492,7 @@ class ChildTool(BaseTool): """Initialize the tool. Raises: - TypeError: If ``args_schema`` is not a subclass of pydantic ``BaseModel`` or + TypeError: If ``args_schema`` is not a subclass of pydantic `BaseModel` or dict. """ if ( @@ -617,9 +617,9 @@ class ChildTool(BaseTool): Raises: ValueError: If string input is provided with JSON schema ``args_schema``. - ValueError: If InjectedToolCallId is required but ``tool_call_id`` is not + ValueError: If InjectedToolCallId is required but `tool_call_id` is not provided. - TypeError: If args_schema is not a Pydantic ``BaseModel`` or dict. + TypeError: If args_schema is not a Pydantic `BaseModel` or dict. """ input_args = self.args_schema if isinstance(tool_input, str): @@ -767,16 +767,16 @@ class ChildTool(BaseTool): Args: tool_input: The input to the tool. - verbose: Whether to log the tool's progress. Defaults to None. + verbose: Whether to log the tool's progress. Defaults to `None`. start_color: The color to use when starting the tool. Defaults to 'green'. color: The color to use when ending the tool. Defaults to 'green'. - callbacks: Callbacks to be called during tool execution. Defaults to None. - tags: Optional list of tags associated with the tool. Defaults to None. - metadata: Optional metadata associated with the tool. Defaults to None. - run_name: The name of the run. Defaults to None. - run_id: The id of the run. Defaults to None. - config: The configuration for the tool. Defaults to None. - tool_call_id: The id of the tool call. Defaults to None. + callbacks: Callbacks to be called during tool execution. Defaults to `None`. + tags: Optional list of tags associated with the tool. Defaults to `None`. + metadata: Optional metadata associated with the tool. Defaults to `None`. + run_name: The name of the run. Defaults to `None`. + run_id: The id of the run. Defaults to `None`. + config: The configuration for the tool. Defaults to `None`. + tool_call_id: The id of the tool call. Defaults to `None`. kwargs: Keyword arguments to be passed to tool callbacks (event handler) Returns: @@ -879,16 +879,16 @@ class ChildTool(BaseTool): Args: tool_input: The input to the tool. - verbose: Whether to log the tool's progress. Defaults to None. + verbose: Whether to log the tool's progress. Defaults to `None`. start_color: The color to use when starting the tool. Defaults to 'green'. color: The color to use when ending the tool. Defaults to 'green'. - callbacks: Callbacks to be called during tool execution. Defaults to None. - tags: Optional list of tags associated with the tool. Defaults to None. - metadata: Optional metadata associated with the tool. Defaults to None. - run_name: The name of the run. Defaults to None. - run_id: The id of the run. Defaults to None. - config: The configuration for the tool. Defaults to None. - tool_call_id: The id of the tool call. Defaults to None. + callbacks: Callbacks to be called during tool execution. Defaults to `None`. + tags: Optional list of tags associated with the tool. Defaults to `None`. + metadata: Optional metadata associated with the tool. Defaults to `None`. + run_name: The name of the run. Defaults to `None`. + run_id: The id of the run. Defaults to `None`. + config: The configuration for the tool. Defaults to `None`. + tool_call_id: The id of the tool call. Defaults to `None`. kwargs: Keyword arguments to be passed to tool callbacks Returns: diff --git a/libs/core/langchain_core/tools/convert.py b/libs/core/langchain_core/tools/convert.py index 53c43acd568..30f7bfab4fa 100644 --- a/libs/core/langchain_core/tools/convert.py +++ b/libs/core/langchain_core/tools/convert.py @@ -99,13 +99,13 @@ def tool( (used only if `description` / docstring are not provided) *args: Extra positional arguments. Must be empty. return_direct: Whether to return directly from the tool rather - than continuing the agent loop. Defaults to False. + than continuing the agent loop. Defaults to `False`. args_schema: optional argument schema for user to specify. - Defaults to None. + Defaults to `None`. infer_schema: Whether to infer the schema of the arguments from the function's signature. This also makes the resultant tool accept a dictionary input to its `run()` function. - Defaults to True. + Defaults to `True`. response_format: The tool response format. If "content" then the output of the tool is interpreted as the contents of a ToolMessage. If "content_and_artifact" then the output is expected to be a two-tuple @@ -113,10 +113,10 @@ def tool( Defaults to "content". parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt to parse parameter descriptions from Google Style function docstrings. - Defaults to False. + Defaults to `False`. error_on_invalid_docstring: if ``parse_docstring`` is provided, configure whether to raise ValueError on invalid Google Style docstrings. - Defaults to True. + Defaults to `True`. Raises: ValueError: If too many positional arguments are provided. @@ -397,10 +397,10 @@ def convert_runnable_to_tool( Args: runnable: The runnable to convert. - args_schema: The schema for the tool's input arguments. Defaults to None. - name: The name of the tool. Defaults to None. - description: The description of the tool. Defaults to None. - arg_types: The types of the arguments. Defaults to None. + args_schema: The schema for the tool's input arguments. Defaults to `None`. + name: The name of the tool. Defaults to `None`. + description: The description of the tool. Defaults to `None`. + arg_types: The types of the arguments. Defaults to `None`. Returns: The tool. diff --git a/libs/core/langchain_core/tools/retriever.py b/libs/core/langchain_core/tools/retriever.py index e5ff95049fe..fff2fe3fe87 100644 --- a/libs/core/langchain_core/tools/retriever.py +++ b/libs/core/langchain_core/tools/retriever.py @@ -81,7 +81,7 @@ def create_retriever_tool( so should be unique and somewhat descriptive. description: The description for the tool. This will be passed to the language model, so should be descriptive. - document_prompt: The prompt to use for the document. Defaults to None. + document_prompt: The prompt to use for the document. Defaults to `None`. document_separator: The separator to use between documents. Defaults to "\n\n". response_format: The tool response format. If "content" then the output of the tool is interpreted as the contents of a ToolMessage. If diff --git a/libs/core/langchain_core/tools/simple.py b/libs/core/langchain_core/tools/simple.py index a1524b099fd..658ab5f4256 100644 --- a/libs/core/langchain_core/tools/simple.py +++ b/libs/core/langchain_core/tools/simple.py @@ -177,9 +177,9 @@ class Tool(BaseTool): func: The function to create the tool from. name: The name of the tool. description: The description of the tool. - return_direct: Whether to return the output directly. Defaults to False. - args_schema: The schema of the tool's input arguments. Defaults to None. - coroutine: The asynchronous version of the function. Defaults to None. + return_direct: Whether to return the output directly. Defaults to `False`. + args_schema: The schema of the tool's input arguments. Defaults to `None`. + coroutine: The asynchronous version of the function. Defaults to `None`. kwargs: Additional arguments to pass to the tool. Returns: diff --git a/libs/core/langchain_core/tools/structured.py b/libs/core/langchain_core/tools/structured.py index 4beeb9f68ea..ac9a46b30ee 100644 --- a/libs/core/langchain_core/tools/structured.py +++ b/libs/core/langchain_core/tools/structured.py @@ -149,10 +149,10 @@ class StructuredTool(BaseTool): description: The description of the tool. Defaults to the function docstring. return_direct: Whether to return the result directly or as a callback. - Defaults to False. - args_schema: The schema of the tool's input arguments. Defaults to None. + Defaults to `False`. + args_schema: The schema of the tool's input arguments. Defaults to `None`. infer_schema: Whether to infer the schema from the function's signature. - Defaults to True. + Defaults to `True`. response_format: The tool response format. If "content" then the output of the tool is interpreted as the contents of a ToolMessage. If "content_and_artifact" then the output is expected to be a two-tuple @@ -160,10 +160,10 @@ class StructuredTool(BaseTool): Defaults to "content". parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt to parse parameter descriptions from Google Style function docstrings. - Defaults to False. + Defaults to `False`. error_on_invalid_docstring: if ``parse_docstring`` is provided, configure whether to raise ValueError on invalid Google Style docstrings. - Defaults to False. + Defaults to `False`. kwargs: Additional arguments to pass to the tool Returns: @@ -173,7 +173,7 @@ class StructuredTool(BaseTool): ValueError: If the function is not provided. ValueError: If the function does not have a docstring and description is not provided. - TypeError: If the ``args_schema`` is not a ``BaseModel`` or dict. + TypeError: If the ``args_schema`` is not a `BaseModel` or dict. Examples: diff --git a/libs/core/langchain_core/tracers/base.py b/libs/core/langchain_core/tracers/base.py index bf8188f75c7..80e112b7d9a 100644 --- a/libs/core/langchain_core/tracers/base.py +++ b/libs/core/langchain_core/tracers/base.py @@ -67,9 +67,9 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): serialized: The serialized model. messages: The messages to start the chat with. run_id: The run ID. - tags: The tags for the run. Defaults to None. - parent_run_id: The parent run ID. Defaults to None. - metadata: The metadata for the run. Defaults to None. + tags: The tags for the run. Defaults to `None`. + parent_run_id: The parent run ID. Defaults to `None`. + metadata: The metadata for the run. Defaults to `None`. name: The name of the run. kwargs: Additional arguments. @@ -108,9 +108,9 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): serialized: The serialized model. prompts: The prompts to start the LLM with. run_id: The run ID. - tags: The tags for the run. Defaults to None. - parent_run_id: The parent run ID. Defaults to None. - metadata: The metadata for the run. Defaults to None. + tags: The tags for the run. Defaults to `None`. + parent_run_id: The parent run ID. Defaults to `None`. + metadata: The metadata for the run. Defaults to `None`. name: The name of the run. kwargs: Additional arguments. @@ -145,9 +145,9 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): Args: token: The token. - chunk: The chunk. Defaults to None. + chunk: The chunk. Defaults to `None`. run_id: The run ID. - parent_run_id: The parent run ID. Defaults to None. + parent_run_id: The parent run ID. Defaults to `None`. kwargs: Additional arguments. Returns: @@ -255,10 +255,10 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): serialized: The serialized chain. inputs: The inputs for the chain. run_id: The run ID. - tags: The tags for the run. Defaults to None. - parent_run_id: The parent run ID. Defaults to None. - metadata: The metadata for the run. Defaults to None. - run_type: The type of the run. Defaults to None. + tags: The tags for the run. Defaults to `None`. + parent_run_id: The parent run ID. Defaults to `None`. + metadata: The metadata for the run. Defaults to `None`. + run_type: The type of the run. Defaults to `None`. name: The name of the run. kwargs: Additional arguments. @@ -294,7 +294,7 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): Args: outputs: The outputs for the chain. run_id: The run ID. - inputs: The inputs for the chain. Defaults to None. + inputs: The inputs for the chain. Defaults to `None`. kwargs: Additional arguments. Returns: @@ -322,7 +322,7 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): Args: error: The error. - inputs: The inputs for the chain. Defaults to None. + inputs: The inputs for the chain. Defaults to `None`. run_id: The run ID. kwargs: Additional arguments. @@ -357,9 +357,9 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): serialized: The serialized tool. input_str: The input string. run_id: The run ID. - tags: The tags for the run. Defaults to None. - parent_run_id: The parent run ID. Defaults to None. - metadata: The metadata for the run. Defaults to None. + tags: The tags for the run. Defaults to `None`. + parent_run_id: The parent run ID. Defaults to `None`. + metadata: The metadata for the run. Defaults to `None`. name: The name of the run. inputs: The inputs for the tool. kwargs: Additional arguments. @@ -446,9 +446,9 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC): serialized: The serialized retriever. query: The query. run_id: The run ID. - parent_run_id: The parent run ID. Defaults to None. - tags: The tags for the run. Defaults to None. - metadata: The metadata for the run. Defaults to None. + parent_run_id: The parent run ID. Defaults to `None`. + tags: The tags for the run. Defaults to `None`. + metadata: The metadata for the run. Defaults to `None`. name: The name of the run. kwargs: Additional arguments. diff --git a/libs/core/langchain_core/tracers/context.py b/libs/core/langchain_core/tracers/context.py index c630026c3a9..d09ba5f40e1 100644 --- a/libs/core/langchain_core/tracers/context.py +++ b/libs/core/langchain_core/tracers/context.py @@ -48,13 +48,13 @@ def tracing_v2_enabled( Args: project_name (str, optional): The name of the project. - Defaults to ``'default'``. + Defaults to `'default'`. example_id (str or UUID, optional): The ID of the example. - Defaults to None. + Defaults to `None`. tags (list[str], optional): The tags to add to the run. - Defaults to None. + Defaults to `None`. client (LangSmithClient, optional): The client of the langsmith. - Defaults to None. + Defaults to `None`. Yields: LangChainTracer: The LangChain tracer. @@ -182,8 +182,8 @@ def register_configure_hook( context_var (ContextVar[Optional[Any]]): The context variable. inheritable (bool): Whether the context variable is inheritable. handle_class (Optional[Type[BaseCallbackHandler]], optional): - The callback handler class. Defaults to None. - env_var (Optional[str], optional): The environment variable. Defaults to None. + The callback handler class. Defaults to `None`. + env_var (Optional[str], optional): The environment variable. Defaults to `None`. Raises: ValueError: If env_var is set, handle_class must also be set diff --git a/libs/core/langchain_core/tracers/langchain.py b/libs/core/langchain_core/tracers/langchain.py index d1bd4c89b1e..d37eccabf9c 100644 --- a/libs/core/langchain_core/tracers/langchain.py +++ b/libs/core/langchain_core/tracers/langchain.py @@ -134,10 +134,10 @@ class LangChainTracer(BaseTracer): serialized: The serialized model. messages: The messages. run_id: The run ID. - tags: The tags. Defaults to None. - parent_run_id: The parent run ID. Defaults to None. - metadata: The metadata. Defaults to None. - name: The name. Defaults to None. + tags: The tags. Defaults to `None`. + parent_run_id: The parent run ID. Defaults to `None`. + metadata: The metadata. Defaults to `None`. + name: The name. Defaults to `None`. kwargs: Additional keyword arguments. Returns: diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.py index 8822bc92d91..26cedf60960 100644 --- a/libs/core/langchain_core/tracers/log_stream.py +++ b/libs/core/langchain_core/tracers/log_stream.py @@ -659,7 +659,7 @@ async def _astream_log_implementation( stream: The stream to send the run logs to. diff: Whether to yield run log patches (True) or full run logs (False). with_streamed_output_list: Whether to include a list of all streamed - outputs in each patch. If False, only the final output will be included + outputs in each patch. If `False`, only the final output will be included in the patches. **kwargs: Additional keyword arguments to pass to the runnable. diff --git a/libs/core/langchain_core/utils/aiter.py b/libs/core/langchain_core/utils/aiter.py index 8c7598be92d..085420efde7 100644 --- a/libs/core/langchain_core/utils/aiter.py +++ b/libs/core/langchain_core/utils/aiter.py @@ -203,7 +203,7 @@ class Tee(Generic[T]): iterable: The iterable to split. n: The number of iterators to create. Defaults to 2. lock: The lock to synchronise access to the shared buffers. - Defaults to None. + Defaults to `None`. """ self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist self._buffers: list[deque[T]] = [deque() for _ in range(n)] diff --git a/libs/core/langchain_core/utils/env.py b/libs/core/langchain_core/utils/env.py index 0256518cce1..dd593dc2dad 100644 --- a/libs/core/langchain_core/utils/env.py +++ b/libs/core/langchain_core/utils/env.py @@ -38,7 +38,7 @@ def get_from_dict_or_env( env_key: The environment variable to look up if the key is not in the dictionary. default: The default value to return if the key is not in the dictionary - or the environment. Defaults to None. + or the environment. Defaults to `None`. Returns: The dict value or the environment variable value. @@ -64,7 +64,7 @@ def get_from_env(key: str, env_key: str, default: str | None = None) -> str: env_key: The environment variable to look up if the key is not in the dictionary. default: The default value to return if the key is not in the dictionary - or the environment. Defaults to None. + or the environment. Defaults to `None`. Returns: str: The value of the key. diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.py index 47189f4624c..8c9edb57373 100644 --- a/libs/core/langchain_core/utils/function_calling.py +++ b/libs/core/langchain_core/utils/function_calling.py @@ -114,7 +114,7 @@ def _convert_json_schema_to_openai_function( used. description: The description of the function. If not provided, the description of the schema will be used. - rm_titles: Whether to remove titles from the schema. Defaults to True. + rm_titles: Whether to remove titles from the schema. Defaults to `True`. Returns: The function description. @@ -148,7 +148,7 @@ def _convert_pydantic_to_openai_function( used. description: The description of the function. If not provided, the description of the schema will be used. - rm_titles: Whether to remove titles from the schema. Defaults to True. + rm_titles: Whether to remove titles from the schema. Defaults to `True`. Raises: TypeError: If the model is not a Pydantic model. @@ -408,8 +408,8 @@ def convert_to_openai_function( top-level 'title' key specified, an Anthropic format tool, or an Amazon Bedrock Converse format tool. strict: - If True, model output is guaranteed to exactly match the JSON Schema - provided in the function definition. If None, ``strict`` argument will not + If `True`, model output is guaranteed to exactly match the JSON Schema + provided in the function definition. If `None`, ``strict`` argument will not be included in function definition. Returns: @@ -538,8 +538,8 @@ def convert_to_openai_tool( top-level 'title' key specified, an Anthropic format tool, or an Amazon Bedrock Converse format tool. strict: - If True, model output is guaranteed to exactly match the JSON Schema - provided in the function definition. If None, ``strict`` argument will not + If `True`, model output is guaranteed to exactly match the JSON Schema + provided in the function definition. If `None`, ``strict`` argument will not be included in tool definition. Returns: @@ -601,8 +601,8 @@ def convert_to_json_schema( Args: schema: The schema to convert. - strict: If True, model output is guaranteed to exactly match the JSON Schema - provided in the function definition. If None, ``strict`` argument will not + strict: If `True`, model output is guaranteed to exactly match the JSON Schema + provided in the function definition. If `None`, ``strict`` argument will not be included in function definition. Raises: @@ -649,15 +649,15 @@ def tool_example_to_messages( The list of messages per example by default corresponds to: - 1. ``HumanMessage``: contains the content from which content should be extracted. - 2. ``AIMessage``: contains the extracted information from the model - 3. ``ToolMessage``: contains confirmation to the model that the model requested a + 1. `HumanMessage`: contains the content from which content should be extracted. + 2. `AIMessage`: contains the extracted information from the model + 3. `ToolMessage`: contains confirmation to the model that the model requested a tool correctly. - If ``ai_response`` is specified, there will be a final ``AIMessage`` with that + If ``ai_response`` is specified, there will be a final `AIMessage` with that response. - The ``ToolMessage`` is required because some chat models are hyper-optimized for + The `ToolMessage` is required because some chat models are hyper-optimized for agents rather than for an extraction use case. Args: @@ -665,8 +665,8 @@ def tool_example_to_messages( tool_calls: Tool calls represented as Pydantic BaseModels tool_outputs: Tool call outputs. Does not need to be provided. If not provided, a placeholder value - will be inserted. Defaults to None. - ai_response: If provided, content for a final ``AIMessage``. + will be inserted. Defaults to `None`. + ai_response: If provided, content for a final `AIMessage`. Returns: A list of messages diff --git a/libs/core/langchain_core/utils/html.py b/libs/core/langchain_core/utils/html.py index a0054e613b3..df0687845dd 100644 --- a/libs/core/langchain_core/utils/html.py +++ b/libs/core/langchain_core/utils/html.py @@ -66,10 +66,10 @@ def extract_sub_links( url: the url of the HTML. base_url: the base URL to check for outside links against. pattern: Regex to use for extracting links from raw HTML. - prevent_outside: If True, ignore external links which are not children + prevent_outside: If `True`, ignore external links which are not children of the base URL. exclude_prefixes: Exclude any URLs that start with one of these prefixes. - continue_on_failure: If True, continue if parsing a specific link raises an + continue_on_failure: If `True`, continue if parsing a specific link raises an exception. Otherwise, raise the exception. Returns: diff --git a/libs/core/langchain_core/utils/input.py b/libs/core/langchain_core/utils/input.py index b5f9fea712c..bedb58cb625 100644 --- a/libs/core/langchain_core/utils/input.py +++ b/libs/core/langchain_core/utils/input.py @@ -65,9 +65,9 @@ def print_text( Args: text: The text to print. - color: The color to use. Defaults to None. + color: The color to use. Defaults to `None`. end: The end character to use. Defaults to "". - file: The file to write to. Defaults to None. + file: The file to write to. Defaults to `None`. """ text_to_print = get_colored_text(text, color) if color else text print(text_to_print, end=end, file=file) diff --git a/libs/core/langchain_core/utils/iter.py b/libs/core/langchain_core/utils/iter.py index 3ed9d13e375..45a6e07019a 100644 --- a/libs/core/langchain_core/utils/iter.py +++ b/libs/core/langchain_core/utils/iter.py @@ -139,7 +139,7 @@ class Tee(Generic[T]): iterable: The iterable to split. n: The number of iterators to create. Defaults to 2. lock: The lock to synchronise access to the shared buffers. - Defaults to None. + Defaults to `None`. """ self._iterator = iter(iterable) self._buffers: list[deque[T]] = [deque() for _ in range(n)] @@ -207,7 +207,7 @@ def batch_iterate(size: int | None, iterable: Iterable[T]) -> Iterator[list[T]]: """Utility batching function. Args: - size: The size of the batch. If None, returns a single batch. + size: The size of the batch. If `None`, returns a single batch. iterable: The iterable to batch. Yields: diff --git a/libs/core/langchain_core/utils/json.py b/libs/core/langchain_core/utils/json.py index c7e28f360df..b1e3879a476 100644 --- a/libs/core/langchain_core/utils/json.py +++ b/libs/core/langchain_core/utils/json.py @@ -51,7 +51,7 @@ def parse_partial_json(s: str, *, strict: bool = False) -> Any: Args: s: The JSON string to parse. - strict: Whether to use strict parsing. Defaults to False. + strict: Whether to use strict parsing. Defaults to `False`. Returns: The parsed JSON object as a Python dictionary. diff --git a/libs/core/langchain_core/utils/json_schema.py b/libs/core/langchain_core/utils/json_schema.py index 939ac06eb01..6118bd95dc2 100644 --- a/libs/core/langchain_core/utils/json_schema.py +++ b/libs/core/langchain_core/utils/json_schema.py @@ -85,7 +85,7 @@ def _dereference_refs_helper( full_schema: The complete schema containing all definitions processed_refs: Set tracking currently processing refs (for cycle detection) skip_keys: Keys under which to skip recursion - shallow_refs: If True, only break cycles; if False, deep-inline all refs + shallow_refs: If `True`, only break cycles; if False, deep-inline all refs Returns: The object with $ref properties resolved and merged with other properties. @@ -184,7 +184,7 @@ def dereference_refs( point to. If not provided, defaults to schema_obj (useful when the schema is self-contained). skip_keys: Controls recursion behavior and reference resolution depth: - - If None (default): Only recurse under '$defs' and use shallow reference + - If `None` (Default): Only recurse under '$defs' and use shallow reference resolution (break cycles but don't deep-inline nested refs) - If provided (even as []): Recurse under all keys and use deep reference resolution (fully inline all nested references) diff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.py index 792b3596f5c..da633095c1a 100644 --- a/libs/core/langchain_core/utils/pydantic.py +++ b/libs/core/langchain_core/utils/pydantic.py @@ -78,7 +78,7 @@ def is_pydantic_v1_subclass(cls: type) -> bool: """Check if the given class is Pydantic v1-like. Returns: - True if the given class is a subclass of Pydantic ``BaseModel`` 1.x. + True if the given class is a subclass of Pydantic `BaseModel` 1.x. """ return issubclass(cls, BaseModelV1) @@ -101,7 +101,7 @@ def is_basemodel_subclass(cls: type) -> bool: * pydantic.v1.BaseModel in Pydantic 2.x Returns: - True if the given class is a subclass of Pydantic ``BaseModel``. + True if the given class is a subclass of Pydantic `BaseModel`. """ # Before we can use issubclass on the cls we need to check if it is a class if not inspect.isclass(cls) or isinstance(cls, GenericAlias): @@ -119,7 +119,7 @@ def is_basemodel_instance(obj: Any) -> bool: * pydantic.v1.BaseModel in Pydantic 2.x Returns: - True if the given class is an instance of Pydantic ``BaseModel``. + True if the given class is an instance of Pydantic `BaseModel`. """ return isinstance(obj, (BaseModel, BaseModelV1)) diff --git a/libs/core/langchain_core/utils/utils.py b/libs/core/langchain_core/utils/utils.py index 06c16ca4762..6d36f630ac7 100644 --- a/libs/core/langchain_core/utils/utils.py +++ b/libs/core/langchain_core/utils/utils.py @@ -122,9 +122,9 @@ def guard_import( Args: module_name (str): The name of the module to import. pip_name (str, optional): The name of the module to install with pip. - Defaults to None. + Defaults to `None`. package (str, optional): The package to import the module from. - Defaults to None. + Defaults to `None`. Returns: Any: The imported module. @@ -156,13 +156,13 @@ def check_package_version( Args: package (str): The name of the package. lt_version (str, optional): The version must be less than this. - Defaults to None. + Defaults to `None`. lte_version (str, optional): The version must be less than or equal to this. - Defaults to None. + Defaults to `None`. gt_version (str, optional): The version must be greater than this. - Defaults to None. + Defaults to `None`. gte_version (str, optional): The version must be greater than or equal to this. - Defaults to None. + Defaults to `None`. Raises: ValueError: If the package version does not meet the requirements. diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.py index fc8e430b287..3addb5d2322 100644 --- a/libs/core/langchain_core/vectorstores/base.py +++ b/libs/core/langchain_core/vectorstores/base.py @@ -123,7 +123,7 @@ class VectorStore(ABC): """Delete by vector ID or other criteria. Args: - ids: List of ids to delete. If None, delete all. Default is None. + ids: List of ids to delete. If `None`, delete all. Default is None. **kwargs: Other keyword arguments that subclasses might use. Returns: @@ -191,7 +191,7 @@ class VectorStore(ABC): """Async delete by vector ID or other criteria. Args: - ids: List of ids to delete. If None, delete all. Default is None. + ids: List of ids to delete. If `None`, delete all. Default is None. **kwargs: Other keyword arguments that subclasses might use. Returns: diff --git a/libs/core/langchain_core/vectorstores/in_memory.py b/libs/core/langchain_core/vectorstores/in_memory.py index a85232ed729..0ad9f928c69 100644 --- a/libs/core/langchain_core/vectorstores/in_memory.py +++ b/libs/core/langchain_core/vectorstores/in_memory.py @@ -38,7 +38,7 @@ class InMemoryVectorStore(VectorStore): Uses a dictionary, and computes cosine similarity for search using numpy. Setup: - Install ``langchain-core``. + Install `langchain-core`. .. code-block:: bash diff --git a/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr b/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr index 07cf2d3587d..9cd3d7e6e1b 100644 --- a/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr +++ b/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr @@ -385,10 +385,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -520,7 +520,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -714,7 +714,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -1113,10 +1113,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -1125,7 +1125,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -1147,7 +1147,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -1337,7 +1337,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -1811,10 +1811,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -1946,7 +1946,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -2140,7 +2140,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -2539,10 +2539,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -2551,7 +2551,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -2573,7 +2573,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -2763,7 +2763,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ diff --git a/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr b/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr index 4226eacf352..a1855795797 100644 --- a/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr +++ b/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr @@ -809,10 +809,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -944,7 +944,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -1138,7 +1138,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -1537,10 +1537,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -1549,7 +1549,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -1571,7 +1571,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -1761,7 +1761,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ diff --git a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr index 2a77498441c..83bea22fdb9 100644 --- a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr +++ b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr @@ -2336,10 +2336,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -2469,7 +2469,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -2661,7 +2661,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -3055,10 +3055,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -3067,7 +3067,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -3089,7 +3089,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -3277,7 +3277,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -3805,10 +3805,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -3938,7 +3938,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -4130,7 +4130,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -4543,10 +4543,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -4555,7 +4555,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -4577,7 +4577,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -4765,7 +4765,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -5305,10 +5305,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -5438,7 +5438,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -5630,7 +5630,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -6043,10 +6043,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -6055,7 +6055,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -6077,7 +6077,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -6265,7 +6265,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -6680,10 +6680,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -6813,7 +6813,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -7005,7 +7005,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -7399,10 +7399,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -7411,7 +7411,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -7433,7 +7433,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -7621,7 +7621,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -8191,10 +8191,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -8324,7 +8324,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -8516,7 +8516,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -8929,10 +8929,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -8941,7 +8941,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -8963,7 +8963,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -9151,7 +9151,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -9611,10 +9611,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -9744,7 +9744,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -9936,7 +9936,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -10330,10 +10330,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -10342,7 +10342,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -10364,7 +10364,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -10552,7 +10552,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -11030,10 +11030,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -11163,7 +11163,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -11355,7 +11355,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -11779,10 +11779,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -11791,7 +11791,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -11813,7 +11813,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -12001,7 +12001,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ @@ -12491,10 +12491,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``FunctionMessage`` are an older version of the ``ToolMessage`` schema, and - do not contain the ``tool_call_id`` field. + ``FunctionMessage`` are an older version of the `ToolMessage` schema, and + do not contain the `tool_call_id` field. - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -12624,7 +12624,7 @@ 'description': ''' Message from a human. - ``HumanMessage``s are messages that are passed in from a human to the model. + `HumanMessage`s are messages that are passed in from a human to the model. Example: @@ -12816,7 +12816,7 @@ 'description': ''' Allowance for errors made by LLM. - Here we add an ``error`` key to surface errors made during generation + Here we add an `error` key to surface errors made during generation (e.g., invalid JSON arguments.) ''', 'properties': dict({ @@ -13229,10 +13229,10 @@ 'description': ''' Message for passing the result of executing a tool back to a model. - ``ToolMessage``s contain the result of a tool invocation. Typically, the result + `ToolMessage` objects contain the result of a tool invocation. Typically, the result is encoded inside the ``content`` field. - Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id + Example: A `ToolMessage` representing a result of ``42`` from a tool call with id .. code-block:: python @@ -13241,7 +13241,7 @@ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - Example: A ``ToolMessage`` where only part of the tool output is sent to the model + Example: A `ToolMessage` where only part of the tool output is sent to the model and the full output is passed in to artifact. !!! version-added "Added in version 0.2.17" @@ -13263,7 +13263,7 @@ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", ) - The ``tool_call_id`` field is used to associate the tool call request with the + The `tool_call_id` field is used to associate the tool call request with the tool call response. This is useful in situations where a chat model is able to request multiple tool calls in parallel. ''', @@ -13451,7 +13451,7 @@ } !!! warning "Behavior changed in 0.3.9" - Added ``input_token_details`` and ``output_token_details``. + Added `input_token_details` and `output_token_details`. ''', 'properties': dict({ 'input_token_details': dict({ diff --git a/libs/langchain/langchain_classic/agents/agent.py b/libs/langchain/langchain_classic/agents/agent.py index bd80f592368..53091eb079c 100644 --- a/libs/langchain/langchain_classic/agents/agent.py +++ b/libs/langchain/langchain_classic/agents/agent.py @@ -405,9 +405,9 @@ class RunnableAgent(BaseSingleActionAgent): stream_runnable: bool = True """Whether to stream from the runnable or not. - If True then underlying LLM is invoked in a streaming fashion to make it possible + If `True` then underlying LLM is invoked in a streaming fashion to make it possible to get access to the individual LLM tokens when using stream_log with the Agent - Executor. If False then LLM is invoked in a non-streaming fashion and + Executor. If `False` then LLM is invoked in a non-streaming fashion and individual LLM tokens will not be available in stream_log. """ @@ -513,9 +513,9 @@ class RunnableMultiActionAgent(BaseMultiActionAgent): stream_runnable: bool = True """Whether to stream from the runnable or not. - If True then underlying LLM is invoked in a streaming fashion to make it possible + If `True` then underlying LLM is invoked in a streaming fashion to make it possible to get access to the individual LLM tokens when using stream_log with the Agent - Executor. If False then LLM is invoked in a non-streaming fashion and + Executor. If `False` then LLM is invoked in a non-streaming fashion and individual LLM tokens will not be available in stream_log. """ @@ -723,7 +723,7 @@ class Agent(BaseSingleActionAgent): output_parser: AgentOutputParser """Output parser to use for agent.""" allowed_tools: list[str] | None = None - """Allowed tools for the agent. If None, all tools are allowed.""" + """Allowed tools for the agent. If `None`, all tools are allowed.""" @override def dict(self, **kwargs: Any) -> builtins.dict: diff --git a/libs/langchain/langchain_classic/agents/agent_iterator.py b/libs/langchain/langchain_classic/agents/agent_iterator.py index 874173a423b..75dc4b7cdc7 100644 --- a/libs/langchain/langchain_classic/agents/agent_iterator.py +++ b/libs/langchain/langchain_classic/agents/agent_iterator.py @@ -62,17 +62,17 @@ class AgentExecutorIterator: agent_executor (AgentExecutor): The AgentExecutor to iterate over. inputs (Any): The inputs to the AgentExecutor. callbacks (Callbacks, optional): The callbacks to use during iteration. - Defaults to None. + Defaults to `None`. tags (Optional[list[str]], optional): The tags to use during iteration. - Defaults to None. + Defaults to `None`. metadata (Optional[Dict[str, Any]], optional): The metadata to use - during iteration. Defaults to None. - run_name (Optional[str], optional): The name of the run. Defaults to None. - run_id (Optional[UUID], optional): The ID of the run. Defaults to None. + during iteration. Defaults to `None`. + run_name (Optional[str], optional): The name of the run. Defaults to `None`. + run_id (Optional[UUID], optional): The ID of the run. Defaults to `None`. include_run_info (bool, optional): Whether to include run info - in the output. Defaults to False. + in the output. Defaults to `False`. yield_actions (bool, optional): Whether to yield actions as they - are generated. Defaults to False. + are generated. Defaults to `False`. """ self._agent_executor = agent_executor self.inputs = inputs diff --git a/libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/base.py b/libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/base.py index 0e74a0900b5..0011fe15f0f 100644 --- a/libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/base.py +++ b/libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/base.py @@ -87,11 +87,12 @@ def create_vectorstore_agent( Args: llm: LLM that will be used by the agent toolkit: Set of tools for the agent - callback_manager: Object to handle the callback [ Defaults to None. ] + callback_manager: Object to handle the callback [ Defaults to `None`. ] prefix: The prefix prompt for the agent. If not provided uses default PREFIX. - verbose: If you want to see the content of the scratchpad. [ Defaults to False ] + verbose: If you want to see the content of the scratchpad. + [ Defaults to `False` ] agent_executor_kwargs: If there is any other parameter you want to send to the - agent. [ Defaults to None ] + agent. [ Defaults to `None` ] kwargs: Additional named parameters to pass to the ZeroShotAgent. Returns: @@ -201,12 +202,13 @@ def create_vectorstore_router_agent( llm: LLM that will be used by the agent toolkit: Set of tools for the agent which have routing capability with multiple vector stores - callback_manager: Object to handle the callback [ Defaults to None. ] + callback_manager: Object to handle the callback [ Defaults to `None`. ] prefix: The prefix prompt for the router agent. If not provided uses default ROUTER_PREFIX. - verbose: If you want to see the content of the scratchpad. [ Defaults to False ] + verbose: If you want to see the content of the scratchpad. + [ Defaults to `False` ] agent_executor_kwargs: If there is any other parameter you want to send to the - agent. [ Defaults to None ] + agent. [ Defaults to `None` ] kwargs: Additional named parameters to pass to the ZeroShotAgent. Returns: diff --git a/libs/langchain/langchain_classic/agents/conversational_chat/base.py b/libs/langchain/langchain_classic/agents/conversational_chat/base.py index 313ee266c54..b8943bdb356 100644 --- a/libs/langchain/langchain_classic/agents/conversational_chat/base.py +++ b/libs/langchain/langchain_classic/agents/conversational_chat/base.py @@ -91,8 +91,8 @@ class ConversationalChatAgent(Agent): Defaults to the PREFIX. human_message: The human message to use. Defaults to the SUFFIX. - input_variables: The input variables to use. Defaults to None. - output_parser: The output parser to use. Defaults to None. + input_variables: The input variables to use. Defaults to `None`. + output_parser: The output parser to use. Defaults to `None`. Returns: A PromptTemplate. diff --git a/libs/langchain/langchain_classic/agents/format_scratchpad/tools.py b/libs/langchain/langchain_classic/agents/format_scratchpad/tools.py index 3e4cba62f06..e58caab98e8 100644 --- a/libs/langchain/langchain_classic/agents/format_scratchpad/tools.py +++ b/libs/langchain/langchain_classic/agents/format_scratchpad/tools.py @@ -51,7 +51,7 @@ def _create_tool_message( def format_to_tool_messages( intermediate_steps: Sequence[tuple[AgentAction, str]], ) -> list[BaseMessage]: - """Convert (AgentAction, tool output) tuples into ToolMessages. + """Convert (AgentAction, tool output) tuples into `ToolMessage` objects. Args: intermediate_steps: Steps the LLM has taken to date, along with observations. diff --git a/libs/langchain/langchain_classic/agents/initialize.py b/libs/langchain/langchain_classic/agents/initialize.py index edd1e32440f..c1df318ab60 100644 --- a/libs/langchain/langchain_classic/agents/initialize.py +++ b/libs/langchain/langchain_classic/agents/initialize.py @@ -37,15 +37,15 @@ def initialize_agent( Args: tools: List of tools this agent has access to. llm: Language model to use as the agent. - agent: Agent type to use. If None and agent_path is also None, will default - to AgentType.ZERO_SHOT_REACT_DESCRIPTION. Defaults to None. + agent: Agent type to use. If `None` and agent_path is also None, will default + to AgentType.ZERO_SHOT_REACT_DESCRIPTION. Defaults to `None`. callback_manager: CallbackManager to use. Global callback manager is used if - not provided. Defaults to None. - agent_path: Path to serialized agent to use. If None and agent is also None, - will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION. Defaults to None. + not provided. Defaults to `None`. + agent_path: Path to serialized agent to use. If `None` and agent is also None, + will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION. Defaults to `None`. agent_kwargs: Additional keyword arguments to pass to the underlying agent. - Defaults to None. - tags: Tags to apply to the traced runs. Defaults to None. + Defaults to `None`. + tags: Tags to apply to the traced runs. Defaults to `None`. kwargs: Additional keyword arguments passed to the agent executor. Returns: diff --git a/libs/langchain/langchain_classic/agents/json_chat/base.py b/libs/langchain/langchain_classic/agents/json_chat/base.py index b174879f48c..3b01e4a4650 100644 --- a/libs/langchain/langchain_classic/agents/json_chat/base.py +++ b/libs/langchain/langchain_classic/agents/json_chat/base.py @@ -26,8 +26,8 @@ def create_json_chat_agent( tools: Tools this agent has access to. prompt: The prompt to use. See Prompt section below for more. stop_sequence: bool or list of str. - If True, adds a stop token of "Observation:" to avoid hallucinates. - If False, does not add a stop token. + If `True`, adds a stop token of "Observation:" to avoid hallucinates. + If `False`, does not add a stop token. If a list of str, uses the provided list as the stop tokens. Default is True. You may to set this to False if the LLM you are using diff --git a/libs/langchain/langchain_classic/agents/mrkl/base.py b/libs/langchain/langchain_classic/agents/mrkl/base.py index d0b05766ee3..799b7337022 100644 --- a/libs/langchain/langchain_classic/agents/mrkl/base.py +++ b/libs/langchain/langchain_classic/agents/mrkl/base.py @@ -98,7 +98,7 @@ class ZeroShotAgent(Agent): format_instructions: Instructions on how to use the tools. Defaults to FORMAT_INSTRUCTIONS input_variables: List of input variables the final prompt will expect. - Defaults to None. + Defaults to `None`. Returns: A PromptTemplate with the template assembled from the pieces here. @@ -129,13 +129,13 @@ class ZeroShotAgent(Agent): Args: llm: The LLM to use as the agent LLM. tools: The tools to use. - callback_manager: The callback manager to use. Defaults to None. - output_parser: The output parser to use. Defaults to None. + callback_manager: The callback manager to use. Defaults to `None`. + output_parser: The output parser to use. Defaults to `None`. prefix: The prefix to use. Defaults to PREFIX. suffix: The suffix to use. Defaults to SUFFIX. format_instructions: The format instructions to use. Defaults to FORMAT_INSTRUCTIONS. - input_variables: The input variables to use. Defaults to None. + input_variables: The input variables to use. Defaults to `None`. kwargs: Additional parameters to pass to the agent. """ cls._validate_tools(tools) diff --git a/libs/langchain/langchain_classic/agents/openai_assistant/base.py b/libs/langchain/langchain_classic/agents/openai_assistant/base.py index db09216195b..179b764c6e1 100644 --- a/libs/langchain/langchain_classic/agents/openai_assistant/base.py +++ b/libs/langchain/langchain_classic/agents/openai_assistant/base.py @@ -316,7 +316,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]): run_metadata: Metadata to associate with new run. attachments: A list of files attached to the message, and the tools they should be added to. - config: Runnable config. Defaults to None. + config: Runnable config. Defaults to `None`. **kwargs: Additional arguments. Returns: @@ -448,7 +448,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]): max_completion_tokens: Allow setting max_completion_tokens for this run. max_prompt_tokens: Allow setting max_prompt_tokens for this run. run_metadata: Metadata to associate with new run. - config: Runnable config. Defaults to None. + config: Runnable config. Defaults to `None`. kwargs: Additional arguments. Returns: diff --git a/libs/langchain/langchain_classic/agents/openai_functions_agent/base.py b/libs/langchain/langchain_classic/agents/openai_functions_agent/base.py index c5ca2ef5956..f964f4a6eef 100644 --- a/libs/langchain/langchain_classic/agents/openai_functions_agent/base.py +++ b/libs/langchain/langchain_classic/agents/openai_functions_agent/base.py @@ -106,8 +106,8 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent): Args: intermediate_steps: Steps the LLM has taken to date, along with observations. - callbacks: Callbacks to use. Defaults to None. - with_functions: Whether to use functions. Defaults to True. + callbacks: Callbacks to use. Defaults to `None`. + with_functions: Whether to use functions. Defaults to `True`. **kwargs: User inputs. Returns: @@ -146,7 +146,7 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent): Args: intermediate_steps: Steps the LLM has taken to date, along with observations. - callbacks: Callbacks to use. Defaults to None. + callbacks: Callbacks to use. Defaults to `None`. **kwargs: User inputs. Returns: @@ -261,8 +261,8 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent): Args: llm: The LLM to use as the agent. tools: The tools to use. - callback_manager: The callback manager to use. Defaults to None. - extra_prompt_messages: Extra prompt messages to use. Defaults to None. + callback_manager: The callback manager to use. Defaults to `None`. + extra_prompt_messages: Extra prompt messages to use. Defaults to `None`. system_message: The system message to use. Defaults to a default system message. kwargs: Additional parameters to pass to the agent. diff --git a/libs/langchain/langchain_classic/agents/react/agent.py b/libs/langchain/langchain_classic/agents/react/agent.py index b290281a8c3..7fc2c5c58ba 100644 --- a/libs/langchain/langchain_classic/agents/react/agent.py +++ b/libs/langchain/langchain_classic/agents/react/agent.py @@ -44,8 +44,8 @@ def create_react_agent( tools_renderer: This controls how the tools are converted into a string and then passed into the LLM. Default is `render_text_description`. stop_sequence: bool or list of str. - If True, adds a stop token of "Observation:" to avoid hallucinates. - If False, does not add a stop token. + If `True`, adds a stop token of "Observation:" to avoid hallucinates. + If `False`, does not add a stop token. If a list of str, uses the provided list as the stop tokens. Default is True. You may to set this to False if the LLM you are using diff --git a/libs/langchain/langchain_classic/agents/structured_chat/base.py b/libs/langchain/langchain_classic/agents/structured_chat/base.py index 488fb242817..f39116689cf 100644 --- a/libs/langchain/langchain_classic/agents/structured_chat/base.py +++ b/libs/langchain/langchain_classic/agents/structured_chat/base.py @@ -178,8 +178,8 @@ def create_structured_chat_agent( tools: Tools this agent has access to. prompt: The prompt to use. See Prompt section below for more. stop_sequence: bool or list of str. - If True, adds a stop token of "Observation:" to avoid hallucinates. - If False, does not add a stop token. + If `True`, adds a stop token of "Observation:" to avoid hallucinates. + If `False`, does not add a stop token. If a list of str, uses the provided list as the stop tokens. Default is True. You may to set this to False if the LLM you are using diff --git a/libs/langchain/langchain_classic/agents/xml/base.py b/libs/langchain/langchain_classic/agents/xml/base.py index 8dc226aad91..fcc3d83e4e9 100644 --- a/libs/langchain/langchain_classic/agents/xml/base.py +++ b/libs/langchain/langchain_classic/agents/xml/base.py @@ -132,8 +132,8 @@ def create_xml_agent( tools_renderer: This controls how the tools are converted into a string and then passed into the LLM. Default is `render_text_description`. stop_sequence: bool or list of str. - If True, adds a stop token of "" to avoid hallucinates. - If False, does not add a stop token. + If `True`, adds a stop token of "" to avoid hallucinates. + If `False`, does not add a stop token. If a list of str, uses the provided list as the stop tokens. Default is True. You may to set this to False if the LLM you are using diff --git a/libs/langchain/langchain_classic/callbacks/streamlit/__init__.py b/libs/langchain/langchain_classic/callbacks/streamlit/__init__.py index 04a9222eba8..a17acc3c319 100644 --- a/libs/langchain/langchain_classic/callbacks/streamlit/__init__.py +++ b/libs/langchain/langchain_classic/callbacks/streamlit/__init__.py @@ -34,13 +34,13 @@ def StreamlitCallbackHandler( # noqa: N802 collapsed into a "History" expander. Defaults to 4. expand_new_thoughts Each LLM "thought" gets its own `st.expander`. This param controls whether that - expander is expanded by default. Defaults to True. + expander is expanded by default. Defaults to `True`. collapse_completed_thoughts - If True, LLM thought expanders will be collapsed when completed. - Defaults to True. + If `True`, LLM thought expanders will be collapsed when completed. + Defaults to `True`. thought_labeler An optional custom LLMThoughtLabeler instance. If unspecified, the handler - will use the default thought labeling logic. Defaults to None. + will use the default thought labeling logic. Defaults to `None`. Returns: ------- diff --git a/libs/langchain/langchain_classic/chains/base.py b/libs/langchain/langchain_classic/chains/base.py index 7c522d4879b..a40e482bebc 100644 --- a/libs/langchain/langchain_classic/chains/base.py +++ b/libs/langchain/langchain_classic/chains/base.py @@ -73,14 +73,14 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): """ memory: BaseMemory | None = None - """Optional memory object. Defaults to None. + """Optional memory object. Defaults to `None`. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog.""" callbacks: Callbacks = Field(default=None, exclude=True) - """Optional list of callback handlers (or callback manager). Defaults to None. + """Optional list of callback handlers (or callback manager). Defaults to `None`. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs @@ -90,13 +90,13 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): will be printed to the console. Defaults to the global `verbose` value, accessible via `langchain.globals.get_verbose()`.""" tags: list[str] | None = None - """Optional list of tags associated with the chain. Defaults to None. + """Optional list of tags associated with the chain. Defaults to `None`. These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a chain with its use case. """ metadata: dict[str, Any] | None = None - """Optional metadata associated with the chain. Defaults to None. + """Optional metadata associated with the chain. Defaults to `None`. This metadata will be associated with each call to this chain, and passed as arguments to the handlers defined in `callbacks`. You can use these to eg identify a specific instance of a chain with its use case. @@ -385,16 +385,16 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): `Chain.input_keys` except for inputs that will be set by the chain's memory. return_only_outputs: Whether to return only outputs in the - response. If True, only new keys generated by this chain will be - returned. If False, both input keys and new keys generated by this - chain will be returned. Defaults to False. + response. If `True`, only new keys generated by this chain will be + returned. If `False`, both input keys and new keys generated by this + chain will be returned. Defaults to `False`. callbacks: Callbacks to use for this chain run. These will be called in addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. - metadata: Optional metadata associated with the chain. Defaults to None. + metadata: Optional metadata associated with the chain. Defaults to `None`. run_name: Optional name for this run of the chain. include_run_info: Whether to include run info in the response. Defaults to False. @@ -437,16 +437,16 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): `Chain.input_keys` except for inputs that will be set by the chain's memory. return_only_outputs: Whether to return only outputs in the - response. If True, only new keys generated by this chain will be - returned. If False, both input keys and new keys generated by this - chain will be returned. Defaults to False. + response. If `True`, only new keys generated by this chain will be + returned. If `False`, both input keys and new keys generated by this + chain will be returned. Defaults to `False`. callbacks: Callbacks to use for this chain run. These will be called in addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. - metadata: Optional metadata associated with the chain. Defaults to None. + metadata: Optional metadata associated with the chain. Defaults to `None`. run_name: Optional name for this run of the chain. include_run_info: Whether to include run info in the response. Defaults to False. @@ -480,7 +480,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): inputs: Dictionary of chain inputs, including any inputs added by chain memory. outputs: Dictionary of initial chain outputs. - return_only_outputs: Whether to only return the chain outputs. If False, + return_only_outputs: Whether to only return the chain outputs. If `False`, inputs are also added to the final outputs. Returns: @@ -505,7 +505,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC): inputs: Dictionary of chain inputs, including any inputs added by chain memory. outputs: Dictionary of initial chain outputs. - return_only_outputs: Whether to only return the chain outputs. If False, + return_only_outputs: Whether to only return the chain outputs. If `False`, inputs are also added to the final outputs. Returns: diff --git a/libs/langchain/langchain_classic/chains/combine_documents/reduce.py b/libs/langchain/langchain_classic/chains/combine_documents/reduce.py index 86f5f07d9c1..ba977eb5042 100644 --- a/libs/langchain/langchain_classic/chains/combine_documents/reduce.py +++ b/libs/langchain/langchain_classic/chains/combine_documents/reduce.py @@ -207,7 +207,7 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain): This is typically a StuffDocumentsChain.""" collapse_documents_chain: BaseCombineDocumentsChain | None = None """Chain to use to collapse documents if needed until they can all fit. - If None, will use the combine_documents_chain. + If `None`, will use the combine_documents_chain. This is typically a StuffDocumentsChain.""" token_max: int = 3000 """The maximum number of tokens to group documents into. For example, if @@ -215,7 +215,7 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain): 3000 tokens before trying to combine them into a smaller chunk.""" collapse_max_retries: int | None = None """The maximum number of retries to collapse documents to fit token_max. - If None, it will keep trying to collapse documents to fit token_max. + If `None`, it will keep trying to collapse documents to fit token_max. Otherwise, after it reaches the max number, it will throw an error""" model_config = ConfigDict( diff --git a/libs/langchain/langchain_classic/chains/constitutional_ai/base.py b/libs/langchain/langchain_classic/chains/constitutional_ai/base.py index f6d534a1d7d..3884fa20f24 100644 --- a/libs/langchain/langchain_classic/chains/constitutional_ai/base.py +++ b/libs/langchain/langchain_classic/chains/constitutional_ai/base.py @@ -209,7 +209,7 @@ class ConstitutionalChain(Chain): Args: names: List of names of constitutional principles to retrieve. - If None (default), all principles are returned. + If `None` (Default), all principles are returned. """ if names is None: return list(PRINCIPLES.values()) diff --git a/libs/langchain/langchain_classic/chains/conversational_retrieval/base.py b/libs/langchain/langchain_classic/chains/conversational_retrieval/base.py index 7d7d8692ef2..2d1af746464 100644 --- a/libs/langchain/langchain_classic/chains/conversational_retrieval/base.py +++ b/libs/langchain/langchain_classic/chains/conversational_retrieval/base.py @@ -88,8 +88,8 @@ class BaseConversationalRetrievalChain(Chain): """The output key to return the final answer of this chain in.""" rephrase_question: bool = True """Whether or not to pass the new generated question to the combine_docs_chain. - If True, will pass the new generated question along. - If False, will only use the new generated question for retrieval and pass the + If `True`, will pass the new generated question along. + If `False`, will only use the new generated question for retrieval and pass the original question along to the combine_docs_chain.""" return_source_documents: bool = False """Return the retrieved source documents as part of the final result.""" @@ -97,7 +97,7 @@ class BaseConversationalRetrievalChain(Chain): """Return the generated question as part of the final result.""" get_chat_history: Callable[[list[CHAT_TURN_TYPE]], str] | None = None """An optional function to get a string of the chat history. - If None is provided, will use a default.""" + If `None` is provided, will use a default.""" response_if_no_docs_found: str | None = None """If specified, the chain will return a fixed response if no docs are found for the question. """ diff --git a/libs/langchain/langchain_classic/chains/llm.py b/libs/langchain/langchain_classic/chains/llm.py index 5e792501cb8..0076c298287 100644 --- a/libs/langchain/langchain_classic/chains/llm.py +++ b/libs/langchain/langchain_classic/chains/llm.py @@ -93,7 +93,7 @@ class LLMChain(Chain): Defaults to one that takes the most likely string but does not change it otherwise.""" return_final_only: bool = True - """Whether to return only the final parsed result. Defaults to True. + """Whether to return only the final parsed result. Defaults to `True`. If false, will return a bunch of extra information about the generation.""" llm_kwargs: dict = Field(default_factory=dict) diff --git a/libs/langchain/langchain_classic/chains/openai_functions/base.py b/libs/langchain/langchain_classic/chains/openai_functions/base.py index 0a4586f91b4..e4e1c992ba1 100644 --- a/libs/langchain/langchain_classic/chains/openai_functions/base.py +++ b/libs/langchain/langchain_classic/chains/openai_functions/base.py @@ -65,7 +65,7 @@ def create_openai_fn_chain( llm: Language model to use, assumed to support the OpenAI function-calling API. prompt: BasePromptTemplate to pass to the model. enforce_single_function_usage: only used if a single function is passed in. If - True, then the model will be forced to use the given function. If False, + True, then the model will be forced to use the given function. If `False`, then the model will be given the option to use the given function or not. output_key: The key to use when returning the output in LLMChain.__call__. output_parser: BaseLLMOutputParser to use for parsing model outputs. By default diff --git a/libs/langchain/langchain_classic/chains/query_constructor/base.py b/libs/langchain/langchain_classic/chains/query_constructor/base.py index 46eda5ef5bb..902ea26b8b3 100644 --- a/libs/langchain/langchain_classic/chains/query_constructor/base.py +++ b/libs/langchain/langchain_classic/chains/query_constructor/base.py @@ -218,7 +218,7 @@ def get_query_constructor_prompt( examples: Optional list of examples to use for the chain. allowed_comparators: Sequence of allowed comparators. allowed_operators: Sequence of allowed operators. - enable_limit: Whether to enable the limit operator. Defaults to False. + enable_limit: Whether to enable the limit operator. Defaults to `False`. schema_prompt: Prompt for describing query schema. Should have string input variables allowed_comparators and allowed_operators. kwargs: Additional named params to pass to FewShotPromptTemplate init. @@ -291,7 +291,7 @@ def load_query_constructor_chain( allowed_comparators: Sequence of allowed comparators. Defaults to all Comparators. allowed_operators: Sequence of allowed operators. Defaults to all Operators. - enable_limit: Whether to enable the limit operator. Defaults to False. + enable_limit: Whether to enable the limit operator. Defaults to `False`. schema_prompt: Prompt for describing query schema. Should have string input variables allowed_comparators and allowed_operators. **kwargs: Arbitrary named params to pass to LLMChain. @@ -346,7 +346,7 @@ def load_query_constructor_runnable( allowed_comparators: Sequence of allowed comparators. Defaults to all Comparators. allowed_operators: Sequence of allowed operators. Defaults to all Operators. - enable_limit: Whether to enable the limit operator. Defaults to False. + enable_limit: Whether to enable the limit operator. Defaults to `False`. schema_prompt: Prompt for describing query schema. Should have string input variables allowed_comparators and allowed_operators. fix_invalid: Whether to fix invalid filter directives by ignoring invalid diff --git a/libs/langchain/langchain_classic/chains/router/base.py b/libs/langchain/langchain_classic/chains/router/base.py index 497e001bbb4..ea078cb037b 100644 --- a/libs/langchain/langchain_classic/chains/router/base.py +++ b/libs/langchain/langchain_classic/chains/router/base.py @@ -73,8 +73,8 @@ class MultiRouteChain(Chain): default_chain: Chain """Default chain to use when none of the destination chains are suitable.""" silent_errors: bool = False - """If True, use default_chain when an invalid destination name is provided. - Defaults to False.""" + """If `True`, use default_chain when an invalid destination name is provided. + Defaults to `False`.""" model_config = ConfigDict( arbitrary_types_allowed=True, diff --git a/libs/langchain/langchain_classic/chains/sql_database/query.py b/libs/langchain/langchain_classic/chains/sql_database/query.py index 99954121497..18b0f07e352 100644 --- a/libs/langchain/langchain_classic/chains/sql_database/query.py +++ b/libs/langchain/langchain_classic/chains/sql_database/query.py @@ -59,10 +59,10 @@ def create_sql_query_chain( llm: The language model to use. db: The SQLDatabase to generate the query for. prompt: The prompt to use. If none is provided, will choose one - based on dialect. Defaults to None. See Prompt section below for more. + based on dialect. Defaults to `None`. See Prompt section below for more. k: The number of results per select statement to return. Defaults to 5. get_col_comments: Whether to retrieve column comments along with table info. - Defaults to False. + Defaults to `False`. Returns: A chain that takes in a question and generates a SQL query that answers diff --git a/libs/langchain/langchain_classic/chains/structured_output/base.py b/libs/langchain/langchain_classic/chains/structured_output/base.py index 58512f99a84..555ed69a75b 100644 --- a/libs/langchain/langchain_classic/chains/structured_output/base.py +++ b/libs/langchain/langchain_classic/chains/structured_output/base.py @@ -88,7 +88,7 @@ def create_openai_fn_runnable( llm: Language model to use, assumed to support the OpenAI function-calling API. prompt: BasePromptTemplate to pass to the model. enforce_single_function_usage: only used if a single function is passed in. If - True, then the model will be forced to use the given function. If False, + True, then the model will be forced to use the given function. If `False`, then the model will be given the option to use the given function or not. output_parser: BaseLLMOutputParser to use for parsing model outputs. By default will be inferred from the function types. If pydantic.BaseModels are passed @@ -221,12 +221,12 @@ def create_structured_output_runnable( recommended over 'openai-functions'. If 'openai-json' then OpenAI model with response_format set to JSON is used. enforce_function_usage: Only applies when mode is 'openai-tools' or - 'openai-functions'. If True, then the model will be forced to use the given - output schema. If False, then the model can elect whether to use the output + 'openai-functions'. If `True`, then the model will be forced to use the given + output schema. If `False`, then the model can elect whether to use the output schema. return_single: Only applies when mode is 'openai-tools'. Whether to a list of - structured outputs or a single one. If True and model does not return any - structured outputs then chain output is None. If False and model does not + structured outputs or a single one. If `True` and model does not return any + structured outputs then chain output is None. If `False` and model does not return any structured outputs then chain output is an empty list. kwargs: Additional named arguments. diff --git a/libs/langchain/langchain_classic/chains/summarize/chain.py b/libs/langchain/langchain_classic/chains/summarize/chain.py index f5ae19f5718..8b712d06cb9 100644 --- a/libs/langchain/langchain_classic/chains/summarize/chain.py +++ b/libs/langchain/langchain_classic/chains/summarize/chain.py @@ -50,7 +50,7 @@ def _load_stuff_chain( passed into the LLM. Defaults to `stuff_prompt.PROMPT`. document_variable_name: Variable name in the prompt template where the document text will be inserted. Defaults to "text". - verbose: Whether to log progress and intermediate steps. Defaults to None. + verbose: Whether to log progress and intermediate steps. Defaults to `None`. **kwargs: Additional keyword arguments passed to the StuffDocumentsChain. Returns: @@ -112,17 +112,17 @@ def _load_map_reduce_chain( map_reduce_document_variable_name: Variable name in the `map_prompt` where document text is inserted. Defaults to "text". collapse_prompt: Optional prompt used to collapse intermediate summaries - if they exceed the token limit (`token_max`). Defaults to None. - reduce_llm: Optional separate LLM for the reduce step. Defaults to None, + if they exceed the token limit (`token_max`). Defaults to `None`. + reduce_llm: Optional separate LLM for the reduce step. Defaults to `None`, which uses the same model as the map step. - collapse_llm: Optional separate LLM for the collapse step. Defaults to None, + collapse_llm: Optional separate LLM for the collapse step. Defaults to `None`, which uses the same model as the map step. - verbose: Whether to log progess and intermediate steps. Defaults to None. + verbose: Whether to log progess and intermediate steps. Defaults to `None`. token_max: Token threshold that triggers the collapse step during reduction. Defaults to 3000. - callbacks: Optional callbacks for logging and tracing. Defaults to None. + callbacks: Optional callbacks for logging and tracing. Defaults to `None`. collapse_max_retries: Maximum retries for the collapse step if it fails. - Defaults to None. + Defaults to `None`. **kwargs: Additional keyword arguments passed to the MapReduceDocumentsChain. Returns: diff --git a/libs/langchain/langchain_classic/chat_models/base.py b/libs/langchain/langchain_classic/chat_models/base.py index d0ffb2002f1..d451d30f19f 100644 --- a/libs/langchain/langchain_classic/chat_models/base.py +++ b/libs/langchain/langchain_classic/chat_models/base.py @@ -91,9 +91,9 @@ def init_chat_model( above). Supported model_provider values and the corresponding integration package are: - - ``openai`` -> ``langchain-openai`` - - ``anthropic`` -> ``langchain-anthropic`` - - ``azure_openai`` -> ``langchain-openai`` + - ``openai`` -> `langchain-openai` + - ``anthropic`` -> `langchain-anthropic` + - ``azure_openai`` -> `langchain-openai` - ``azure_ai`` -> ``langchain-azure-ai`` - ``google_vertexai`` -> ``langchain-google-vertexai`` - ``google_genai`` -> ``langchain-google-genai`` @@ -129,7 +129,7 @@ def init_chat_model( configurable_fields: Which model parameters are configurable: - None: No configurable fields. - - ``'any'``: All fields are configurable. **See Security Note below.** + - `'any'`: All fields are configurable. **See Security Note below.** - Union[List[str], Tuple[str, ...]]: Specified fields are configurable. Fields are assumed to have config_prefix stripped if there is a @@ -289,7 +289,7 @@ def init_chat_model( !!! version-added "Added in version 0.2.7" !!! warning "Behavior changed in 0.2.8" - Support for ``configurable_fields`` and ``config_prefix`` added. + Support for `configurable_fields` and ``config_prefix`` added. !!! warning "Behavior changed in 0.2.12" Support for Ollama via langchain-ollama package added @@ -653,7 +653,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]): @property @override def InputType(self) -> TypeAlias: - """Get the input type for this runnable.""" + """Get the input type for this `Runnable`.""" from langchain_core.prompt_values import ( ChatPromptValueConcrete, StringPromptValue, diff --git a/libs/langchain/langchain_classic/embeddings/cache.py b/libs/langchain/langchain_classic/embeddings/cache.py index c9a207d7138..169c217ef3a 100644 --- a/libs/langchain/langchain_classic/embeddings/cache.py +++ b/libs/langchain/langchain_classic/embeddings/cache.py @@ -154,7 +154,7 @@ class CacheBackedEmbeddings(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. + If `None`, query embeddings are not cached. """ super().__init__() self.document_embedding_store = document_embedding_store @@ -242,7 +242,7 @@ class CacheBackedEmbeddings(Embeddings): """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. + ``cache_query`` parameter to `True` when initializing the embedder. Args: text: The text to embed. @@ -265,7 +265,7 @@ class CacheBackedEmbeddings(Embeddings): """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. + ``cache_query`` parameter to `True` when initializing the embedder. Args: text: The text to embed. diff --git a/libs/langchain/langchain_classic/evaluation/exact_match/base.py b/libs/langchain/langchain_classic/evaluation/exact_match/base.py index 7ce9fbce3f6..b555d932b78 100644 --- a/libs/langchain/langchain_classic/evaluation/exact_match/base.py +++ b/libs/langchain/langchain_classic/evaluation/exact_match/base.py @@ -35,11 +35,11 @@ class ExactMatchStringEvaluator(StringEvaluator): Args: ignore_case: Whether to ignore case when comparing strings. - Defaults to False. + Defaults to `False`. ignore_punctuation: Whether to ignore punctuation when comparing strings. - Defaults to False. + Defaults to `False`. ignore_numbers: Whether to ignore numbers when comparing strings. - Defaults to False. + Defaults to `False`. """ super().__init__() self.ignore_case = ignore_case diff --git a/libs/langchain/langchain_classic/output_parsers/structured.py b/libs/langchain/langchain_classic/output_parsers/structured.py index 23250cf08df..b5efae9060c 100644 --- a/libs/langchain/langchain_classic/output_parsers/structured.py +++ b/libs/langchain/langchain_classic/output_parsers/structured.py @@ -96,8 +96,8 @@ class StructuredOutputParser(BaseOutputParser[dict[str, Any]]): # ``` Args: - only_json (bool): If True, only the json in the Markdown code snippet - will be returned, without the introducing text. Defaults to False. + only_json (bool): If `True`, only the json in the Markdown code snippet + will be returned, without the introducing text. Defaults to `False`. """ schema_str = "\n".join( [_get_sub_string(schema) for schema in self.response_schemas], diff --git a/libs/langchain/langchain_classic/retrievers/document_compressors/cohere_rerank.py b/libs/langchain/langchain_classic/retrievers/document_compressors/cohere_rerank.py index 8907911671f..8930f052c15 100644 --- a/libs/langchain/langchain_classic/retrievers/document_compressors/cohere_rerank.py +++ b/libs/langchain/langchain_classic/retrievers/document_compressors/cohere_rerank.py @@ -74,7 +74,7 @@ class CohereRerank(BaseDocumentCompressor): query: The query to use for reranking. documents: A sequence of documents to rerank. model: The model to use for re-ranking. Default to self.model. - top_n : The number of results to return. If None returns all results. + top_n : The number of results to return. If `None` returns all results. Defaults to self.top_n. max_chunks_per_doc : The maximum number of chunks derived from a document. """ # noqa: E501 diff --git a/libs/langchain/langchain_classic/retrievers/document_compressors/embeddings_filter.py b/libs/langchain/langchain_classic/retrievers/document_compressors/embeddings_filter.py index 017863373bd..3bb99c00946 100644 --- a/libs/langchain/langchain_classic/retrievers/document_compressors/embeddings_filter.py +++ b/libs/langchain/langchain_classic/retrievers/document_compressors/embeddings_filter.py @@ -37,7 +37,7 @@ class EmbeddingsFilter(BaseDocumentCompressor): `similarity_threshold` must be specified. Defaults to 20.""" similarity_threshold: float | None = None """Threshold for determining when two documents are similar enough - to be considered redundant. Defaults to None, must be specified if `k` is set + to be considered redundant. Defaults to `None`, must be specified if `k` is set to None.""" model_config = ConfigDict( diff --git a/libs/langchain/langchain_classic/retrievers/document_compressors/listwise_rerank.py b/libs/langchain/langchain_classic/retrievers/document_compressors/listwise_rerank.py index e5ad73ace7e..8db5fc9038e 100644 --- a/libs/langchain/langchain_classic/retrievers/document_compressors/listwise_rerank.py +++ b/libs/langchain/langchain_classic/retrievers/document_compressors/listwise_rerank.py @@ -45,7 +45,7 @@ class LLMListwiseRerank(BaseDocumentCompressor): ``LLMListwiseRerank`` uses a language model to rerank a list of documents based on their relevance to a query. - **NOTE**: requires that underlying model implement ``with_structured_output``. + **NOTE**: requires that underlying model implement `with_structured_output`. Example usage: .. code-block:: python diff --git a/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py b/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py index abb955757d5..6f7322697ba 100644 --- a/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py +++ b/libs/langchain/langchain_classic/retrievers/parent_document_retriever.py @@ -71,7 +71,7 @@ class ParentDocumentRetriever(MultiVectorRetriever): If none, then the parent documents will be the raw documents passed in.""" child_metadata_fields: Sequence[str] | None = None - """Metadata fields to leave in child documents. If None, leave all parent document + """Metadata fields to leave in child documents. If `None`, leave all parent document metadata. """ diff --git a/libs/langchain/tests/unit_tests/chat_models/test_base.py b/libs/langchain/tests/unit_tests/chat_models/test_base.py index f3dec20c72f..42a5d005cfd 100644 --- a/libs/langchain/tests/unit_tests/chat_models/test_base.py +++ b/libs/langchain/tests/unit_tests/chat_models/test_base.py @@ -70,9 +70,9 @@ def test_configurable() -> None: """Test configurable chat model behavior without default parameters. Verifies that a configurable chat model initialized without default parameters: - - Has access to all standard runnable methods (``invoke``, ``stream``, etc.) + - Has access to all standard runnable methods (`invoke`, `stream`, etc.) - Blocks access to non-configurable methods until configuration is provided - - Supports declarative operations (``bind_tools``) without mutating original model + - Supports declarative operations (`bind_tools`) without mutating original model - Can chain declarative operations and configuration to access full functionality - Properly resolves to the configured model type when parameters are provided @@ -196,7 +196,7 @@ def test_configurable_with_default() -> None: """Test configurable chat model behavior with default parameters. Verifies that a configurable chat model initialized with default parameters: - - Has access to all standard runnable methods (``invoke``, ``stream``, etc.) + - Has access to all standard runnable methods (`invoke`, `stream`, etc.) - Provides immediate access to non-configurable methods (e.g. ``get_num_tokens``) - Supports model switching through runtime configuration using ``config_prefix`` - Maintains proper model identity and attributes when reconfigured diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py index 687ac33170f..c370661e7c6 100644 --- a/libs/langchain_v1/langchain/agents/factory.py +++ b/libs/langchain_v1/langchain/agents/factory.py @@ -330,7 +330,7 @@ def _supports_provider_strategy(model: str | BaseChatModel) -> bool: model: Model name string or BaseChatModel instance. Returns: - ``True`` if the model supports provider-specific structured output, ``False`` otherwise. + `True` if the model supports provider-specific structured output, `False` otherwise. """ model_name: str | None = None if isinstance(model, str): @@ -494,7 +494,7 @@ def create_agent( # noqa: PLR0915 Args: model: The language model for the agent. Can be a string identifier (e.g., ``"openai:gpt-4"``), a chat model instance (e.g., ``ChatOpenAI()``). - tools: A list of tools, dicts, or callables. If ``None`` or an empty list, + tools: A list of tools, dicts, or callables. If `None` or an empty list, the agent will consist of a model node without a tool calling loop. system_prompt: An optional system prompt for the LLM. If provided as a string, it will be converted to a SystemMessage and added to the beginning @@ -529,10 +529,10 @@ def create_agent( # noqa: PLR0915 A compiled StateGraph that can be used for chat interactions. The agent node calls the language model with the messages list (after applying - the system prompt). If the resulting AIMessage contains ``tool_calls``, the graph will + the system prompt). If the resulting AIMessage contains `tool_calls`, the graph will then call the tools. The tools node executes the tools and adds the responses - to the messages list as ``ToolMessage`` objects. The agent node then calls the - language model again. The process repeats until no more ``tool_calls`` are + to the messages list as `ToolMessage` objects. The agent node then calls the + language model again. The process repeats until no more `tool_calls` are present in the response. The agent then returns the full list of messages. Example: diff --git a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py index 681041f267e..222dc9ccb45 100644 --- a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py +++ b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py @@ -163,8 +163,8 @@ class HumanInTheLoopMiddleware(AgentMiddleware): interrupt_on: Mapping of tool name to allowed actions. If a tool doesn't have an entry, it's auto-approved by default. - * ``True`` indicates all actions are allowed: accept, edit, and respond. - * ``False`` indicates that the tool is auto-approved. + * `True` indicates all actions are allowed: accept, edit, and respond. + * `False` indicates that the tool is auto-approved. * ``ToolConfig`` indicates the specific actions allowed for this tool. The ToolConfig can include a ``description`` field (str or callable) for custom formatting of the interrupt description. diff --git a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py index b8eb425adf9..63f0be50fda 100644 --- a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py +++ b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py @@ -108,9 +108,9 @@ class ModelCallLimitMiddleware(AgentMiddleware): Args: thread_limit: Maximum number of model calls allowed per thread. - None means no limit. Defaults to None. + None means no limit. Defaults to `None`. run_limit: Maximum number of model calls allowed per run. - None means no limit. Defaults to None. + None means no limit. Defaults to `None`. exit_behavior: What to do when limits are exceeded. - "end": Jump to the end of the agent execution and inject an artificial AI message indicating that the limit was exceeded. diff --git a/libs/langchain_v1/langchain/agents/middleware/pii.py b/libs/langchain_v1/langchain/agents/middleware/pii.py index cb1193e80a2..4d667cf575f 100644 --- a/libs/langchain_v1/langchain/agents/middleware/pii.py +++ b/libs/langchain_v1/langchain/agents/middleware/pii.py @@ -500,8 +500,8 @@ class PIIMiddleware(AgentMiddleware): * If ``Callable``: Function that takes content string and returns list of PIIMatch objects - * If ``str``: Regex pattern to match PII - * If ``None``: Uses built-in detector for the pii_type + * If `str`: Regex pattern to match PII + * If `None`: Uses built-in detector for the pii_type apply_to_input: Whether to check user messages before model call. apply_to_output: Whether to check AI messages after model call. @@ -626,7 +626,7 @@ class PIIMiddleware(AgentMiddleware): # Check tool results if enabled if self.apply_to_tool_results: - # Find the last AIMessage, then process all ToolMessages after it + # Find the last AIMessage, then process all `ToolMessage` objects after it last_ai_idx = None for i in range(len(messages) - 1, -1, -1): if isinstance(messages[i], AIMessage): diff --git a/libs/langchain_v1/langchain/agents/middleware/summarization.py b/libs/langchain_v1/langchain/agents/middleware/summarization.py index 5138dc4267e..de59095be1c 100644 --- a/libs/langchain_v1/langchain/agents/middleware/summarization.py +++ b/libs/langchain_v1/langchain/agents/middleware/summarization.py @@ -81,7 +81,7 @@ class SummarizationMiddleware(AgentMiddleware): Args: model: The language model to use for generating summaries. max_tokens_before_summary: Token threshold to trigger summarization. - If None, summarization is disabled. + If `None`, summarization is disabled. messages_to_keep: Number of recent messages to preserve after summarization. token_counter: Function to count tokens in messages. summary_prompt: Prompt template for generating summaries. diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py index f2abdaab09d..52c5d488bee 100644 --- a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py +++ b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py @@ -18,7 +18,7 @@ def _count_tool_calls_in_messages(messages: list[AnyMessage], tool_name: str | N Args: messages: List of messages to count tool calls in. tool_name: If specified, only count calls to this specific tool. - If None, count all tool calls. + If `None`, count all tool calls. Returns: The total number of tool calls (optionally filtered by tool_name). @@ -168,12 +168,12 @@ class ToolCallLimitMiddleware(AgentMiddleware): """Initialize the tool call limit middleware. Args: - tool_name: Name of the specific tool to limit. If None, limits apply - to all tools. Defaults to None. + tool_name: Name of the specific tool to limit. If `None`, limits apply + to all tools. Defaults to `None`. thread_limit: Maximum number of tool calls allowed per thread. - None means no limit. Defaults to None. + None means no limit. Defaults to `None`. run_limit: Maximum number of tool calls allowed per run. - None means no limit. Defaults to None. + None means no limit. Defaults to `None`. exit_behavior: What to do when limits are exceeded. - "end": Jump to the end of the agent execution and inject an artificial AI message indicating that the limit was exceeded. diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py index 618ebd681c4..5b0bc4a08ee 100644 --- a/libs/langchain_v1/langchain/chat_models/base.py +++ b/libs/langchain_v1/langchain/chat_models/base.py @@ -272,7 +272,7 @@ def init_chat_model( !!! version-added "Added in version 0.2.7" !!! warning "Behavior changed in 0.2.8" - Support for ``configurable_fields`` and ``config_prefix`` added. + Support for `configurable_fields` and ``config_prefix`` added. !!! warning "Behavior changed in 0.2.12" Support for Ollama via langchain-ollama package added @@ -625,7 +625,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]): @property def InputType(self) -> TypeAlias: - """Get the input type for this runnable.""" + """Get the input type for this `Runnable`.""" from langchain_core.prompt_values import ( ChatPromptValueConcrete, StringPromptValue, diff --git a/libs/langchain_v1/langchain/embeddings/cache.py b/libs/langchain_v1/langchain/embeddings/cache.py index ebac5c911e3..b315368a9dd 100644 --- a/libs/langchain_v1/langchain/embeddings/cache.py +++ b/libs/langchain_v1/langchain/embeddings/cache.py @@ -157,7 +157,7 @@ class CacheBackedEmbeddings(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. + If `None`, query embeddings are not cached. """ super().__init__() self.document_embedding_store = document_embedding_store @@ -235,7 +235,7 @@ class CacheBackedEmbeddings(Embeddings): """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. + ``cache_query`` parameter to `True` when initializing the embedder. Args: text: The text to embed. @@ -258,7 +258,7 @@ class CacheBackedEmbeddings(Embeddings): """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. + ``cache_query`` parameter to `True` when initializing the embedder. Args: text: The text to embed. diff --git a/libs/langchain_v1/langchain/tools/tool_node.py b/libs/langchain_v1/langchain/tools/tool_node.py index cb9b5bc1790..0fc895be3ad 100644 --- a/libs/langchain_v1/langchain/tools/tool_node.py +++ b/libs/langchain_v1/langchain/tools/tool_node.py @@ -265,7 +265,7 @@ def _handle_tool_error( Args: e: The exception that occurred during tool execution. flag: Configuration for how to handle the error. Can be: - - bool: If True, use default error template + - bool: If `True`, use default error template - str: Use this string as the error message - Callable: Call this function with the exception to get error message - tuple: Not used in this context (handled by caller) @@ -398,7 +398,7 @@ class ToolNode(RunnableCallable): name: The name identifier for this node in the graph. Used for debugging and visualization. Defaults to "tools". tags: Optional metadata tags to associate with the node for filtering - and organization. Defaults to None. + and organization. Defaults to `None`. handle_tool_errors: Configuration for error handling during tool execution. Supports multiple strategies: @@ -420,7 +420,7 @@ class ToolNode(RunnableCallable): - ignores tool execution errors (they will be re-raised) messages_key: The key in the state dictionary that contains the message list. - This same key will be used for the output ToolMessages. + This same key will be used for the output `ToolMessage` objects. Defaults to "messages". Allows custom state schemas with different message field names. @@ -1355,7 +1355,7 @@ class InjectedState(InjectedToolArg): to the model's tool-calling interface. Args: - field: Optional key to extract from the state dictionary. If None, the entire + field: Optional key to extract from the state dictionary. If `None`, the entire state is injected. If specified, only that field's value is injected. This allows tools to request specific state components rather than processing the full state structure. diff --git a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py index a89dc6adb95..5b53f3d7360 100644 --- a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py +++ b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py @@ -71,9 +71,9 @@ def test_configurable() -> None: """Test configurable chat model behavior without default parameters. Verifies that a configurable chat model initialized without default parameters: - - Has access to all standard runnable methods (``invoke``, ``stream``, etc.) + - Has access to all standard runnable methods (`invoke`, `stream`, etc.) - Blocks access to non-configurable methods until configuration is provided - - Supports declarative operations (``bind_tools``) without mutating original model + - Supports declarative operations (`bind_tools`) without mutating original model - Can chain declarative operations and configuration to access full functionality - Properly resolves to the configured model type when parameters are provided @@ -197,7 +197,7 @@ def test_configurable_with_default() -> None: """Test configurable chat model behavior with default parameters. Verifies that a configurable chat model initialized with default parameters: - - Has access to all standard runnable methods (``invoke``, ``stream``, etc.) + - Has access to all standard runnable methods (`invoke`, `stream`, etc.) - Provides immediate access to non-configurable methods (e.g. ``get_num_tokens``) - Supports model switching through runtime configuration using ``config_prefix`` - Maintains proper model identity and attributes when reconfigured 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 adc07fbee34..5570bd2d421 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 @@ -819,12 +819,12 @@ async def test_async_handler_can_throw_exception() -> None: def test_handler_cannot_yield_multiple_tool_messages() -> None: - """Test that yielding multiple ToolMessages is rejected.""" + """Test that yielding multiple `ToolMessage` objects is rejected.""" def multi_message_handler( request: ToolCallRequest, _state: Any, _runtime: Any ) -> Generator[ToolCallRequest | ToolMessage | Command, ToolMessage | Command, None]: - """Handler that incorrectly yields multiple ToolMessages.""" + """Handler that incorrectly yields multiple `ToolMessage` objects.""" # First short-circuit yield ToolMessage("first", tool_call_id=request.tool_call["id"], name="add") # Second short-circuit - should fail diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py index d3f723552d7..1f99f97d6a7 100644 --- a/libs/partners/anthropic/langchain_anthropic/chat_models.py +++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py @@ -569,7 +569,7 @@ class ChatAnthropic(BaseChatModel): list of the latest models. Setup: - Install ``langchain-anthropic`` and set environment variable ``ANTHROPIC_API_KEY``. + Install `langchain-anthropic` and set environment variable ``ANTHROPIC_API_KEY``. .. code-block:: bash @@ -1153,7 +1153,7 @@ class ChatAnthropic(BaseChatModel): response = llm.invoke(messages) Details of cached token counts will be included on the ``InputTokenDetails`` - of response's ``usage_metadata``: + of response's `usage_metadata`: .. code-block:: python @@ -1486,7 +1486,7 @@ class ChatAnthropic(BaseChatModel): """Whether to use streaming or not.""" stream_usage: bool = True - """Whether to include usage metadata in streaming output. If ``True``, additional + """Whether to include usage metadata in streaming output. If `True`, additional message chunks will be generated during the stream including usage metadata. """ @@ -1911,10 +1911,10 @@ class ChatAnthropic(BaseChatModel): tool_choice: Which tool to require the model to call. Options are: - name of the tool as a string or as dict ``{"type": "tool", "name": "<>"}``: calls corresponding tool; - - ``'auto'``, ``{"type: "auto"}``, or ``None``: automatically selects a tool (including no tool); - - ``'any'`` or ``{"type: "any"}``: force at least one tool to be called; - parallel_tool_calls: Set to ``False`` to disable parallel tool use. - Defaults to ``None`` (no specification, which allows parallel tool use). + - ``'auto'``, ``{"type: "auto"}``, or `None`: automatically selects a tool (including no tool); + - `'any'` or ``{"type: "any"}``: force at least one tool to be called; + parallel_tool_calls: Set to `False` to disable parallel tool use. + Defaults to `None` (no specification, which allows parallel tool use). !!! version-added "Added in version 0.3.2" kwargs: Any additional parameters are passed directly to @@ -1954,7 +1954,7 @@ class ChatAnthropic(BaseChatModel): # id='run-87b1331e-9251-4a68-acef-f0a018b639cc-0' # ) - Example — force tool call with tool_choice ``'any'``: + Example — force tool call with tool_choice `'any'`: .. code-block:: python @@ -2183,7 +2183,7 @@ class ChatAnthropic(BaseChatModel): - an Anthropic tool schema, - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class, + - a `TypedDict` class, - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -2191,10 +2191,10 @@ class ChatAnthropic(BaseChatModel): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. include_raw: - If ``False`` then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If ``True`` + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict @@ -2204,10 +2204,10 @@ class ChatAnthropic(BaseChatModel): Returns: A Runnable that takes same inputs as a `langchain_core.language_models.chat.BaseChatModel`. - If ``include_raw`` is ``False`` and ``schema`` is a Pydantic class, Runnable outputs + If ``include_raw`` is `False` and ``schema`` is a Pydantic class, Runnable outputs an instance of ``schema`` (i.e., a Pydantic object). - Otherwise, if ``include_raw`` is ``False`` then Runnable outputs a dict. + Otherwise, if ``include_raw`` is `False` then Runnable outputs a dict. If ``include_raw`` is True, then Runnable outputs a dict with keys: diff --git a/libs/partners/anthropic/langchain_anthropic/output_parsers.py b/libs/partners/anthropic/langchain_anthropic/output_parsers.py index 7695d020089..5cb6f362cdb 100644 --- a/libs/partners/anthropic/langchain_anthropic/output_parsers.py +++ b/libs/partners/anthropic/langchain_anthropic/output_parsers.py @@ -31,7 +31,7 @@ class ToolsOutputParser(BaseGenerationOutputParser): Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. - partial: (Not used) Whether the result is a partial result. If True, the + partial: (Not used) Whether the result is a partial result. If `True`, the parser may return a partial result, which may not be complete or valid. Returns: diff --git a/libs/partners/chroma/langchain_chroma/vectorstores.py b/libs/partners/chroma/langchain_chroma/vectorstores.py index c446e4de990..597ed5a656f 100644 --- a/libs/partners/chroma/langchain_chroma/vectorstores.py +++ b/libs/partners/chroma/langchain_chroma/vectorstores.py @@ -337,13 +337,13 @@ class Chroma(VectorStore): client_settings: Chroma client settings collection_metadata: Collection configurations. collection_configuration: Index configuration for the collection. - Defaults to None. + Defaults to `None`. client: Chroma client. Documentation: https://docs.trychroma.com/reference/python/client relevance_score_fn: Function to calculate relevance score from distance. Used only in `similarity_search_with_relevance_scores` create_collection_if_not_exists: Whether to create collection - if it doesn't exist. Defaults to True. + if it doesn't exist. Defaults to `True`. """ _tenant = tenant or chromadb.DEFAULT_TENANT _database = database or chromadb.DEFAULT_DATABASE @@ -692,7 +692,7 @@ class Chroma(VectorStore): Args: query: Query text to search for. k: Number of results to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. kwargs: Additional keyword arguments to pass to Chroma collection query. Returns: @@ -719,7 +719,7 @@ class Chroma(VectorStore): Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by the document contents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -749,7 +749,7 @@ class Chroma(VectorStore): Args: embedding (List[float]): Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by the documents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -780,7 +780,7 @@ class Chroma(VectorStore): Args: query: Query text to search for. k: Number of results to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by document contents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -822,7 +822,7 @@ class Chroma(VectorStore): Args: query: Query text to search for. k: Number of results to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by the document contents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -1005,7 +1005,7 @@ class Chroma(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by the document contents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -1055,7 +1055,7 @@ class Chroma(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. where_document: dict used to filter by the document contents. E.g. {"$contains": "hello"}. kwargs: Additional keyword arguments to pass to Chroma collection query. @@ -1272,15 +1272,15 @@ class Chroma(VectorStore): Default is 'default_tenant' for local Chroma servers. database: Database name. Required for Chroma Cloud connections. Default is 'default_database'. - embedding: Embedding function. Defaults to None. - metadatas: List of metadatas. Defaults to None. - ids: List of document IDs. Defaults to None. + embedding: Embedding function. Defaults to `None`. + metadatas: List of metadatas. Defaults to `None`. + ids: List of document IDs. Defaults to `None`. client_settings: Chroma client settings. client: Chroma client. Documentation: https://docs.trychroma.com/reference/python/client - collection_metadata: Collection configurations. Defaults to None. + collection_metadata: Collection configurations. Defaults to `None`. collection_configuration: Index configuration for the collection. - Defaults to None. + Defaults to `None`. kwargs: Additional keyword arguments to initialize a Chroma client. Returns: @@ -1371,15 +1371,15 @@ class Chroma(VectorStore): Default is 'default_tenant' for local Chroma servers. database: Database name. Required for Chroma Cloud connections. Default is 'default_database'. - ids : List of document IDs. Defaults to None. + ids : List of document IDs. Defaults to `None`. documents: List of documents to add to the vectorstore. - embedding: Embedding function. Defaults to None. + embedding: Embedding function. Defaults to `None`. client_settings: Chroma client settings. client: Chroma client. Documentation: https://docs.trychroma.com/reference/python/client - collection_metadata: Collection configurations. Defaults to None. + collection_metadata: Collection configurations. Defaults to `None`. collection_configuration: Index configuration for the collection. - Defaults to None. + Defaults to `None`. kwargs: Additional keyword arguments to initialize a Chroma client. Returns: diff --git a/libs/partners/deepseek/langchain_deepseek/chat_models.py b/libs/partners/deepseek/langchain_deepseek/chat_models.py index 60fd76e0e01..1df7a5a8410 100644 --- a/libs/partners/deepseek/langchain_deepseek/chat_models.py +++ b/libs/partners/deepseek/langchain_deepseek/chat_models.py @@ -371,7 +371,7 @@ class ChatDeepSeek(BaseChatOpenAI): - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class (support added in 0.1.20), + - a `TypedDict` class (support added in 0.1.20), - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -379,7 +379,7 @@ class ChatDeepSeek(BaseChatOpenAI): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. method: The method for steering model generation, one of: @@ -392,8 +392,8 @@ class ChatDeepSeek(BaseChatOpenAI): Added support for ``'json_mode'``. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/partners/exa/langchain_exa/tools.py b/libs/partners/exa/langchain_exa/tools.py index 9fa0b306451..4e706f2abc7 100644 --- a/libs/partners/exa/langchain_exa/tools.py +++ b/libs/partners/exa/langchain_exa/tools.py @@ -213,7 +213,7 @@ class ExaFindSimilarResults(BaseTool): # type: ignore[override] end_crawl_date: The end date for the crawl (in YYYY-MM-DD format). start_published_date: The start date for when the document was published (in YYYY-MM-DD format). end_published_date: The end date for when the document was published (in YYYY-MM-DD format). - exclude_source_domain: If True, exclude pages from the same domain as the source URL. + exclude_source_domain: If `True`, exclude pages from the same domain as the source URL. category: Filter for similar pages by category. livecrawl: Option to crawl live webpages if content is not in the index. Options: "always", "fallback", "never" summary: Whether to include a summary of the content. Can be a boolean or a dict with a custom query. diff --git a/libs/partners/fireworks/langchain_fireworks/chat_models.py b/libs/partners/fireworks/langchain_fireworks/chat_models.py index 1429436e21a..0c69a527c8d 100644 --- a/libs/partners/fireworks/langchain_fireworks/chat_models.py +++ b/libs/partners/fireworks/langchain_fireworks/chat_models.py @@ -334,7 +334,7 @@ class ChatFireworks(BaseChatModel): default=None, alias="timeout" ) """Timeout for requests to Fireworks completion API. Can be ``float``, - ``httpx.Timeout`` or ``None``.""" + ``httpx.Timeout`` or `None`.""" streaming: bool = False """Whether to stream the results or not.""" n: int = 1 @@ -635,7 +635,7 @@ class ChatFireworks(BaseChatModel): tool_choice: Which tool to require the model to call. Must be the name of the single provided function, ``'auto'`` to automatically determine which function to call - with the option to not call any function, ``'any'`` to enforce that some + with the option to not call any function, `'any'` to enforce that some function is called, or a dict of the form: ``{"type": "function", "function": {"name": <>}}``. **kwargs: Any additional parameters to pass to @@ -681,7 +681,7 @@ class ChatFireworks(BaseChatModel): - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class (support added in 0.1.7), + - a `TypedDict` class (support added in 0.1.7), - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -689,7 +689,7 @@ class ChatFireworks(BaseChatModel): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. !!! warning "Behavior changed in 0.1.7" Added support for TypedDict class. @@ -707,8 +707,8 @@ class ChatFireworks(BaseChatModel): Added support for ``'json_schema'``. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/partners/groq/langchain_groq/chat_models.py b/libs/partners/groq/langchain_groq/chat_models.py index 0b7006fcb05..639838e9ab2 100644 --- a/libs/partners/groq/langchain_groq/chat_models.py +++ b/libs/partners/groq/langchain_groq/chat_models.py @@ -835,7 +835,7 @@ class ChatGroq(BaseChatModel): - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class (supported added in 0.1.9), + - a `TypedDict` class (supported added in 0.1.9), - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -843,7 +843,7 @@ class ChatGroq(BaseChatModel): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. !!! warning "Behavior changed in 0.1.9" Added support for TypedDict class. @@ -885,8 +885,8 @@ class ChatGroq(BaseChatModel): ``'json_mode'`` does not support streaming responses stop sequences. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py b/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py index 490d92cf048..fc26e8e902a 100644 --- a/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py +++ b/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py @@ -896,8 +896,8 @@ class ChatHuggingFace(BaseChatModel): - ``'json_mode'``: uses JSON mode. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py b/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py index afe8e93b956..5b34deccc45 100644 --- a/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py +++ b/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py @@ -175,7 +175,7 @@ class HuggingFaceEndpoint(LLM): # model (`str`, `optional`): # The model to run inference with. Can be a model id hosted on the Hugging # Face Hub, e.g. `bigcode/starcoder` - # or a URL to a deployed Inference Endpoint. Defaults to None, in which + # or a URL to a deployed Inference Endpoint. Defaults to `None`, in which # case a recommended model is # automatically selected for the task. diff --git a/libs/partners/mistralai/langchain_mistralai/chat_models.py b/libs/partners/mistralai/langchain_mistralai/chat_models.py index 9ce2f81ecb4..edea4f27bc4 100644 --- a/libs/partners/mistralai/langchain_mistralai/chat_models.py +++ b/libs/partners/mistralai/langchain_mistralai/chat_models.py @@ -753,7 +753,7 @@ class ChatMistralAI(BaseChatModel): - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class (support added in 0.1.12), + - a `TypedDict` class (support added in 0.1.12), - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -761,7 +761,7 @@ class ChatMistralAI(BaseChatModel): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. !!! warning "Behavior changed in 0.1.12" Added support for TypedDict class. @@ -785,8 +785,8 @@ class ChatMistralAI(BaseChatModel): Added method="json_schema" include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict @@ -794,9 +794,9 @@ class ChatMistralAI(BaseChatModel): kwargs: Any additional parameters are passed directly to ``self.bind(**kwargs)``. This is useful for passing in - parameters such as ``tool_choice`` or ``tools`` to control + parameters such as `tool_choice` or `tools` to control which tool the model should call, or to pass in parameters such as - ``stop`` to control when the model should stop generating output. + `stop` to control when the model should stop generating output. Returns: A Runnable that takes same inputs as a `langchain_core.language_models.chat.BaseChatModel`. diff --git a/libs/partners/ollama/langchain_ollama/__init__.py b/libs/partners/ollama/langchain_ollama/__init__.py index 53ffa95927e..d0ae3d03e96 100644 --- a/libs/partners/ollama/langchain_ollama/__init__.py +++ b/libs/partners/ollama/langchain_ollama/__init__.py @@ -6,7 +6,7 @@ service. !!! note **Newly added in 0.3.4:** ``validate_model_on_init`` param on all models. This parameter allows you to validate the model exists in Ollama locally on - initialization. If set to ``True``, it will raise an error if the model does not + initialization. If set to `True`, it will raise an error if the model does not exist locally. This is useful for ensuring that the model is available before attempting to use it, especially in environments where models may not be pre-downloaded. diff --git a/libs/partners/ollama/langchain_ollama/chat_models.py b/libs/partners/ollama/langchain_ollama/chat_models.py index 3baf00942ea..1ed910d0402 100644 --- a/libs/partners/ollama/langchain_ollama/chat_models.py +++ b/libs/partners/ollama/langchain_ollama/chat_models.py @@ -273,16 +273,16 @@ class ChatOllama(BaseChatModel): Controls the reasoning/thinking mode for `supported models `__. - - ``True``: Enables reasoning mode. The model's reasoning process will be + - `True`: Enables reasoning mode. The model's reasoning process will be captured and returned separately in the ``additional_kwargs`` of the response message, under ``reasoning_content``. The main response content will not include the reasoning tags. - - ``False``: Disables reasoning mode. The model will not perform any reasoning, + - `False`: Disables reasoning mode. The model will not perform any reasoning, and the response will not include any reasoning content. - - ``None`` (Default): The model will use its default reasoning behavior. Note + - `None` (Default): The model will use its default reasoning behavior. Note however, if the model's default behavior *is* to perform reasoning, think tags (```` and ````) will be present within the main response content - unless you set ``reasoning`` to ``True``. + unless you set ``reasoning`` to `True`. temperature: float Sampling temperature. Ranges from ``0.0`` to ``1.0``. num_predict: Optional[int] @@ -481,12 +481,12 @@ class ChatOllama(BaseChatModel): Thinking / Reasoning: You can enable reasoning mode for models that support it by setting - the ``reasoning`` parameter to ``True`` in either the constructor or - the ``invoke``/``stream`` methods. This will enable the model to think + the ``reasoning`` parameter to `True` in either the constructor or + the `invoke`/`stream` methods. This will enable the model to think through the problem and return the reasoning process separately in the ``additional_kwargs`` of the response message, under ``reasoning_content``. - If ``reasoning`` is set to ``None``, the model will use its default reasoning + If ``reasoning`` is set to `None`, the model will use its default reasoning behavior, and any reasoning content will *not* be captured under the ``reasoning_content`` key, but will be present within the main response content as think tags (```` and ````). @@ -526,17 +526,17 @@ class ChatOllama(BaseChatModel): reasoning: Optional[Union[bool, str]] = None """Controls the reasoning/thinking mode for `supported models `__. - - ``True``: Enables reasoning mode. The model's reasoning process will be + - `True`: Enables reasoning mode. The model's reasoning process will be captured and returned separately in the ``additional_kwargs`` of the response message, under ``reasoning_content``. The main response content will not include the reasoning tags. - - ``False``: Disables reasoning mode. The model will not perform any reasoning, + - `False`: Disables reasoning mode. The model will not perform any reasoning, and the response will not include any reasoning content. - - ``None`` (Default): The model will use its default reasoning behavior. Note + - `None` (Default): The model will use its default reasoning behavior. Note however, if the model's default behavior *is* to perform reasoning, think tags ()```` and ````) will be present within the main response content - unless you set ``reasoning`` to ``True``. - - ``str``: e.g. ``'low'``, ``'medium'``, ``'high'``. Enables reasoning with a custom + unless you set ``reasoning`` to `True`. + - `str`: e.g. ``'low'``, ``'medium'``, ``'high'``. Enables reasoning with a custom intensity level. Currently, this is only supported ``gpt-oss``. See the `Ollama docs `__ for more information. @@ -551,7 +551,7 @@ class ChatOllama(BaseChatModel): mirostat: Optional[int] = None """Enable Mirostat sampling for controlling perplexity. - (Default: ``0``, ``0`` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0) + (Default: `0`, `0` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0) """ mirostat_eta: Optional[float] = None @@ -580,7 +580,7 @@ class ChatOllama(BaseChatModel): num_gpu: Optional[int] = None """The number of GPUs to use. - On macOS it defaults to ``1`` to enable metal support, ``0`` to disable. + On macOS it defaults to ``1`` to enable metal support, `0` to disable. """ num_thread: Optional[int] = None @@ -600,7 +600,7 @@ class ChatOllama(BaseChatModel): repeat_last_n: Optional[int] = None """Sets how far back for the model to look back to prevent repetition. - (Default: ``64``, ``0`` = disabled, ``-1`` = ``num_ctx``) + (Default: ``64``, `0` = disabled, ``-1`` = ``num_ctx``) """ repeat_penalty: Optional[float] = None @@ -695,17 +695,17 @@ class ChatOllama(BaseChatModel): """ async_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the async client; for shared args use ``client_kwargs``. + These are clients unique to the async client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ sync_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the sync client; for shared args use ``client_kwargs``. + These are clients unique to the sync client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ @@ -1262,7 +1262,7 @@ class ChatOllama(BaseChatModel): - a Pydantic class, - a JSON schema - - a TypedDict class + - a `TypedDict` class - an OpenAI function/tool schema. If ``schema`` is a Pydantic class then the model output will be a @@ -1270,7 +1270,7 @@ class ChatOllama(BaseChatModel): validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. method: The method for steering model generation, one of: @@ -1284,9 +1284,9 @@ class ChatOllama(BaseChatModel): desired schema into the model call. include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True - then both the raw model response (a ``BaseMessage``) and the parsed model + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` + then both the raw model response (a `BaseMessage`) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict with keys ``'raw'``, ``'parsed'``, and ``'parsing_error'``. @@ -1300,7 +1300,7 @@ class ChatOllama(BaseChatModel): If ``include_raw`` is True, then Runnable outputs a dict with keys: - - ``'raw'``: ``BaseMessage`` + - ``'raw'``: `BaseMessage` - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - ``'parsing_error'``: Optional[BaseException] diff --git a/libs/partners/ollama/langchain_ollama/embeddings.py b/libs/partners/ollama/langchain_ollama/embeddings.py index 5a7a5352e13..649fcdbf4b4 100644 --- a/libs/partners/ollama/langchain_ollama/embeddings.py +++ b/libs/partners/ollama/langchain_ollama/embeddings.py @@ -160,17 +160,17 @@ class OllamaEmbeddings(BaseModel, Embeddings): """ async_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the async client; for shared args use ``client_kwargs``. + These are clients unique to the async client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ sync_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the sync client; for shared args use ``client_kwargs``. + These are clients unique to the sync client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ @@ -183,7 +183,7 @@ class OllamaEmbeddings(BaseModel, Embeddings): mirostat: Optional[int] = None """Enable Mirostat sampling for controlling perplexity. - (default: ``0``, ``0`` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0)""" + (default: `0`, `0` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0)""" mirostat_eta: Optional[float] = None """Influences how quickly the algorithm responds to feedback @@ -202,7 +202,7 @@ class OllamaEmbeddings(BaseModel, Embeddings): num_gpu: Optional[int] = None """The number of GPUs to use. On macOS it defaults to ``1`` to - enable metal support, ``0`` to disable.""" + enable metal support, `0` to disable.""" keep_alive: Optional[int] = None """Controls how long the model will stay loaded into memory @@ -217,7 +217,7 @@ class OllamaEmbeddings(BaseModel, Embeddings): repeat_last_n: Optional[int] = None """Sets how far back for the model to look back to prevent - repetition. (Default: ``64``, ``0`` = disabled, ``-1`` = ``num_ctx``)""" + repetition. (Default: ``64``, `0` = disabled, ``-1`` = ``num_ctx``)""" repeat_penalty: Optional[float] = None """Sets how strongly to penalize repetitions. A higher value (e.g., ``1.5``) diff --git a/libs/partners/ollama/langchain_ollama/llms.py b/libs/partners/ollama/langchain_ollama/llms.py index 26aac086fbd..b495069fd70 100644 --- a/libs/partners/ollama/langchain_ollama/llms.py +++ b/libs/partners/ollama/langchain_ollama/llms.py @@ -116,13 +116,13 @@ class OllamaLLM(BaseLLM): """Controls the reasoning/thinking mode for `supported models `__. - - ``True``: Enables reasoning mode. The model's reasoning process will be + - `True`: Enables reasoning mode. The model's reasoning process will be captured and returned separately in the ``additional_kwargs`` of the response message, under ``reasoning_content``. The main response content will not include the reasoning tags. - - ``False``: Disables reasoning mode. The model will not perform any reasoning, + - `False`: Disables reasoning mode. The model will not perform any reasoning, and the response will not include any reasoning content. - - ``None`` (Default): The model will use its default reasoning behavior. If + - `None` (Default): The model will use its default reasoning behavior. If the model performs reasoning, the ```` and ```` tags will be present directly within the main response content.""" @@ -134,7 +134,7 @@ class OllamaLLM(BaseLLM): mirostat: Optional[int] = None """Enable Mirostat sampling for controlling perplexity. - (default: ``0``, ``0`` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0)""" + (default: `0`, `0` = disabled, ``1`` = Mirostat, ``2`` = Mirostat 2.0)""" mirostat_eta: Optional[float] = None """Influences how quickly the algorithm responds to feedback @@ -153,7 +153,7 @@ class OllamaLLM(BaseLLM): num_gpu: Optional[int] = None """The number of GPUs to use. On macOS it defaults to ``1`` to - enable metal support, ``0`` to disable.""" + enable metal support, `0` to disable.""" num_thread: Optional[int] = None """Sets the number of threads to use during computation. @@ -167,7 +167,7 @@ class OllamaLLM(BaseLLM): repeat_last_n: Optional[int] = None """Sets how far back for the model to look back to prevent - repetition. (Default: ``64``, ``0`` = disabled, ``-1`` = ``num_ctx``)""" + repetition. (Default: ``64``, `0` = disabled, ``-1`` = ``num_ctx``)""" repeat_penalty: Optional[float] = None """Sets how strongly to penalize repetitions. A higher value (e.g., ``1.5``) @@ -239,17 +239,17 @@ class OllamaLLM(BaseLLM): """ async_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the async client; for shared args use ``client_kwargs``. + These are clients unique to the async client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ sync_client_kwargs: Optional[dict] = {} - """Additional kwargs to merge with ``client_kwargs`` before passing to httpx client. + """Additional kwargs to merge with `client_kwargs` before passing to httpx client. - These are clients unique to the sync client; for shared args use ``client_kwargs``. + These are clients unique to the sync client; for shared args use `client_kwargs`. For a full list of the params, see the `httpx documentation `__. """ diff --git a/libs/partners/openai/langchain_openai/chat_models/azure.py b/libs/partners/openai/langchain_openai/chat_models/azure.py index cf226d297f1..821742205d7 100644 --- a/libs/partners/openai/langchain_openai/chat_models/azure.py +++ b/libs/partners/openai/langchain_openai/chat_models/azure.py @@ -900,7 +900,7 @@ class AzureChatOpenAI(BaseChatOpenAI): If a model elects to call a tool, the resulting `AIMessage` in ``'raw'`` will include tool calls. - ??? note "Example" + ??? example .. code-block:: python diff --git a/libs/partners/openai/langchain_openai/chat_models/base.py b/libs/partners/openai/langchain_openai/chat_models/base.py index d9665272d66..b7a2db1d85e 100644 --- a/libs/partners/openai/langchain_openai/chat_models/base.py +++ b/libs/partners/openai/langchain_openai/chat_models/base.py @@ -1791,7 +1791,7 @@ class BaseChatOpenAI(BaseChatModel): If a model elects to call a tool, the resulting `AIMessage` in `'raw'` will include tool calls. - ??? note "Example" + ??? example ```python from langchain.chat_models import init_chat_model @@ -2015,7 +2015,7 @@ class BaseChatOpenAI(BaseChatModel): class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] r"""Interface to OpenAI chat model APIs. - ???+ note "Setup" + ???+ info "Setup" Install `langchain-openai` and set environment variable `OPENAI_API_KEY`. @@ -2030,42 +2030,32 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] export OPENAI_API_KEY="your-api-key" ``` - ??? note "Key init args — completion params" + ??? info "Key init args — completion params" - model: str - Name of OpenAI model to use. - temperature: float - Sampling temperature. - max_tokens: int | None - Max number of tokens to generate. - logprobs: bool | None - Whether to return logprobs. - stream_options: Dict - Configure streaming outputs, like whether to return token usage when - streaming (`{"include_usage": True}`). - use_responses_api: bool | None - Whether to use the responses API. + | Param | Type | Description | + | ------------------- | ------------- | ----------------------------------------------------------------------------------------------------------- | + | `model` | `str` | Name of OpenAI model to use. | + | `temperature` | `float` | Sampling temperature. | + | `max_tokens` | `int | None` | Max number of tokens to generate. | + | `logprobs` | `bool | None` | Whether to return logprobs. | + | `stream_options` | `dict` | Configure streaming outputs, like whether to return token usage when streaming (`{"include_usage": True}`). | + | `use_responses_api` | `bool | None` | Whether to use the responses API. | - See full list of supported init args and their descriptions in the params section. + See full list of supported init args and their descriptions below. - ??? note "Key init args — client params" + ??? info "Key init args — client params" - timeout: Union[float, Tuple[float, float], Any, None] - Timeout for requests. - max_retries: int | None - Max number of retries. - api_key: str | None - OpenAI API key. If not passed in will be read from env var `OPENAI_API_KEY`. - base_url: str | None - Base URL for API requests. Only specify if using a proxy or service - emulator. - organization: str | None - OpenAI organization ID. If not passed in will be read from env - var `OPENAI_ORG_ID`. + | Param | Type | Description | + | -------------- | ------------------------------------------ | ----------------------------------------------------------------------------------- | + | `timeout` | `float | Tuple[float, float] | Any | None` | Timeout for requests. | + | `max_retries` | `int | None` | Max number of retries. | + | `api_key` | `str | None` | OpenAI API key. If not passed in will be read from env var `OPENAI_API_KEY`. | + | `base_url` | `str | None` | Base URL for API requests. Only specify if using a proxy or service emulator. | + | `organization` | `str | None` | OpenAI organization ID. If not passed in will be read from env var `OPENAI_ORG_ID`. | - See full list of supported init args and their descriptions in the params section. + See full list of supported init args and their descriptions below. - ??? note "Instantiate" + ??? info "Instantiate" Create a model instance with desired params. For example: @@ -2107,7 +2097,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ChatOpenAI(...).invoke(..., frequency_penalty=0.2) ``` - ??? note "Invoke" + ??? info "Invoke" Generate a response from the model: @@ -2143,7 +2133,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ) ``` - ??? note "Stream" + ??? info "Stream" Stream a response from the model: @@ -2187,7 +2177,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ) ``` - ??? note "Async" + ??? info "Async" Asynchronous equivalents of `invoke`, `stream`, and `batch` are also available: @@ -2227,9 +2217,9 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ) ``` - For batched calls, results in a list of `AIMessage` responses. + For batched calls, results in a `list[AIMessage]`. - ??? note "Tool calling" + ??? info "Tool calling" ```python from pydantic import BaseModel, Field @@ -2314,17 +2304,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] See `bind_tools` for more. - ??? note "Built-in (server-side) tools" - - !!! version-added "Added in version 0.3.9" - - !!! version-added "Added in version 0.3.26: Updated `AIMessage` format" - `langchain-openai >= 0.3.26` allows users to opt-in to an updated - `AIMessage` format when using the Responses API. Setting - `ChatOpenAI(..., output_version="responses/v1")` will format output from - reasoning summaries, built-in tool invocations, and other response items - into the message's `content` field, rather than `additional_kwargs`. We - recommend this format for new applications. + ??? info "Built-in (server-side) tools" You can access [built-in tools](https://platform.openai.com/docs/guides/tools?api-mode=responses) supported by the OpenAI Responses API. See [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/openai#responses-api) @@ -2360,10 +2340,18 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ] ``` - ??? note "Managing conversation state" - !!! version-added "Added in version 0.3.9" + !!! version-added "Added in version 0.3.26: Updated `AIMessage` format" + [`langchain-openai >= 0.3.26`](https://pypi.org/project/langchain-openai/#history) + allows users to opt-in to an updated `AIMessage` format when using the + Responses API. Setting `ChatOpenAI(..., output_version="responses/v1")` will + format output from reasoning summaries, built-in tool invocations, and other + response items into the message's `content` field, rather than + `additional_kwargs`. We recommend this format for new applications. + + ??? info "Managing conversation state" + OpenAI's Responses API supports management of [conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses). Passing in response IDs from previous messages will continue a conversational thread. @@ -2380,7 +2368,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] response.text ``` - ```python + ```txt "Hi Bob! How can I assist you today?" ``` @@ -2392,12 +2380,13 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] second_response.text ``` - ```python + ```txt "Your name is Bob. How can I help you today, Bob?" ``` - !!! version-added "Added in version 0.3.26" + !!! version-added "Added in version 0.3.9" + !!! version-added "Added in version 0.3.26" You can also initialize `ChatOpenAI` with `use_previous_response_id`. Input messages up to the most recent response will then be dropped from request payloads, and `previous_response_id` will be set using the ID of the most @@ -2407,15 +2396,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] llm = ChatOpenAI(model="...", use_previous_response_id=True) ``` - ??? note "Reasoning output" - - !!! version-added "Added in version 0.3.26: Updated `AIMessage` format" - `langchain-openai >= 0.3.26` allows users to opt-in to an updated - `AIMessage` format when using the Responses API. Setting - `ChatOpenAI(..., output_version="responses/v1")` will format output from - reasoning summaries, built-in tool invocations, and other response items - into the message's `content` field, rather than `additional_kwargs`. We - recommend this format for new applications. + ??? info "Reasoning output" OpenAI's Responses API supports [reasoning models](https://platform.openai.com/docs/guides/reasoning?api-mode=responses) that expose a summary of internal reasoning processes. @@ -2448,7 +2429,15 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] Reasoning: The user wants to know... ``` - ??? note "Structured output" + !!! version-added "Added in version 0.3.26: Updated `AIMessage` format" + [`langchain-openai >= 0.3.26`](https://pypi.org/project/langchain-openai/#history) + allows users to opt-in to an updated `AIMessage` format when using the + Responses API. Setting `ChatOpenAI(..., output_version="responses/v1")` will + format output from reasoning summaries, built-in tool invocations, and other + response items into the message's `content` field, rather than + `additional_kwargs`. We recommend this format for new applications. + + ??? info "Structured output" ```python from pydantic import BaseModel, Field @@ -2478,7 +2467,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] See `with_structured_output` for more info. - ??? note "JSON mode" + ??? info "JSON mode" ```python json_llm = llm.bind(response_format={"type": "json_object"}) @@ -2492,7 +2481,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] '\\n{\\n "random_ints": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\\n}' ``` - ??? note "Image input" + ??? info "Image input" ```python import base64 @@ -2519,7 +2508,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] "The weather in the image appears to be clear and pleasant. The sky is mostly blue with scattered, light clouds, suggesting a sunny day with minimal cloud cover. There is no indication of rain or strong winds, and the overall scene looks bright and calm. The lush green grass and clear visibility further indicate good weather conditions." ``` - ??? note "Token usage" + ??? info "Token usage" ```python ai_msg = llm.invoke(messages) @@ -2543,7 +2532,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] {"input_tokens": 28, "output_tokens": 5, "total_tokens": 33} ``` - ??? note "Logprobs" + ??? info "Logprobs" ```python logprobs_llm = llm.bind(logprobs=True) @@ -2603,7 +2592,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] } ``` - ??? note "Response metadata" + ??? info "Response metadata" ```python ai_msg = llm.invoke(messages) @@ -2624,7 +2613,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] } ``` - ??? note "Flex processing" + ??? info "Flex processing" OpenAI offers a variety of [service tiers](https://platform.openai.com/docs/guides/flex-processing?api-mode=responses). The "flex" tier offers cheaper pricing for requests, with the trade-off that @@ -2644,7 +2633,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] See OpenAI [flex processing docs](https://platform.openai.com/docs/guides/flex-processing?api-mode=responses) for more detail. - ??? note "OpenAI-compatible APIs" + ??? info "OpenAI-compatible APIs" `ChatOpenAI` can be used with OpenAI-compatible APIs like [LM Studio](https://lmstudio.ai/), [vLLM](https://github.com/vllm-project/vllm), @@ -2673,7 +2662,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] ) ``` - ??? note "`model_kwargs` vs `extra_body`" + ??? info "`model_kwargs` vs `extra_body`" Use the correct parameter for different types of API arguments: @@ -2725,7 +2714,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] Always use `extra_body` for custom parameters, **not** `model_kwargs`. Using `model_kwargs` for non-OpenAI parameters will cause API errors. - ??? note "Prompt caching optimization" + ??? info "Prompt caching optimization" For high-volume applications with repetitive prompts, use `prompt_cache_key` per-invocation to improve cache hit rates and reduce costs: @@ -2749,7 +2738,6 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] Cache keys help ensure requests with the same prompt prefix are routed to machines with existing cache, providing cost reduction and latency improvement on cached tokens. - """ # noqa: E501 max_tokens: Optional[int] = Field(default=None, alias="max_completion_tokens") @@ -2907,7 +2895,7 @@ class ChatOpenAI(BaseChatOpenAI): # type: ignore[override] If a model elects to call a tool, the resulting `AIMessage` in `'raw'` will include tool calls. - ??? note "Example" + ??? example ```python from langchain.chat_models import init_chat_model diff --git a/libs/partners/openai/tests/integration_tests/chat_models/test_responses_standard.py b/libs/partners/openai/tests/integration_tests/chat_models/test_responses_standard.py index 788fb39f3c0..565b88fa95a 100644 --- a/libs/partners/openai/tests/integration_tests/chat_models/test_responses_standard.py +++ b/libs/partners/openai/tests/integration_tests/chat_models/test_responses_standard.py @@ -84,7 +84,7 @@ class TestOpenAIResponses(TestOpenAIStandard): return False def test_openai_pdf_tool_messages(self, model: BaseChatModel) -> None: - """Test that the model can process PDF inputs in ToolMessages.""" + """Test that the model can process PDF inputs in `ToolMessage` objects.""" url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" pdf_data = base64.b64encode(httpx.get(url).content).decode("utf-8") diff --git a/libs/partners/perplexity/langchain_perplexity/chat_models.py b/libs/partners/perplexity/langchain_perplexity/chat_models.py index a8e906e9d97..08ffe2539a5 100644 --- a/libs/partners/perplexity/langchain_perplexity/chat_models.py +++ b/libs/partners/perplexity/langchain_perplexity/chat_models.py @@ -414,7 +414,7 @@ class ChatPerplexity(BaseChatModel): schema: The output schema. Can be passed in as: - a JSON Schema, - - a TypedDict class, + - a `TypedDict` class, - or a Pydantic class method: The method for steering model generation, currently only support: @@ -423,8 +423,8 @@ class ChatPerplexity(BaseChatModel): include_raw: - If False then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If True + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict diff --git a/libs/partners/prompty/langchain_prompty/utils.py b/libs/partners/prompty/langchain_prompty/utils.py index 970a2f83db3..32fba7e743a 100644 --- a/libs/partners/prompty/langchain_prompty/utils.py +++ b/libs/partners/prompty/langchain_prompty/utils.py @@ -19,7 +19,7 @@ def load(prompt_path: str, configuration: str = "default") -> Prompty: Args: prompt_path: The path to the prompty file. - configuration: The configuration to use. Defaults to ``'default'``. + configuration: The configuration to use. Defaults to `'default'`. Returns: The Prompty object. @@ -126,7 +126,7 @@ def prepare( Args: prompt: The Prompty object. - inputs: The inputs to the prompty. Defaults to ``{}``. + inputs: The inputs to the prompty. Defaults to `{}`. Returns: The prepared inputs. @@ -176,9 +176,9 @@ def run( Args: prompt: The Prompty object. content: The content to run the prompty on. - configuration: The configuration to use. Defaults to ``{}``. - parameters: The parameters to use. Defaults to ``{}``. - raw: Whether to return the raw output. Defaults to False. + configuration: The configuration to use. Defaults to `{}`. + parameters: The parameters to use. Defaults to `{}`. + raw: Whether to return the raw output. Defaults to `False`. Returns: The result of running the prompty. @@ -230,11 +230,11 @@ def execute( Args: prompt: The prompt to execute. Can be a path to a prompty file or a Prompty object. - configuration: The configuration to use. Defaults to ``{}``. - parameters: The parameters to use. Defaults to ``{}``. - inputs: The inputs to the prompty. Defaults to ``{}``. - raw: Whether to return the raw output. Defaults to False. - connection: The connection to use. Defaults to ``'default'``. + configuration: The configuration to use. Defaults to `{}`. + parameters: The parameters to use. Defaults to `{}`. + inputs: The inputs to the prompty. Defaults to `{}`. + raw: Whether to return the raw output. Defaults to `False`. + connection: The connection to use. Defaults to `'default'`. Returns: The result of executing the prompty. diff --git a/libs/partners/qdrant/langchain_qdrant/fastembed_sparse.py b/libs/partners/qdrant/langchain_qdrant/fastembed_sparse.py index 2f855a23728..1b6a52eb486 100644 --- a/libs/partners/qdrant/langchain_qdrant/fastembed_sparse.py +++ b/libs/partners/qdrant/langchain_qdrant/fastembed_sparse.py @@ -40,7 +40,7 @@ class FastEmbedSparse(SparseEmbeddings): If `0`, use all available cores.\ If `None`, don't use data-parallel processing,\ use default onnxruntime threading instead.\ - Defaults to None. + Defaults to `None`. kwargs: Additional options to pass to fastembed.SparseTextEmbedding Raises: ValueError: If the model_name is not supported in SparseTextEmbedding. diff --git a/libs/partners/qdrant/langchain_qdrant/qdrant.py b/libs/partners/qdrant/langchain_qdrant/qdrant.py index 2472a6fdbc7..013dbd747d5 100644 --- a/libs/partners/qdrant/langchain_qdrant/qdrant.py +++ b/libs/partners/qdrant/langchain_qdrant/qdrant.py @@ -329,7 +329,7 @@ class QdrantVectorStore(VectorStore): """Get the sparse embeddings instance that is being used. Raises: - ValueError: If sparse embeddings are ``None``. + ValueError: If sparse embeddings are `None`. Returns: SparseEmbeddings: An instance of ``SparseEmbeddings``. diff --git a/libs/partners/qdrant/langchain_qdrant/vectorstores.py b/libs/partners/qdrant/langchain_qdrant/vectorstores.py index 8b6f6b5510f..9ad20acff84 100644 --- a/libs/partners/qdrant/langchain_qdrant/vectorstores.py +++ b/libs/partners/qdrant/langchain_qdrant/vectorstores.py @@ -240,7 +240,7 @@ class Qdrant(VectorStore): Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -295,7 +295,7 @@ class Qdrant(VectorStore): Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. **kwargs: Additional keyword arguments. Returns: @@ -321,7 +321,7 @@ class Qdrant(VectorStore): Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -379,7 +379,7 @@ class Qdrant(VectorStore): Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -438,7 +438,7 @@ class Qdrant(VectorStore): Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -497,7 +497,7 @@ class Qdrant(VectorStore): Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -556,7 +556,7 @@ class Qdrant(VectorStore): Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -645,7 +645,7 @@ class Qdrant(VectorStore): Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params offset: Offset of the first result to return. @@ -749,7 +749,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params score_threshold: Define a minimal score threshold for the result. @@ -815,7 +815,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params score_threshold: Define a minimal score threshold for the result. @@ -880,7 +880,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params score_threshold: Define a minimal score threshold for the result. @@ -946,7 +946,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params score_threshold: Define a minimal score threshold for the result. @@ -1013,7 +1013,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params score_threshold: Define a minimal score threshold for the result. @@ -1105,7 +1105,7 @@ class Qdrant(VectorStore): of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. - filter: Filter by metadata. Defaults to None. + filter: Filter by metadata. Defaults to `None`. search_params: Additional search params. score_threshold: Define a minimal score threshold for the result. consistency: Read consistency of the search. diff --git a/libs/partners/xai/langchain_xai/chat_models.py b/libs/partners/xai/langchain_xai/chat_models.py index f4268326f1a..e6037e04692 100644 --- a/libs/partners/xai/langchain_xai/chat_models.py +++ b/libs/partners/xai/langchain_xai/chat_models.py @@ -43,7 +43,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] model: str Name of model to use. temperature: float - Sampling temperature between ``0`` and ``2``. Higher values mean more random completions, + Sampling temperature between `0` and ``2``. Higher values mean more random completions, while lower values (like ``0.2``) mean more focused and deterministic completions. (Default: ``1``.) max_tokens: Optional[int] @@ -235,19 +235,19 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] With stream response, the tool / function call will be returned in whole in a single chunk, instead of being streamed across chunks. - Tool choice can be controlled by setting the ``tool_choice`` parameter in the model + Tool choice can be controlled by setting the `tool_choice` parameter in the model constructor's ``extra_body`` argument. For example, to disable tool / function calling: .. code-block:: python llm = ChatXAI(model="grok-4", extra_body={"tool_choice": "none"}) - To require that the model always calls a tool / function, set ``tool_choice`` to ``'required'``: + To require that the model always calls a tool / function, set `tool_choice` to ``'required'``: .. code-block:: python llm = ChatXAI(model="grok-4", extra_body={"tool_choice": "required"}) - To specify a tool / function to call, set ``tool_choice`` to the name of the tool / function: + To specify a tool / function to call, set `tool_choice` to the name of the tool / function: .. code-block:: python @@ -592,7 +592,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] - an OpenAI function/tool schema, - a JSON Schema, - - a TypedDict class (support added in 0.1.20), + - a `TypedDict` class (support added in 0.1.20), - or a Pydantic class. If ``schema`` is a Pydantic class then the model output will be a @@ -600,7 +600,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] validated by the Pydantic class. Otherwise the model output will be a dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool` for more on how to properly specify types and descriptions of - schema fields when specifying a Pydantic or TypedDict class. + schema fields when specifying a Pydantic or `TypedDict` class. method: The method for steering model generation, one of: @@ -612,21 +612,21 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] Uses xAI's JSON mode feature. include_raw: - If ``False`` then only the parsed structured output is returned. If - an error occurs during model output parsing it will be raised. If ``True`` + If `False` then only the parsed structured output is returned. If + an error occurs during model output parsing it will be raised. If `True` then both the raw model response (a BaseMessage) and the parsed model response will be returned. If an error occurs during output parsing it will be caught and returned as well. The final output is always a dict with keys ``'raw'``, ``'parsed'``, and ``'parsing_error'``. strict: - - ``True``: + - `True`: Model output is guaranteed to exactly match the schema. The input schema will also be validated according to the `supported schemas `__. - - ``False``: + - `False`: Input schema will not be validated and model output will not be validated. - - ``None``: + - `None`: ``strict`` argument will not be passed to the model. kwargs: Additional keyword args aren't supported. @@ -634,9 +634,9 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] Returns: A Runnable that takes same inputs as a `langchain_core.language_models.chat.BaseChatModel`. - If ``include_raw`` is ``False`` and ``schema`` is a Pydantic class, Runnable outputs an instance of ``schema`` (i.e., a Pydantic object). Otherwise, if ``include_raw`` is ``False`` then Runnable outputs a dict. + If ``include_raw`` is `False` and ``schema`` is a Pydantic class, Runnable outputs an instance of ``schema`` (i.e., a Pydantic object). Otherwise, if ``include_raw`` is `False` then Runnable outputs a dict. - If ``include_raw`` is ``True``, then Runnable outputs a dict with keys: + If ``include_raw`` is `True`, then Runnable outputs a dict with keys: - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. diff --git a/libs/standard-tests/langchain_tests/integration_tests/chat_models.py b/libs/standard-tests/langchain_tests/integration_tests/chat_models.py index c65ca1ffc24..b87f2ded3f1 100644 --- a/libs/standard-tests/langchain_tests/integration_tests/chat_models.py +++ b/libs/standard-tests/langchain_tests/integration_tests/chat_models.py @@ -143,8 +143,8 @@ def unicode_customer(customer_name: str, description: str) -> str: class ChatModelIntegrationTests(ChatModelTests): '''Base class for chat model integration tests. - Test subclasses must implement the ``chat_model_class`` and - ``chat_model_params`` properties to specify what model to test and its + Test subclasses must implement the `chat_model_class` and + `chat_model_params` properties to specify what model to test and its initialization parameters. Example: @@ -175,7 +175,7 @@ class ChatModelIntegrationTests(ChatModelTests): Test subclasses **must** implement the following two properties: chat_model_class - The chat model class to test, e.g., ``ChatParrotLink``. + The chat model class to test, e.g., `ChatParrotLink`. Example: @@ -222,10 +222,10 @@ class ChatModelIntegrationTests(ChatModelTests): !!! warning Deprecated since version 0.3.15. This property will be removed in version 0.3.20. If a model supports - ``tool_choice``, it should accept ``tool_choice="any"`` and - ``tool_choice=``. If a model does not - support forcing tool calling, override the ``has_tool_choice`` property to - return ``False``. + `tool_choice`, it should accept `tool_choice="any"` and + `tool_choice=`. If a model does not + support forcing tool calling, override the `has_tool_choice` property to + return `False`. Example: @@ -238,13 +238,13 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`has_tool_choice`" Boolean property indicating whether the chat model supports forcing tool - calling via a ``tool_choice`` parameter. + calling via a `tool_choice` parameter. By default, this is determined by whether the parameter is included in the - signature for the corresponding ``bind_tools`` method. + signature for the corresponding `bind_tools` method. - If ``True``, the minimum requirement for this feature is that - ``tool_choice="any"`` will force a tool call, and ``tool_choice=`` + If `True`, the minimum requirement for this feature is that + `tool_choice="any"` will force a tool call, and `tool_choice=` will force a call to a specific tool. Example override: @@ -261,7 +261,7 @@ class ChatModelIntegrationTests(ChatModelTests): output. By default, this is determined by whether the chat model's - ``with_structured_output`` method is overridden. If the base implementation is + `with_structured_output` method is overridden. If the base implementation is intended to be used, this method should be overridden. See: https://python.langchain.com/docs/concepts/structured_outputs/ @@ -277,7 +277,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`structured_output_kwargs`" Dict property that can be used to specify additional kwargs for - ``with_structured_output``. Useful for testing different models. + `with_structured_output`. Useful for testing different models. Example: @@ -290,7 +290,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_json_mode`" Boolean property indicating whether the chat model supports JSON mode in - ``with_structured_output``. + `with_structured_output`. See: https://python.langchain.com/docs/concepts/structured_outputs/#json-mode @@ -305,9 +305,9 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_image_inputs`" Boolean property indicating whether the chat model supports image inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested by inputting an + If set to `True`, the chat model will be tested by inputting an `ImageContentBlock` with the shape: .. code-block:: python @@ -340,9 +340,9 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_image_urls`" Boolean property indicating whether the chat model supports image inputs from - URLs. Defaults to ``False``. + URLs. Defaults to `False`. - If set to ``True``, the chat model will be tested using content blocks of the + If set to `True`, the chat model will be tested using content blocks of the form .. code-block:: python @@ -365,9 +365,9 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_pdf_inputs`" Boolean property indicating whether the chat model supports PDF inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested by inputting a + If set to `True`, the chat model will be tested by inputting a `FileContentBlock` with the shape: .. code-block:: python @@ -391,9 +391,9 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_audio_inputs`" Boolean property indicating whether the chat model supports audio inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested by inputting an + If set to `True`, the chat model will be tested by inputting an `AudioContentBlock` with the shape: .. code-block:: python @@ -417,16 +417,16 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "`supports_video_inputs`" Boolean property indicating whether the chat model supports image inputs. - Defaults to ``False``. No current tests are written for this feature. + Defaults to `False`. No current tests are written for this feature. ??? note "`returns_usage_metadata`" Boolean property indicating whether the chat model returns usage metadata - on invoke and streaming responses. Defaults to ``True``. + on invoke and streaming responses. Defaults to `True`. - ``usage_metadata`` is an optional dict attribute on ``AIMessage``s that track input + `usage_metadata` is an optional dict attribute on `AIMessage`s that track input and output tokens. - `See more. `__ + [See more](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.ai.UsageMetadata.html). Example: @@ -436,8 +436,8 @@ class ChatModelIntegrationTests(ChatModelTests): def returns_usage_metadata(self) -> bool: return False - Models supporting ``usage_metadata`` should also return the name of the - underlying model in the ``response_metadata`` of the ``AIMessage``. + Models supporting `usage_metadata` should also return the name of the + underlying model in the `response_metadata` of the `AIMessage`. ??? note "`supports_anthropic_inputs`" @@ -458,7 +458,7 @@ class ChatModelIntegrationTests(ChatModelTests): }, ] - If set to ``True``, the chat model will be tested using content blocks of this + If set to `True`, the chat model will be tested using content blocks of this form. Example: @@ -504,8 +504,8 @@ class ChatModelIntegrationTests(ChatModelTests): ) - If set to ``True``, the chat model will be tested with message sequences that - include ToolMessages of this form. + If set to `True`, the chat model will be tested with message sequences that + include `ToolMessage` objects of this form. Example: @@ -534,8 +534,8 @@ class ChatModelIntegrationTests(ChatModelTests): name="random_pdf", ) - If set to ``True``, the chat model will be tested with message sequences that - include ToolMessages of this form. + If set to `True`, the chat model will be tested with message sequences that + include `ToolMessage` objects of this form. Example: @@ -550,11 +550,11 @@ class ChatModelIntegrationTests(ChatModelTests): Property controlling what usage metadata details are emitted in both invoke and stream. - ``usage_metadata`` is an optional dict attribute on ``AIMessage``s that track input + `usage_metadata` is an optional dict attribute on `AIMessage`s that track input and output tokens. - `See more. `__ + [See more](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.ai.UsageMetadata.html). - It includes optional keys ``input_token_details`` and ``output_token_details`` + It includes optional keys `input_token_details` and `output_token_details` that can track usage details associated with special types of tokens, such as cached, audio, or reasoning. @@ -568,7 +568,7 @@ class ChatModelIntegrationTests(ChatModelTests): To enable these tests, follow these steps: - 1. Override the ``enable_vcr_tests`` property to return ``True``: + 1. Override the `enable_vcr_tests` property to return `True`: .. code-block:: python @@ -579,17 +579,17 @@ class ChatModelIntegrationTests(ChatModelTests): 2. Configure VCR to exclude sensitive headers and other information from cassettes. - !!! important + !!! warning VCR will by default record authentication headers and other sensitive information in cassettes. Read below for how to configure what information is recorded in cassettes. - To add configuration to VCR, add a ``conftest.py`` file to the ``tests/`` - directory and implement the ``vcr_config`` fixture there. + To add configuration to VCR, add a `conftest.py` file to the `tests/` + directory and implement the `vcr_config` fixture there. - ``langchain-tests`` excludes the headers ``'authorization'``, - ``'x-api-key'``, and ``'api-key'`` from VCR cassettes. To pick up this - configuration, you will need to add ``conftest.py`` as shown below. You can + `langchain-tests` excludes the headers `'authorization'`, + `'x-api-key'`, and `'api-key'` from VCR cassettes. To pick up this + configuration, you will need to add `conftest.py` as shown below. You can also exclude additional headers, override the default exclusions, or apply other customizations to the VCR configuration. See example below: @@ -624,8 +624,8 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Compressing cassettes" - ``langchain-tests`` includes a custom VCR serializer that compresses - cassettes using gzip. To use it, register the ``yaml.gz`` serializer + `langchain-tests` includes a custom VCR serializer that compresses + cassettes using gzip. To use it, register the `yaml.gz` serializer to your VCR fixture and enable this serializer in the config. See example below: @@ -702,12 +702,12 @@ class ChatModelIntegrationTests(ChatModelTests): uv run python -m pytest tests/integration_tests/test_chat_models.py::TestMyModel::test_stream_time This will generate a VCR cassette for the test in - ``tests/integration_tests/cassettes/``. + `tests/integration_tests/cassettes/`. - !!! important + !!! warning You should inspect the generated cassette to ensure that it does not contain sensitive information. If it does, you can modify the - ``vcr_config`` fixture to exclude headers or modify the response + `vcr_config` fixture to exclude headers or modify the response before it is recorded. You can then commit the cassette to your repository. Subsequent test runs @@ -721,13 +721,13 @@ class ChatModelIntegrationTests(ChatModelTests): return {} def test_invoke(self, model: BaseChatModel) -> None: - """Test to verify that ``model.invoke(simple_message)`` works. + """Test to verify that `model.invoke(simple_message)` works. This should pass for all integrations. ??? note "Troubleshooting" - If this test fails, you should make sure your ``_generate`` method + If this test fails, you should make sure your `_generate` method does not raise any exceptions, and that it returns a valid `langchain_core.outputs.chat_result.ChatResult` like so: @@ -747,7 +747,7 @@ class ChatModelIntegrationTests(ChatModelTests): assert len(result.content) > 0 async def test_ainvoke(self, model: BaseChatModel) -> None: - """Test to verify that ``await model.ainvoke(simple_message)`` works. + """Test to verify that `await model.ainvoke(simple_message)` works. This should pass for all integrations. Passing this test does not indicate a "natively async" implementation, but rather that the model can be used @@ -757,7 +757,7 @@ class ChatModelIntegrationTests(ChatModelTests): First, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_invoke`. - because ``ainvoke`` has a default implementation that calls ``invoke`` in an + because `ainvoke` has a default implementation that calls `invoke` in an async context. If that test passes but not this one, you should make sure your _agenerate @@ -781,7 +781,7 @@ class ChatModelIntegrationTests(ChatModelTests): @pytest.mark.parametrize("model", [{}, {"output_version": "v1"}], indirect=True) def test_stream(self, model: BaseChatModel) -> None: - """Test to verify that ``model.stream(simple_message)`` works. + """Test to verify that `model.stream(simple_message)` works. This should pass for all integrations. Passing this test does not indicate a "streaming" implementation, but rather that the model can be used in a @@ -791,10 +791,10 @@ class ChatModelIntegrationTests(ChatModelTests): First, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_invoke`. - because ``stream`` has a default implementation that calls ``invoke`` and + because `stream` has a default implementation that calls `invoke` and yields the result as a single chunk. - If that test passes but not this one, you should make sure your ``_stream`` + If that test passes but not this one, you should make sure your `_stream` method does not raise any exceptions, and that it yields valid `langchain_core.outputs.chat_generation.ChatGenerationChunk` objects like so: @@ -820,7 +820,7 @@ class ChatModelIntegrationTests(ChatModelTests): @pytest.mark.parametrize("model", [{}, {"output_version": "v1"}], indirect=True) async def test_astream(self, model: BaseChatModel) -> None: - """Test to verify that ``await model.astream(simple_message)`` works. + """Test to verify that `await model.astream(simple_message)` works. This should pass for all integrations. Passing this test does not indicate a "natively async" or "streaming" implementation, but rather that the model can @@ -832,11 +832,11 @@ class ChatModelIntegrationTests(ChatModelTests): `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_stream`. and `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_ainvoke`. - because ``astream`` has a default implementation that calls ``_stream`` in - an async context if it is implemented, or ``ainvoke`` and yields the result + because `astream` has a default implementation that calls `_stream` in + an async context if it is implemented, or `ainvoke` and yields the result as a single chunk if not. - If those tests pass but not this one, you should make sure your ``_astream`` + If those tests pass but not this one, you should make sure your `_astream` method does not raise any exceptions, and that it yields valid `langchain_core.outputs.chat_generation.ChatGenerationChunk` objects like so: @@ -861,7 +861,7 @@ class ChatModelIntegrationTests(ChatModelTests): assert full.content_blocks[0]["type"] == "text" def test_batch(self, model: BaseChatModel) -> None: - """Test to verify that ``model.batch([messages])`` works. + """Test to verify that `model.batch([messages])` works. This should pass for all integrations. Tests the model's ability to process multiple prompts in a single batch. @@ -870,10 +870,10 @@ class ChatModelIntegrationTests(ChatModelTests): First, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_invoke` - because ``batch`` has a default implementation that calls ``invoke`` for + because `batch` has a default implementation that calls `invoke` for each message in the batch. - If that test passes but not this one, you should make sure your ``batch`` + If that test passes but not this one, you should make sure your `batch` method does not raise any exceptions, and that it returns a list of valid `langchain_core.messages.AIMessage` objects. @@ -889,7 +889,7 @@ class ChatModelIntegrationTests(ChatModelTests): assert len(result.content) > 0 async def test_abatch(self, model: BaseChatModel) -> None: - """Test to verify that ``await model.abatch([messages])`` works. + """Test to verify that `await model.abatch([messages])` works. This should pass for all integrations. Tests the model's ability to process multiple prompts in a single batch asynchronously. @@ -900,10 +900,10 @@ class ChatModelIntegrationTests(ChatModelTests): `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_batch` and `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_ainvoke` - because ``abatch`` has a default implementation that calls ``ainvoke`` for + because `abatch` has a default implementation that calls `ainvoke` for each message in the batch. - If those tests pass but not this one, you should make sure your ``abatch`` + If those tests pass but not this one, you should make sure your `abatch` method does not raise any exceptions, and that it returns a list of valid `langchain_core.messages.AIMessage` objects. @@ -929,7 +929,7 @@ class ChatModelIntegrationTests(ChatModelTests): First, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_invoke` - because this test also uses ``model.invoke()``. + because this test also uses `model.invoke`. If that test passes but not this one, you should verify that: 1. Your model correctly processes the message history @@ -960,7 +960,7 @@ class ChatModelIntegrationTests(ChatModelTests): First, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_invoke` - because this test also uses ``model.invoke()``. + because this test also uses `model.invoke`. Second, debug `langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_conversation` @@ -995,14 +995,14 @@ class ChatModelIntegrationTests(ChatModelTests): usage metadata (see Configuration below). !!! warning "Behavior changed in 0.3.17" - Additionally check for the presence of ``model_name`` in the response + Additionally check for the presence of `model_name` in the response metadata, which is needed for usage tracking in callback handlers. ??? note "Configuration" By default, this test is run. - To disable this feature, set ``returns_usage_metadata`` to ``False`` in your + To disable this feature, set `returns_usage_metadata` to `False` in your test class: .. code-block:: python @@ -1013,7 +1013,7 @@ class ChatModelIntegrationTests(ChatModelTests): return False This test can also check the format of specific kinds of usage metadata - based on the ``supported_usage_metadata_details`` property. This property + based on the `supported_usage_metadata_details` property. This property should be configured as follows with the types of tokens that the model supports tracking: @@ -1044,7 +1044,7 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, first verify that your model returns `langchain_core.messages.ai.UsageMetadata` dicts - attached to the returned AIMessage object in ``_generate``: + attached to the returned AIMessage object in `_generate`: .. code-block:: python @@ -1072,9 +1072,8 @@ class ChatModelIntegrationTests(ChatModelTests): ] ) - Check also that the response includes a ``'model_name'`` key in its - ``usage_metadata``. - + Check also that the response includes a `model_name` key in its + `usage_metadata`. """ if not self.returns_usage_metadata: pytest.skip("Not implemented.") @@ -1170,13 +1169,13 @@ class ChatModelIntegrationTests(ChatModelTests): Test to verify that the model returns correct usage metadata in streaming mode. !!! warning "Behavior changed in 0.3.17" - Additionally check for the presence of ``model_name`` in the response + Additionally check for the presence of `model_name` in the response metadata, which is needed for usage tracking in callback handlers. ??? note "Configuration" By default, this test is run. - To disable this feature, set ``returns_usage_metadata`` to ``False`` in your + To disable this feature, set `returns_usage_metadata` to `False` in your test class: .. code-block:: python @@ -1187,7 +1186,7 @@ class ChatModelIntegrationTests(ChatModelTests): return False This test can also check the format of specific kinds of usage metadata - based on the ``supported_usage_metadata_details`` property. This property + based on the `supported_usage_metadata_details` property. This property should be configured as follows with the types of tokens that the model supports tracking: @@ -1217,16 +1216,16 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, first verify that your model yields `langchain_core.messages.ai.UsageMetadata` dicts - attached to the returned AIMessage object in ``_stream`` + attached to the returned AIMessage object in `_stream` that sum up to the total usage metadata. - Note that ``input_tokens`` should only be included on one of the chunks - (typically the first or the last chunk), and the rest should have ``0`` or - ``None`` to avoid counting input tokens multiple times. + Note that `input_tokens` should only be included on one of the chunks + (typically the first or the last chunk), and the rest should have `0` or + `None` to avoid counting input tokens multiple times. - ``output_tokens`` typically count the number of tokens in each chunk, not - the sum. This test will pass as long as the sum of ``output_tokens`` across - all chunks is not ``0``. + `output_tokens` typically count the number of tokens in each chunk, not + the sum. This test will pass as long as the sum of `output_tokens` across + all chunks is not `0`. .. code-block:: python @@ -1258,8 +1257,8 @@ class ChatModelIntegrationTests(ChatModelTests): ] ) - Check also that the aggregated response includes a ``'model_name'`` key - in its ``usage_metadata``. + Check also that the aggregated response includes a `model_name` key + in its `usage_metadata`. """ if not self.returns_usage_metadata: @@ -1326,19 +1325,19 @@ class ChatModelIntegrationTests(ChatModelTests): ) def test_stop_sequence(self, model: BaseChatModel) -> None: - """Test that model does not fail when invoked with the ``stop`` parameter. + """Test that model does not fail when invoked with the `stop` parameter. - The ``stop`` parameter is a standard parameter for stopping generation at a + The `stop` parameter is a standard parameter for stopping generation at a certain token. - `More on standard parameters `__ + [More on standard parameters](https://python.langchain.com/docs/concepts/chat_models/#standard-parameters). This should pass for all integrations. ??? note "Troubleshooting" - If this test fails, check that the function signature for ``_generate`` - (as well as ``_stream`` and async variants) accepts the ``stop`` parameter: + If this test fails, check that the function signature for `_generate` + (as well as `_stream` and async variants) accepts the `stop` parameter: .. code-block:: python @@ -1366,15 +1365,15 @@ class ChatModelIntegrationTests(ChatModelTests): def test_tool_calling(self, model: BaseChatModel) -> None: """Test that the model generates tool calls. - This test is skipped if the ``has_tool_calling`` property on the test class is - set to False. + This test is skipped if the `has_tool_calling` property on the test class is + set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1386,14 +1385,14 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that ``bind_tools`` is implemented to correctly + If this test fails, check that `bind_tools` is implemented to correctly translate LangChain tool objects into the appropriate schema for your chat model. - This test may fail if the chat model does not support a ``tool_choice`` + This test may fail if the chat model does not support a `tool_choice` parameter. This parameter can be used to force a tool call. If - ``tool_choice`` is not supported and the model consistently fails this - test, you can ``xfail`` the test: + `tool_choice` is not supported and the model consistently fails this + test, you can `xfail` the test: .. code-block:: python @@ -1402,7 +1401,7 @@ class ChatModelIntegrationTests(ChatModelTests): super().test_tool_calling(model) Otherwise, in the case that only one tool is bound, ensure that - ``tool_choice`` supports the string ``'any'`` to force calling that tool. + `tool_choice` supports the string `'any'` to force calling that tool. """ if not self.has_tool_calling: @@ -1428,15 +1427,15 @@ class ChatModelIntegrationTests(ChatModelTests): async def test_tool_calling_async(self, model: BaseChatModel) -> None: """Test that the model generates tool calls. - This test is skipped if the ``has_tool_calling`` property on the test class is - set to False. + This test is skipped if the `has_tool_calling` property on the test class is + set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1448,14 +1447,14 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that ``bind_tools`` is implemented to correctly + If this test fails, check that `bind_tools` is implemented to correctly translate LangChain tool objects into the appropriate schema for your chat model. - This test may fail if the chat model does not support a ``tool_choice`` + This test may fail if the chat model does not support a `tool_choice` parameter. This parameter can be used to force a tool call. If - ``tool_choice`` is not supported and the model consistently fails this - test, you can ``xfail`` the test: + `tool_choice` is not supported and the model consistently fails this + test, you can `xfail` the test: .. code-block:: python @@ -1464,7 +1463,7 @@ class ChatModelIntegrationTests(ChatModelTests): await super().test_tool_calling_async(model) Otherwise, in the case that only one tool is bound, ensure that - ``tool_choice`` supports the string ``'any'`` to force calling that tool. + `tool_choice` supports the string `'any'` to force calling that tool. """ if not self.has_tool_calling: @@ -1491,15 +1490,15 @@ class ChatModelIntegrationTests(ChatModelTests): """Test bind runnables as tools. Test that the model generates tool calls for tools that are derived from - LangChain runnables. This test is skipped if the ``has_tool_calling`` property - on the test class is set to False. + LangChain runnables. This test is skipped if the `has_tool_calling` property + on the test class is set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1511,14 +1510,14 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that ``bind_tools`` is implemented to correctly + If this test fails, check that `bind_tools` is implemented to correctly translate LangChain tool objects into the appropriate schema for your chat model. - This test may fail if the chat model does not support a ``tool_choice`` + This test may fail if the chat model does not support a `tool_choice` parameter. This parameter can be used to force a tool call. If - ``tool_choice`` is not supported and the model consistently fails this - test, you can ``xfail`` the test: + `tool_choice` is not supported and the model consistently fails this + test, you can `xfail` the test: .. code-block:: python @@ -1526,7 +1525,7 @@ class ChatModelIntegrationTests(ChatModelTests): def test_bind_runnables_as_tools(self, model: BaseChatModel) -> None: super().test_bind_runnables_as_tools(model) - Otherwise, ensure that the ``tool_choice_value`` property is correctly + Otherwise, ensure that the `tool_choice_value` property is correctly specified on the test class. """ @@ -1569,7 +1568,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1584,13 +1583,13 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, check that: 1. The model can correctly handle message histories that include - ``AIMessage`` objects with ``""`` content. - 2. The ``tool_calls`` attribute on ``AIMessage`` objects is correctly + `AIMessage` objects with `""` content. + 2. The `tool_calls` attribute on `AIMessage` objects is correctly handled and passed to the model in an appropriate format. - 3. The model can correctly handle ``ToolMessage`` objects with string - content and arbitrary string values for ``tool_call_id``. + 3. The model can correctly handle `ToolMessage` objects with string + content and arbitrary string values for `tool_call_id`. - You can ``xfail`` the test if tool calling is implemented but this format + You can `xfail` the test if tool calling is implemented but this format is not supported. .. code-block:: python @@ -1641,7 +1640,7 @@ class ChatModelIntegrationTests(ChatModelTests): For instance with Anthropic format contents. - These message histories will include ``AIMessage`` objects with "tool use" and + These message histories will include `AIMessage` objects with "tool use" and content blocks, e.g., .. code-block:: python @@ -1661,7 +1660,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1676,13 +1675,13 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, check that: 1. The model can correctly handle message histories that include - ``AIMessage`` objects with list content. - 2. The ``tool_calls`` attribute on ``AIMessage`` objects is correctly + `AIMessage` objects with list content. + 2. The `tool_calls` attribute on `AIMessage` objects is correctly handled and passed to the model in an appropriate format. 3. The model can correctly handle ToolMessage objects with string content - and arbitrary string values for ``tool_call_id``. + and arbitrary string values for `tool_call_id`. - You can ``xfail`` the test if tool calling is implemented but this format + You can `xfail` the test if tool calling is implemented but this format is not supported. .. code-block:: python @@ -1731,18 +1730,18 @@ class ChatModelIntegrationTests(ChatModelTests): assert isinstance(result_list_content, AIMessage) def test_tool_choice(self, model: BaseChatModel) -> None: - """Test ``tool_choice`` parameter. + """Test `tool_choice` parameter. - Test that the model can force tool calling via the ``tool_choice`` - parameter. This test is skipped if the ``has_tool_choice`` property on the - test class is set to False. + Test that the model can force tool calling via the `tool_choice` + parameter. This test is skipped if the `has_tool_choice` property on the + test class is set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_choice`` to False in your + To disable tool calling tests, set `has_tool_choice` to False in your test class: .. code-block:: python @@ -1754,14 +1753,14 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check whether the ``test_tool_calling`` test is passing. + If this test fails, check whether the `test_tool_calling` test is passing. If it is not, refer to the troubleshooting steps in that test first. - If ``test_tool_calling`` is passing, check that the underlying model - supports forced tool calling. If it does, ``bind_tools`` should accept a - ``tool_choice`` parameter that can be used to force a tool call. + If `test_tool_calling` is passing, check that the underlying model + supports forced tool calling. If it does, `bind_tools` should accept a + `tool_choice` parameter that can be used to force a tool call. - It should accept (1) the string ``'any'`` to force calling the bound tool, + It should accept (1) the string `'any'` to force calling the bound tool, and (2) the string name of the tool to force calling that tool. """ @@ -1786,15 +1785,15 @@ class ChatModelIntegrationTests(ChatModelTests): def test_tool_calling_with_no_arguments(self, model: BaseChatModel) -> None: """Test that the model generates tool calls for tools with no arguments. - This test is skipped if the ``has_tool_calling`` property on the test class - is set to False. + This test is skipped if the `has_tool_calling` property on the test class + is set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1806,15 +1805,15 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that ``bind_tools`` is implemented to correctly + If this test fails, check that `bind_tools` is implemented to correctly translate LangChain tool objects into the appropriate schema for your chat model. It should correctly handle the case where a tool has no arguments. - This test may fail if the chat model does not support a ``tool_choice`` + This test may fail if the chat model does not support a `tool_choice` parameter. This parameter can be used to force a tool call. It may also fail if a provider does not support this form of tool. In these cases, - you can ``xfail`` the test: + you can `xfail` the test: .. code-block:: python @@ -1825,7 +1824,7 @@ class ChatModelIntegrationTests(ChatModelTests): super().test_tool_calling_with_no_arguments(model) Otherwise, in the case that only one tool is bound, ensure that - ``tool_choice`` supports the string ``'any'`` to force calling that tool. + `tool_choice` supports the string `'any'` to force calling that tool. """ if not self.has_tool_calling: @@ -1848,7 +1847,7 @@ class ChatModelIntegrationTests(ChatModelTests): def test_tool_message_error_status( self, model: BaseChatModel, my_adder_tool: BaseTool ) -> None: - """Test that ``ToolMessage`` with ``status="error"`` can be handled. + """Test that `ToolMessage` with `status="error"` can be handled. These messages may take the form: @@ -1861,7 +1860,7 @@ class ChatModelIntegrationTests(ChatModelTests): status="error", ) - If possible, the ``status`` field should be parsed and passed appropriately + If possible, the `status` field should be parsed and passed appropriately to the model. This test is optional and should be skipped if the model does not support @@ -1869,7 +1868,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1881,7 +1880,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that the ``status`` field on ``ToolMessage`` + If this test fails, check that the `status` field on `ToolMessage` objects is either ignored or passed to the model appropriately. """ @@ -1919,18 +1918,18 @@ class ChatModelIntegrationTests(ChatModelTests): These are represented as a sequence of messages of the following form: - - ``HumanMessage`` with string content; - - ``AIMessage`` with the ``tool_calls`` attribute populated; - - ``ToolMessage`` with string content; - - ``AIMessage`` with string content (an answer); - - ``HumanMessage`` with string content (a follow-up question). + - `HumanMessage` with string content; + - `AIMessage` with the `tool_calls` attribute populated; + - `ToolMessage` with string content; + - `AIMessage` with string content (an answer); + - `HumanMessage` with string content (a follow-up question). This test should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -1942,14 +1941,14 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - This test uses `a utility function `__ - in ``langchain_core`` to generate a sequence of messages representing + This test uses [a utility function](https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.tool_example_to_messages.html). + in `langchain_core` to generate a sequence of messages representing "few-shot" examples. If this test fails, check that the model can correctly handle this sequence of messages. - You can ``xfail`` the test if tool calling is implemented but this format + You can `xfail` the test if tool calling is implemented but this format is not supported. .. code-block:: python @@ -1992,7 +1991,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable structured output tests, set ``has_structured_output`` to False + To disable structured output tests, set `has_structured_output` to False in your test class: .. code-block:: python @@ -2002,19 +2001,19 @@ class ChatModelIntegrationTests(ChatModelTests): def has_structured_output(self) -> bool: return False - By default, ``has_structured_output`` is True if a model overrides the - ``with_structured_output`` or ``bind_tools`` methods. + By default, `has_structured_output` is True if a model overrides the + `with_structured_output` or `bind_tools` methods. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method + If this test fails, ensure that the model's `bind_tools` method properly handles both JSON Schema and Pydantic V2 models. - ``langchain_core`` implements `a utility function `__ + `langchain_core` implements a [utility function](https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html). that will accommodate most formats. - See `example implementation `__ - of ``with_structured_output``. + See [example implementation](https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output). + of `with_structured_output`. """ if not self.has_structured_output: @@ -2075,7 +2074,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable structured output tests, set ``has_structured_output`` to False + To disable structured output tests, set `has_structured_output` to False in your test class: .. code-block:: python @@ -2085,19 +2084,19 @@ class ChatModelIntegrationTests(ChatModelTests): def has_structured_output(self) -> bool: return False - By default, ``has_structured_output`` is True if a model overrides the - ``with_structured_output`` or ``bind_tools`` methods. + By default, `has_structured_output` is True if a model overrides the + `with_structured_output` or `bind_tools` methods. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method + If this test fails, ensure that the model's `bind_tools` method properly handles both JSON Schema and Pydantic V2 models. - ``langchain_core`` implements `a utility function `__ + `langchain_core` implements a [utility function](https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html). that will accommodate most formats. - See `example implementation `__ - of ``with_structured_output``. + See [example implementation](https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output). + of `with_structured_output`. """ if not self.has_structured_output: @@ -2148,16 +2147,16 @@ class ChatModelIntegrationTests(ChatModelTests): def test_structured_output_pydantic_2_v1(self, model: BaseChatModel) -> None: """Test structured output using pydantic.v1.BaseModel. - Verify we can generate structured output using ``pydantic.v1.BaseModel``. + Verify we can generate structured output using `pydantic.v1.BaseModel`. - ``pydantic.v1.BaseModel`` is available in the Pydantic 2 package. + `pydantic.v1.BaseModel` is available in the Pydantic 2 package. This test is optional and should be skipped if the model does not support structured output (see Configuration below). ??? note "Configuration" - To disable structured output tests, set ``has_structured_output`` to False + To disable structured output tests, set `has_structured_output` to False in your test class: .. code-block:: python @@ -2167,19 +2166,19 @@ class ChatModelIntegrationTests(ChatModelTests): def has_structured_output(self) -> bool: return False - By default, ``has_structured_output`` is True if a model overrides the - ``with_structured_output`` or ``bind_tools`` methods. + By default, `has_structured_output` is True if a model overrides the + `with_structured_output` or `bind_tools` methods. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method + If this test fails, ensure that the model's `bind_tools` method properly handles both JSON Schema and Pydantic V1 models. - ``langchain_core`` implements `a utility function `__ + `langchain_core` implements [a utility function](https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html). that will accommodate most formats. - See `example implementation `__ - of ``with_structured_output``. + See [example implementation](https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output). + of `with_structured_output`. """ if not self.has_structured_output: @@ -2223,7 +2222,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable structured output tests, set ``has_structured_output`` to False + To disable structured output tests, set `has_structured_output` to False in your test class: .. code-block:: python @@ -2233,19 +2232,19 @@ class ChatModelIntegrationTests(ChatModelTests): def has_structured_output(self) -> bool: return False - By default, ``has_structured_output`` is True if a model overrides the - ``with_structured_output`` or ``bind_tools`` methods. + By default, `has_structured_output` is True if a model overrides the + `with_structured_output` or `bind_tools` methods. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method + If this test fails, ensure that the model's `bind_tools` method properly handles Pydantic V2 models with optional parameters. - ``langchain_core`` implements `a utility function `__ + `langchain_core` implements [a utility function](https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html). that will accommodate most formats. - See `example implementation `__ - of ``with_structured_output``. + See [example implementation](https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output). + of `with_structured_output`. """ if not self.has_structured_output: @@ -2295,7 +2294,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable this test, set ``supports_json_mode`` to False in your + To disable this test, set `supports_json_mode` to False in your test class: .. code-block:: python @@ -2307,7 +2306,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - See example implementation of ``with_structured_output`` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output + See example implementation of `with_structured_output` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output """ if not self.supports_json_mode: @@ -2379,7 +2378,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable this test, set ``supports_pdf_inputs`` to False in your + To disable this test, set `supports_pdf_inputs` to False in your test class: .. code-block:: python @@ -2393,7 +2392,7 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, check that the model can correctly handle messages with pdf content blocks, including base64-encoded files. Otherwise, set - the ``supports_pdf_inputs`` property to False. + the `supports_pdf_inputs` property to False. """ if not self.supports_pdf_inputs: @@ -2465,7 +2464,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable this test, set ``supports_audio_inputs`` to False in your + To disable this test, set `supports_audio_inputs` to False in your test class: .. code-block:: python @@ -2479,7 +2478,7 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, check that the model can correctly handle messages with audio content blocks, specifically base64-encoded files. Otherwise, - set the ``supports_audio_inputs`` property to False. + set the `supports_audio_inputs` property to False. """ if not self.supports_audio_inputs: @@ -2548,7 +2547,7 @@ class ChatModelIntegrationTests(ChatModelTests): See https://python.langchain.com/docs/concepts/multimodality/ - If the property ``supports_image_urls`` is set to True, the test will also + If the property `supports_image_urls` is set to True, the test will also check that we can process content blocks of the form: .. code-block:: python @@ -2560,7 +2559,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable this test, set ``supports_image_inputs`` to False in your + To disable this test, set `supports_image_inputs` to False in your test class: .. code-block:: python @@ -2579,7 +2578,7 @@ class ChatModelIntegrationTests(ChatModelTests): If this test fails, check that the model can correctly handle messages with image content blocks, including base64-encoded images. Otherwise, set - the ``supports_image_inputs`` property to False. + the `supports_image_inputs` property to False. """ if not self.supports_image_inputs: @@ -2627,7 +2626,7 @@ class ChatModelIntegrationTests(ChatModelTests): _ = model.invoke([message]) def test_image_tool_message(self, model: BaseChatModel) -> None: - """Test that the model can process ToolMessages with image inputs. + """Test that the model can process `ToolMessage` objects with image inputs. This test should be skipped if the model does not support messages of the Chat Completions `image_url` format: @@ -2662,12 +2661,12 @@ class ChatModelIntegrationTests(ChatModelTests): name="random_image", ) - This test can be skipped by setting the ``supports_image_tool_message`` property + This test can be skipped by setting the `supports_image_tool_message` property to False (see Configuration below). ??? note "Configuration" - To disable this test, set ``supports_image_tool_message`` to False in your + To disable this test, set `supports_image_tool_message` to False in your test class: .. code-block:: python @@ -2680,8 +2679,8 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" If this test fails, check that the model can correctly handle messages - with image content blocks in ToolMessages, including base64-encoded - images. Otherwise, set the ``supports_image_tool_message`` property to + with image content blocks in `ToolMessage` objects, including base64-encoded + images. Otherwise, set the `supports_image_tool_message` property to False. """ @@ -2742,7 +2741,7 @@ class ChatModelIntegrationTests(ChatModelTests): _ = model.bind_tools([random_image]).invoke(messages) def test_pdf_tool_message(self, model: BaseChatModel) -> None: - """Test that the model can process ToolMessages with PDF inputs. + """Test that the model can process `ToolMessage` objects with PDF inputs. This test should be skipped if the model does not support messages of the LangChain `FileContentBlock` format: @@ -2761,12 +2760,12 @@ class ChatModelIntegrationTests(ChatModelTests): name="random_pdf", ) - This test can be skipped by setting the ``supports_pdf_tool_message`` property + This test can be skipped by setting the `supports_pdf_tool_message` property to False (see Configuration below). .. dropdown:: Configuration - To disable this test, set ``supports_pdf_tool_message`` to False in your + To disable this test, set `supports_pdf_tool_message` to False in your test class: .. code-block:: python @@ -2779,10 +2778,9 @@ class ChatModelIntegrationTests(ChatModelTests): .. dropdown:: Troubleshooting If this test fails, check that the model can correctly handle messages - with PDF content blocks in ToolMessages, specifically base64-encoded - PDFs. Otherwise, set the ``supports_pdf_tool_message`` property to - False. - + with PDF content blocks in `ToolMessage` objects, specifically + base64-encoded PDFs. Otherwise, set the `supports_pdf_tool_message` property + to False. """ if not self.supports_pdf_tool_message: pytest.skip("Model does not support PDF tool message.") @@ -2829,7 +2827,7 @@ class ChatModelIntegrationTests(ChatModelTests): def test_anthropic_inputs(self, model: BaseChatModel) -> None: """Test that model can process Anthropic-style message histories. - These message histories will include ``AIMessage`` objects with ``tool_use`` + These message histories will include `AIMessage` objects with `tool_use` content blocks, e.g., .. code-block:: python @@ -2846,7 +2844,7 @@ class ChatModelIntegrationTests(ChatModelTests): ] ) - as well as ``HumanMessage`` objects containing ``tool_result`` content blocks: + as well as `HumanMessage` objects containing `tool_result` content blocks: .. code-block:: python @@ -2873,7 +2871,7 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Configuration" - To disable this test, set ``supports_anthropic_inputs`` to False in your + To disable this test, set `supports_anthropic_inputs` to False in your test class: .. code-block:: python @@ -2889,13 +2887,13 @@ class ChatModelIntegrationTests(ChatModelTests): 1. The model can correctly handle message histories that include message objects with list content. - 2. The ``tool_calls`` attribute on AIMessage objects is correctly handled + 2. The `tool_calls` attribute on AIMessage objects is correctly handled and passed to the model in an appropriate format. - 3. ``HumanMessage``s with "tool_result" content blocks are correctly + 3. `HumanMessage`s with "tool_result" content blocks are correctly handled. Otherwise, if Anthropic tool call and result formats are not supported, - set the ``supports_anthropic_inputs`` property to False. + set the `supports_anthropic_inputs` property to False. """ if not self.supports_anthropic_inputs: @@ -2998,7 +2996,7 @@ class ChatModelIntegrationTests(ChatModelTests): assert isinstance(response, AIMessage) def test_message_with_name(self, model: BaseChatModel) -> None: - """Test that ``HumanMessage`` with values for the ``name`` field can be handled. + """Test that `HumanMessage` with values for the `name` field can be handled. These messages may take the form: @@ -3006,12 +3004,12 @@ class ChatModelIntegrationTests(ChatModelTests): HumanMessage("hello", name="example_user") - If possible, the ``name`` field should be parsed and passed appropriately + If possible, the `name` field should be parsed and passed appropriately to the model. Otherwise, it should be ignored. ??? note "Troubleshooting" - If this test fails, check that the ``name`` field on ``HumanMessage`` + If this test fails, check that the `name` field on `HumanMessage` objects is either ignored or passed to the model appropriately. """ @@ -3025,15 +3023,15 @@ class ChatModelIntegrationTests(ChatModelTests): def test_agent_loop(self, model: BaseChatModel) -> None: """Test that the model supports a simple ReAct agent loop. - This test is skipped if the ``has_tool_calling`` property on the test class is - set to False. + This test is skipped if the `has_tool_calling` property on the test class is + set to `False`. This test is optional and should be skipped if the model does not support tool calling (see Configuration below). ??? note "Configuration" - To disable tool calling tests, set ``has_tool_calling`` to False in your + To disable tool calling tests, set `has_tool_calling` to False in your test class: .. code-block:: python @@ -3045,15 +3043,15 @@ class ChatModelIntegrationTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that ``bind_tools`` is implemented to correctly + If this test fails, check that `bind_tools` is implemented to correctly translate LangChain tool objects into the appropriate schema for your chat model. Check also that all required information (e.g., tool calling identifiers) - from ``AIMessage`` objects is propagated correctly to model payloads. + from `AIMessage` objects is propagated correctly to model payloads. This test may fail if the chat model does not consistently generate tool - calls in response to an appropriate query. In these cases you can ``xfail`` + calls in response to an appropriate query. In these cases you can `xfail` the test: .. code-block:: python @@ -3098,13 +3096,13 @@ class ChatModelIntegrationTests(ChatModelTests): ) -> None: """Test that streaming does not introduce undue overhead. - See ``enable_vcr_tests`` dropdown `above ` + See `enable_vcr_tests` dropdown `above ` for more information. ??? note "Configuration" - This test can be enabled or disabled using the ``enable_vcr_tests`` - property. For example, to disable the test, set this property to ``False``: + This test can be enabled or disabled using the `enable_vcr_tests` + property. For example, to disable the test, set this property to `False`: .. code-block:: python @@ -3112,9 +3110,9 @@ class ChatModelIntegrationTests(ChatModelTests): def enable_vcr_tests(self) -> bool: return False - !!! important + !!! warning VCR will by default record authentication headers and other sensitive - information in cassettes. See ``enable_vcr_tests`` dropdown + information in cassettes. See `enable_vcr_tests` dropdown `above ` for how to configure what information is recorded in cassettes. @@ -3162,13 +3160,13 @@ class ChatModelIntegrationTests(ChatModelTests): Args: model: The chat model to test - tool_choice: Tool choice parameter to pass to ``bind_tools()`` + tool_choice: Tool choice parameter to pass to `bind_tools()` (provider-specific) force_tool_call: Whether to force a tool call - (use ``tool_choice=True`` if None) + (use `tool_choice=True` if None) Tests that Unicode characters in tool call arguments are preserved correctly, - not escaped as ``\\uXXXX`` sequences. + not escaped as `\\uXXXX` sequences. """ if not self.has_tool_calling: diff --git a/libs/standard-tests/langchain_tests/integration_tests/retrievers.py b/libs/standard-tests/langchain_tests/integration_tests/retrievers.py index 227daf6731b..7f0470b4c9d 100644 --- a/libs/standard-tests/langchain_tests/integration_tests/retrievers.py +++ b/libs/standard-tests/langchain_tests/integration_tests/retrievers.py @@ -15,7 +15,7 @@ class RetrieversIntegrationTests(BaseStandardTests): @property @abstractmethod def retriever_constructor(self) -> type[BaseRetriever]: - """A ``BaseRetriever`` subclass to be tested.""" + """A `BaseRetriever` subclass to be tested.""" ... @property @@ -26,13 +26,13 @@ class RetrieversIntegrationTests(BaseStandardTests): @property @abstractmethod def retriever_query_example(self) -> str: - """Returns a str representing the ``query`` of an example retriever call.""" + """Returns a str representing the `query` of an example retriever call.""" @property def num_results_arg_name(self) -> str: """Returns the name of the parameter for the number of results returned. - Usually something like ``k`` or ``top_k``. + Usually something like `k` or `top_k`. """ return "k" @@ -48,12 +48,12 @@ class RetrieversIntegrationTests(BaseStandardTests): Test that the retriever constructor accepts a parameter representing the number of documents to return. - By default, the parameter tested is named ``k``, but it can be overridden by - setting the ``num_results_arg_name`` property. + By default, the parameter tested is named `k`, but it can be overridden by + setting the `num_results_arg_name` property. !!! note If the retriever doesn't support configuring the number of results returned - via the constructor, this test can be skipped using a pytest ``xfail`` on + via the constructor, this test can be skipped using a pytest `xfail` on the test class: .. code-block:: python @@ -69,7 +69,7 @@ class RetrieversIntegrationTests(BaseStandardTests): If this test fails, the retriever constructor does not accept a number of results parameter, or the retriever does not return the correct number - of documents ( of the one set in ``num_results_arg_name``) when it is + of documents ( of the one set in `num_results_arg_name`) when it is set. For example, a retriever like @@ -99,17 +99,17 @@ class RetrieversIntegrationTests(BaseStandardTests): assert all(isinstance(doc, Document) for doc in result_1) def test_invoke_with_k_kwarg(self, retriever: BaseRetriever) -> None: - """Test the number of results parameter in ``invoke()``. + """Test the number of results parameter in `invoke`. Test that the invoke method accepts a parameter representing the number of documents to return. - By default, the parameter is named ``, but it can be overridden by - setting the ``num_results_arg_name`` property. + By default, the parameter is named, but it can be overridden by + setting the `num_results_arg_name` property. !!! note If the retriever doesn't support configuring the number of results returned - via the invoke method, this test can be skipped using a pytest ``xfail`` on + via the invoke method, this test can be skipped using a pytest `xfail` on the test class: .. code-block:: python @@ -125,7 +125,7 @@ class RetrieversIntegrationTests(BaseStandardTests): If this test fails, the retriever's invoke method does not accept a number of results parameter, or the retriever does not return the correct number - of documents (``k`` of the one set in ``num_results_arg_name``) when it is + of documents (`k` of the one set in `num_results_arg_name`) when it is set. For example, a retriever like @@ -158,8 +158,8 @@ class RetrieversIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" If this test fails, the retriever's invoke method does not return a list of - ``langchain_core.document.Document`` objects. Please confirm that your - ``_get_relevant_documents`` method returns a list of ``Document`` objects. + `Document` objects. Please confirm that your + `_get_relevant_documents` method returns a list of `Document` objects. """ result = retriever.invoke(self.retriever_query_example) diff --git a/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py b/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py index 5c055a5eed5..21f634a7507 100644 --- a/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py +++ b/libs/standard-tests/langchain_tests/integration_tests/vectorstores.py @@ -24,7 +24,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): Implementers should subclass this test suite and provide a fixture that returns an empty vector store for each test. - The fixture should use the ``get_embeddings`` method to get a pre-defined + The fixture should use the `get_embeddings` method to get a pre-defined embeddings model that should be used for this test suite. Here is a template: @@ -52,8 +52,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): # cleanup operations, or deleting data pass - In the fixture, before the ``yield`` we instantiate an empty vector store. In the - ``finally`` block, we call whatever logic is necessary to bring the vector store + In the fixture, before the `yield` we instantiate an empty vector store. In the + `finally` block, we call whatever logic is necessary to bring the vector store to a clean state. Example: @@ -81,7 +81,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): pass Note that by default we enable both sync and async tests. To disable either, - override the ``has_sync`` or ``has_async`` properties to ``False`` in the + override the `has_sync` or `has_async` properties to `False` in the subclass. For example: .. code-block:: python @@ -129,7 +129,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): A pre-defined embeddings model that should be used for this test. - This currently uses ``DeterministicFakeEmbedding`` from ``langchain-core``, + This currently uses `DeterministicFakeEmbedding` from `langchain-core`, which uses numpy to generate random numbers based on a hash of the input text. The resulting embeddings are not meaningful, but they are deterministic. @@ -144,8 +144,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" If this test fails, check that the test class (i.e., sub class of - ``VectorStoreIntegrationTests``) initializes an empty vector store in the - ``vectorestore`` fixture. + `VectorStoreIntegrationTests`) initializes an empty vector store in the + `vectorestore` fixture. """ if not self.has_sync: pytest.skip("Sync tests not supported.") @@ -159,9 +159,9 @@ class VectorStoreIntegrationTests(BaseStandardTests): If this test fails, check that: - 1. We correctly initialize an empty vector store in the ``vectorestore`` + 1. We correctly initialize an empty vector store in the `vectorestore` fixture. - 2. Calling ``.similarity_search`` for the top ``k`` similar documents does + 2. Calling `.similarity_search` for the top `k` similar documents does not threshold by score. 3. We do not mutate the original document object when adding it to the vector store (e.g., by adding an ID). @@ -197,8 +197,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" If this test fails, check that the test class (i.e., sub class of - ``VectorStoreIntegrationTests``) correctly clears the vector store in the - ``finally`` block. + `VectorStoreIntegrationTests`) correctly clears the vector store in the + `finally` block. """ if not self.has_sync: pytest.skip("Sync tests not supported.") @@ -210,8 +210,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``add_documents`` preserves identifiers - passed in through ``ids``, and that ``delete`` correctly removes + If this test fails, check that `add_documents` preserves identifiers + passed in through `ids`, and that `delete` correctly removes documents. """ if not self.has_sync: @@ -232,7 +232,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``delete`` correctly removes multiple + If this test fails, check that `delete` correctly removes multiple documents when given a list of IDs. """ if not self.has_sync: @@ -254,7 +254,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``delete`` does not raise an exception + If this test fails, check that `delete` does not raise an exception when deleting IDs that do not exist. """ if not self.has_sync: @@ -294,7 +294,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that when ``add_documents`` is called with an + If this test fails, check that when `add_documents` is called with an ID that already exists in the vector store, the content is updated rather than duplicated. """ @@ -331,18 +331,18 @@ class VectorStoreIntegrationTests(BaseStandardTests): def test_get_by_ids(self, vectorstore: VectorStore) -> None: """Test get by IDs. - This test requires that ``get_by_ids`` be implemented on the vector store. + This test requires that `get_by_ids` be implemented on the vector store. ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -375,14 +375,14 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and does not + If this test fails, check that `get_by_ids` is implemented and does not raise an exception when given IDs that do not exist. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -406,17 +406,17 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. - Check also that ``add_documents`` will correctly generate string IDs if + Check also that `add_documents` will correctly generate string IDs if none are provided. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -448,21 +448,21 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. This test also verifies that: - 1. IDs specified in the ``Document.id`` field are assigned when adding + 1. IDs specified in the `Document.id` field are assigned when adding documents. 2. If some documents include IDs and others don't string IDs are generated for the latter. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -496,8 +496,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" If this test fails, check that the test class (i.e., sub class of - ``VectorStoreIntegrationTests``) initializes an empty vector store in the - ``vectorestore`` fixture. + `VectorStoreIntegrationTests`) initializes an empty vector store in the + `vectorestore` fixture. """ if not self.has_async: pytest.skip("Async tests not supported.") @@ -511,9 +511,9 @@ class VectorStoreIntegrationTests(BaseStandardTests): If this test fails, check that: - 1. We correctly initialize an empty vector store in the ``vectorestore`` + 1. We correctly initialize an empty vector store in the `vectorestore` fixture. - 2. Calling ``.asimilarity_search`` for the top ``k`` similar documents does + 2. Calling `.asimilarity_search` for the top `k` similar documents does not threshold by score. 3. We do not mutate the original document object when adding it to the vector store (e.g., by adding an ID). @@ -552,8 +552,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" If this test fails, check that the test class (i.e., sub class of - ``VectorStoreIntegrationTests``) correctly clears the vector store in the - ``finally`` block. + `VectorStoreIntegrationTests`) correctly clears the vector store in the + `finally` block. """ if not self.has_async: pytest.skip("Async tests not supported.") @@ -565,8 +565,8 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``aadd_documents`` preserves identifiers - passed in through ``ids``, and that ``delete`` correctly removes + If this test fails, check that `aadd_documents` preserves identifiers + passed in through `ids`, and that `delete` correctly removes documents. """ if not self.has_async: @@ -589,7 +589,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``adelete`` correctly removes multiple + If this test fails, check that `adelete` correctly removes multiple documents when given a list of IDs. """ if not self.has_async: @@ -611,7 +611,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``adelete`` does not raise an exception + If this test fails, check that `adelete` does not raise an exception when deleting IDs that do not exist. """ if not self.has_async: @@ -653,7 +653,7 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that when ``aadd_documents`` is called with an + If this test fails, check that when `aadd_documents` is called with an ID that already exists in the vector store, the content is updated rather than duplicated. """ @@ -690,18 +690,18 @@ class VectorStoreIntegrationTests(BaseStandardTests): async def test_get_by_ids_async(self, vectorstore: VectorStore) -> None: """Test get by IDs. - This test requires that ``get_by_ids`` be implemented on the vector store. + This test requires that `get_by_ids` be implemented on the vector store. ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -734,14 +734,14 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and does not + If this test fails, check that `get_by_ids` is implemented and does not raise an exception when given IDs that do not exist. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -766,17 +766,17 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. - Check also that ``aadd_documents`` will correctly generate string IDs if + Check also that `aadd_documents` will correctly generate string IDs if none are provided. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python @@ -810,21 +810,21 @@ class VectorStoreIntegrationTests(BaseStandardTests): ??? note "Troubleshooting" - If this test fails, check that ``get_by_ids`` is implemented and returns + If this test fails, check that `get_by_ids` is implemented and returns documents in the same order as the IDs passed in. This test also verifies that: - 1. IDs specified in the ``Document.id`` field are assigned when adding + 1. IDs specified in the `Document.id` field are assigned when adding documents. 2. If some documents include IDs and others don't string IDs are generated for the latter. !!! note - ``get_by_ids`` was added to the ``VectorStore`` interface in - ``langchain-core`` version 0.2.11. If difficult to implement, this - test can be skipped by setting the ``has_get_by_ids`` property to - ``False``. + `get_by_ids` was added to the `VectorStore` interface in + `langchain-core` version 0.2.11. If difficult to implement, this + test can be skipped by setting the `has_get_by_ids` property to + `False`. .. code-block:: python diff --git a/libs/standard-tests/langchain_tests/unit_tests/chat_models.py b/libs/standard-tests/langchain_tests/unit_tests/chat_models.py index 1ec97750078..9990e688d85 100644 --- a/libs/standard-tests/langchain_tests/unit_tests/chat_models.py +++ b/libs/standard-tests/langchain_tests/unit_tests/chat_models.py @@ -63,7 +63,7 @@ class ChatModelTests(BaseStandardTests): @property @abstractmethod def chat_model_class(self) -> type[BaseChatModel]: - """The chat model class to test, e.g., ``ChatParrotLink``.""" + """The chat model class to test, e.g., `ChatParrotLink`.""" ... @property @@ -149,7 +149,7 @@ class ChatModelTests(BaseStandardTests): """Supports image inputs. (bool) whether the chat model supports image inputs, defaults to - ``False``. + `False`. """ return False @@ -159,21 +159,21 @@ class ChatModelTests(BaseStandardTests): """Supports image inputs from URLs. (bool) whether the chat model supports image inputs from URLs, defaults to - ``False``. + `False`. """ return False @property def supports_pdf_inputs(self) -> bool: - """(bool) whether the chat model supports PDF inputs, defaults to ``False``.""" + """(bool) whether the chat model supports PDF inputs, defaults to `False`.""" return False @property def supports_audio_inputs(self) -> bool: """Supports audio inputs. - (bool) whether the chat model supports audio inputs, defaults to ``False``. + (bool) whether the chat model supports audio inputs, defaults to `False`. """ return False @@ -182,7 +182,7 @@ class ChatModelTests(BaseStandardTests): def supports_video_inputs(self) -> bool: """Supports video inputs. - (bool) whether the chat model supports video inputs, defaults to ``False``. + (bool) whether the chat model supports video inputs, defaults to `False`. No current tests are written for this feature. @@ -206,9 +206,9 @@ class ChatModelTests(BaseStandardTests): @property def supports_image_tool_message(self) -> bool: - """Supports image ToolMessages. + """Supports image `ToolMessage` objects. - (bool) whether the chat model supports ToolMessages that include image + (bool) whether the chat model supports `ToolMessage` objects that include image content. """ @@ -216,9 +216,9 @@ class ChatModelTests(BaseStandardTests): @property def supports_pdf_tool_message(self) -> bool: - """Supports PDF ToolMessages. + """Supports PDF `ToolMessage` objects. - (bool) whether the chat model supports ToolMessages that include PDF + (bool) whether the chat model supports `ToolMessage` objects that include PDF content. """ @@ -228,8 +228,8 @@ class ChatModelTests(BaseStandardTests): def enable_vcr_tests(self) -> bool: """(bool) whether to enable VCR tests for the chat model. - !!! important - See ``enable_vcr_tests`` dropdown `above ` for more + !!! warning + See `enable_vcr_tests` dropdown `above ` for more information. """ @@ -261,8 +261,8 @@ class ChatModelTests(BaseStandardTests): class ChatModelUnitTests(ChatModelTests): '''Base class for chat model unit tests. - Test subclasses must implement the ``chat_model_class`` and - ``chat_model_params`` properties to specify what model to test and its + Test subclasses must implement the `chat_model_class` and + `chat_model_params` properties to specify what model to test and its initialization parameters. Example: @@ -293,7 +293,7 @@ class ChatModelUnitTests(ChatModelTests): Test subclasses **must** implement the following two properties: chat_model_class - The chat model class to test, e.g., ``ChatParrotLink``. + The chat model class to test, e.g., `ChatParrotLink`. Example: @@ -322,7 +322,7 @@ class ChatModelUnitTests(ChatModelTests): Boolean property indicating whether the chat model supports tool calling. - By default, this is determined by whether the chat model's ``bind_tools`` method + By default, this is determined by whether the chat model's `bind_tools` method is overridden. It typically does not need to be overridden on the test class. Example override: @@ -340,9 +340,9 @@ class ChatModelUnitTests(ChatModelTests): !!! warning Deprecated since version 0.3.15. This property will be removed in version 0.3.20. If a model does not - support forcing tool calling, override the ``has_tool_choice`` property to - return ``False``. Otherwise, models should accept values of ``'any'`` or - the name of a tool in ``tool_choice``. + support forcing tool calling, override the `has_tool_choice` property to + return `False`. Otherwise, models should accept values of `'any'` or + the name of a tool in `tool_choice`. Example: @@ -355,13 +355,13 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`has_tool_choice`" Boolean property indicating whether the chat model supports forcing tool - calling via a ``tool_choice`` parameter. + calling via a `tool_choice` parameter. By default, this is determined by whether the parameter is included in the - signature for the corresponding ``bind_tools`` method. + signature for the corresponding `bind_tools` method. - If ``True``, the minimum requirement for this feature is that - ``tool_choice="any"`` will force a tool call, and ``tool_choice=`` + If `True`, the minimum requirement for this feature is that + `tool_choice="any"` will force a tool call, and `tool_choice=` will force a call to a specific tool. Example override: @@ -378,7 +378,7 @@ class ChatModelUnitTests(ChatModelTests): output. By default, this is determined by whether the chat model overrides the - ``with_structured_output`` or ``bind_tools`` methods. If the base + `with_structured_output` or `bind_tools` methods. If the base implementations are intended to be used, this method should be overridden. See: https://python.langchain.com/docs/concepts/structured_outputs/ @@ -394,7 +394,7 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`structured_output_kwargs`" Dict property that can be used to specify additional kwargs for - ``with_structured_output``. Useful for testing different models. + `with_structured_output`. Useful for testing different models. Example: @@ -407,7 +407,7 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_json_mode`" Boolean property indicating whether the chat model supports JSON mode in - ``with_structured_output``. + `with_structured_output`. See: https://python.langchain.com/docs/concepts/structured_outputs/#json-mode @@ -422,9 +422,9 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_image_inputs`" Boolean property indicating whether the chat model supports image inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested using the LangChain + If set to `True`, the chat model will be tested using the LangChain `ImageContentBlock` format: .. code-block:: python @@ -457,9 +457,9 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_image_urls`" Boolean property indicating whether the chat model supports image inputs from - URLs. Defaults to ``False``. + URLs. Defaults to `False`. - If set to ``True``, the chat model will be tested using content blocks of the + If set to `True`, the chat model will be tested using content blocks of the form. .. code-block:: python @@ -482,9 +482,9 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_pdf_inputs`" Boolean property indicating whether the chat model supports PDF inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested using the LangChain + If set to `True`, the chat model will be tested using the LangChain `FileContentBlock` format: .. code-block:: python @@ -508,9 +508,9 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_audio_inputs`" Boolean property indicating whether the chat model supports audio inputs. - Defaults to ``False``. + Defaults to `False`. - If set to ``True``, the chat model will be tested using the LangChain + If set to `True`, the chat model will be tested using the LangChain `AudioContentBlock` format: .. code-block:: python @@ -534,16 +534,16 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_video_inputs`" Boolean property indicating whether the chat model supports image inputs. - Defaults to ``False``. No current tests are written for this feature. + Defaults to `False`. No current tests are written for this feature. ??? note "`returns_usage_metadata`" Boolean property indicating whether the chat model returns usage metadata - on invoke and streaming responses. Defaults to ``True``. + on invoke and streaming responses. Defaults to `True`. - ``usage_metadata`` is an optional dict attribute on ``AIMessage``s that track + `usage_metadata` is an optional dict attribute on `AIMessage`s that track input and output tokens. - `See more. `__ + [See more](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.ai.UsageMetadata.html). Example: @@ -553,8 +553,8 @@ class ChatModelUnitTests(ChatModelTests): def returns_usage_metadata(self) -> bool: return False - Models supporting ``usage_metadata`` should also return the name of the - underlying model in the ``response_metadata`` of the ``AIMessage``. + Models supporting `usage_metadata` should also return the name of the + underlying model in the `response_metadata` of the `AIMessage`. ??? note "`supports_anthropic_inputs`" @@ -575,7 +575,7 @@ class ChatModelUnitTests(ChatModelTests): }, ] - If set to ``True``, the chat model will be tested using content blocks of this + If set to `True`, the chat model will be tested using content blocks of this form. Example: @@ -588,8 +588,8 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_image_tool_message`" - Boolean property indicating whether the chat model supports ``ToolMessage``s - that include image content, e.g., + Boolean property indicating whether the chat model supports `ToolMessage` + objects that include image content, e.g., .. code-block:: python @@ -623,8 +623,8 @@ class ChatModelUnitTests(ChatModelTests): (standard format). - If set to ``True``, the chat model will be tested with message sequences that - include ToolMessages of this form. + If set to `True`, the chat model will be tested with message sequences that + include `ToolMessage` objects of this form. Example: @@ -636,8 +636,8 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supports_pdf_tool_message`" - Boolean property indicating whether the chat model supports ToolMessages - that include PDF content, i.e., + Boolean property indicating whether the chat model supports `ToolMessage` + objects that include PDF content, i.e., .. code-block:: python @@ -655,8 +655,8 @@ class ChatModelUnitTests(ChatModelTests): using LangChain's `FileContentBlock` format. - If set to ``True``, the chat model will be tested with message sequences that - include ToolMessages of this form. + If set to `True`, the chat model will be tested with message sequences that + include `ToolMessage` objects of this form. Example: @@ -668,14 +668,14 @@ class ChatModelUnitTests(ChatModelTests): ??? note "`supported_usage_metadata_details`" - Property controlling what usage metadata details are emitted in both ``invoke`` - and ``stream``. + Property controlling what usage metadata details are emitted in both `invoke` + and `stream`. - ``usage_metadata`` is an optional dict attribute on ``AIMessage``s that track + `usage_metadata` is an optional dict attribute on `AIMessage`s that track input and output tokens. - `See more. `__ + [See more](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.ai.UsageMetadata.html). - It includes optional keys ``input_token_details`` and ``output_token_details`` + It includes optional keys `input_token_details` and `output_token_details` that can track usage details associated with special types of tokens, such as cached, audio, or reasoning. @@ -689,7 +689,7 @@ class ChatModelUnitTests(ChatModelTests): To enable these tests, follow these steps: - 1. Override the ``enable_vcr_tests`` property to return ``True``: + 1. Override the `enable_vcr_tests` property to return `True`: .. code-block:: python @@ -700,17 +700,17 @@ class ChatModelUnitTests(ChatModelTests): 2. Configure VCR to exclude sensitive headers and other information from cassettes. - !!! important + !!! warning VCR will by default record authentication headers and other sensitive information in cassettes. Read below for how to configure what information is recorded in cassettes. - To add configuration to VCR, add a ``conftest.py`` file to the ``tests/`` - directory and implement the ``vcr_config`` fixture there. + To add configuration to VCR, add a `conftest.py` file to the `tests/` + directory and implement the `vcr_config` fixture there. - ``langchain-tests`` excludes the headers ``'authorization'``, - ``'x-api-key'``, and ``'api-key'`` from VCR cassettes. To pick up this - configuration, you will need to add ``conftest.py`` as shown below. You can + `langchain-tests` excludes the headers `'authorization'`, + `'x-api-key'`, and `'api-key'` from VCR cassettes. To pick up this + configuration, you will need to add `conftest.py` as shown below. You can also exclude additional headers, override the default exclusions, or apply other customizations to the VCR configuration. See example below: @@ -745,8 +745,8 @@ class ChatModelUnitTests(ChatModelTests): ??? note "Compressing cassettes" - ``langchain-tests`` includes a custom VCR serializer that compresses - cassettes using gzip. To use it, register the ``yaml.gz`` serializer + `langchain-tests` includes a custom VCR serializer that compresses + cassettes using gzip. To use it, register the `yaml.gz` serializer to your VCR fixture and enable this serializer in the config. See example below: @@ -823,12 +823,12 @@ class ChatModelUnitTests(ChatModelTests): uv run python -m pytest tests/integration_tests/test_chat_models.py::TestMyModel::test_stream_time This will generate a VCR cassette for the test in - ``tests/integration_tests/cassettes/``. + `tests/integration_tests/cassettes/`. - !!! important + !!! warning You should inspect the generated cassette to ensure that it does not contain sensitive information. If it does, you can modify the - ``vcr_config`` fixture to exclude headers or modify the response + `vcr_config` fixture to exclude headers or modify the response before it is recorded. You can then commit the cassette to your repository. Subsequent test runs @@ -836,7 +836,7 @@ class ChatModelUnitTests(ChatModelTests): Testing initialization from environment variables Some unit tests may require testing initialization from environment variables. - These tests can be enabled by overriding the ``init_from_env_params`` + These tests can be enabled by overriding the `init_from_env_params` property (see below): ??? note "`init_from_env_params`" @@ -892,10 +892,10 @@ class ChatModelUnitTests(ChatModelTests): If this test fails, ensure that: - 1. ``chat_model_params`` is specified and the model can be initialized + 1. `chat_model_params` is specified and the model can be initialized from those params; 2. The model accommodates - `standard parameters `__ + [standard parameters](https://python.langchain.com/docs/concepts/chat_models/#standard-parameters). """ model = self.chat_model_class( @@ -909,12 +909,12 @@ class ChatModelUnitTests(ChatModelTests): def test_init_from_env(self) -> None: """Test initialization from environment variables. - Relies on the ``init_from_env_params`` property. Test is skipped if that + Relies on the `init_from_env_params` property. Test is skipped if that property is not set. ??? note "Troubleshooting" - If this test fails, ensure that ``init_from_env_params`` is specified + If this test fails, ensure that `init_from_env_params` is specified correctly and that model parameters are properly set from environment variables during initialization. @@ -935,14 +935,14 @@ class ChatModelUnitTests(ChatModelTests): def test_init_streaming( self, ) -> None: - """Test that model can be initialized with ``streaming=True``. + """Test that model can be initialized with `streaming=True`. This is for backward-compatibility purposes. ??? note "Troubleshooting" If this test fails, ensure that the model can be initialized with a - boolean ``streaming`` parameter. + boolean `streaming` parameter. """ model = self.chat_model_class( @@ -962,17 +962,16 @@ class ChatModelUnitTests(ChatModelTests): """Test bind tools with Pydantic models. Test that chat model correctly handles Pydantic models that are passed - into ``bind_tools``. Test is skipped if the ``has_tool_calling`` property + into `bind_tools`. Test is skipped if the `has_tool_calling` property on the test class is False. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method - properly handles Pydantic V2 models. ``langchain_core`` implements + If this test fails, ensure that the model's `bind_tools` method + properly handles Pydantic V2 models. `langchain_core` implements a utility function that will accommodate most formats: https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html - See example implementation of ``bind_tools`` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.bind_tools - + See example implementation of `bind_tools` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.bind_tools """ if not self.has_tool_calling: return @@ -1003,18 +1002,18 @@ class ChatModelUnitTests(ChatModelTests): model: BaseChatModel, schema: Any, ) -> None: - """Test ``with_structured_output`` method. + """Test `with_structured_output` method. - Test is skipped if the ``has_structured_output`` property on the test class is + Test is skipped if the `has_structured_output` property on the test class is False. ??? note "Troubleshooting" - If this test fails, ensure that the model's ``bind_tools`` method - properly handles Pydantic V2 models. ``langchain_core`` implements + If this test fails, ensure that the model's `bind_tools` method + properly handles Pydantic V2 models. `langchain_core` implements a utility function that will accommodate most formats: https://python.langchain.com/api_reference/core/utils/langchain_core.utils.function_calling.convert_to_openai_tool.html - See example implementation of ``with_structured_output`` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output + See example implementation of `with_structured_output` here: https://python.langchain.com/api_reference/_modules/langchain_openai/chat_models/base.html#BaseChatOpenAI.with_structured_output """ if not self.has_structured_output: @@ -1035,11 +1034,10 @@ class ChatModelUnitTests(ChatModelTests): ??? note "Troubleshooting" - If this test fails, check that the model accommodates `standard parameters `__. + If this test fails, check that the model accommodates [standard parameters](https://python.langchain.com/docs/concepts/chat_models/#standard-parameters). Check also that the model class is named according to convention - (e.g., ``ChatProviderName``). - + (e.g., `ChatProviderName`). """ class ExpectedParams(BaseModelV1): @@ -1071,14 +1069,13 @@ class ChatModelUnitTests(ChatModelTests): def test_serdes(self, model: BaseChatModel, snapshot: SnapshotAssertion) -> None: """Test serialization and deserialization of the model. - Test is skipped if the ``is_lc_serializable`` property on the chat model class - is not overwritten to return ``True``. + Test is skipped if the `is_lc_serializable` property on the chat model class + is not overwritten to return `True`. ??? note "Troubleshooting" - If this test fails, check that the ``init_from_env_params`` property is + If this test fails, check that the `init_from_env_params` property is correctly set on the test class. - """ if not self.chat_model_class.is_lc_serializable(): pytest.skip("Model is not serializable.") @@ -1100,7 +1097,6 @@ class ChatModelUnitTests(ChatModelTests): If this test fails, check that we are not introducing undue overhead in the model's initialization. - """ def _init_in_loop() -> None: diff --git a/libs/standard-tests/langchain_tests/unit_tests/embeddings.py b/libs/standard-tests/langchain_tests/unit_tests/embeddings.py index a58f32ea631..13d2c8ca0b9 100644 --- a/libs/standard-tests/langchain_tests/unit_tests/embeddings.py +++ b/libs/standard-tests/langchain_tests/unit_tests/embeddings.py @@ -62,7 +62,7 @@ class EmbeddingsUnitTests(EmbeddingsTests): API references for individual test methods include troubleshooting tips. Testing initialization from environment variables - Overriding the ``init_from_env_params`` property will enable additional tests + Overriding the `init_from_env_params` property will enable additional tests for initialization from environment variables. See below for details. ??? note "`init_from_env_params`" @@ -119,12 +119,12 @@ class EmbeddingsUnitTests(EmbeddingsTests): def test_init_from_env(self) -> None: """Test initialization from environment variables. - Relies on the ``init_from_env_params`` property. + Relies on the `init_from_env_params` property. Test is skipped if that property is not set. ??? note "Troubleshooting" - If this test fails, ensure that ``init_from_env_params`` is specified + If this test fails, ensure that `init_from_env_params` is specified correctly and that model parameters are properly set from environment variables during initialization. """ diff --git a/libs/standard-tests/uv.lock b/libs/standard-tests/uv.lock index 0f35664760e..b8a3d71d5a6 100644 --- a/libs/standard-tests/uv.lock +++ b/libs/standard-tests/uv.lock @@ -297,7 +297,7 @@ wheels = [ [[package]] name = "langchain-core" -version = "1.0.0a6" +version = "1.0.0a8" source = { editable = "../core" } dependencies = [ { name = "jsonpatch" }, diff --git a/libs/text-splitters/langchain_text_splitters/html.py b/libs/text-splitters/langchain_text_splitters/html.py index 3cb74a97872..8a9eccdaea7 100644 --- a/libs/text-splitters/langchain_text_splitters/html.py +++ b/libs/text-splitters/langchain_text_splitters/html.py @@ -158,9 +158,9 @@ class HTMLHeaderTextSplitter: boundaries. For example, [("h1", "Header 1"), ("h2", "Header 2")] will split content by

and

tags, assigning their textual content to the Document metadata. - return_each_element: If True, every HTML element encountered + return_each_element: If `True`, every HTML element encountered (including headers, paragraphs, etc.) is returned as a separate - Document. If False, content under the same header hierarchy is + Document. If `False`, content under the same header hierarchy is aggregated into fewer Documents. """ # Sort headers by their numeric level so that h1 < h2 < h3... diff --git a/libs/text-splitters/langchain_text_splitters/json.py b/libs/text-splitters/langchain_text_splitters/json.py index 14353d56d83..3a195e5fab3 100644 --- a/libs/text-splitters/langchain_text_splitters/json.py +++ b/libs/text-splitters/langchain_text_splitters/json.py @@ -35,7 +35,7 @@ class RecursiveJsonSplitter: Args: max_chunk_size: The maximum size for a chunk. Defaults to 2000. - min_chunk_size: The minimum size for a chunk. If None, + min_chunk_size: The minimum size for a chunk. If `None`, defaults to the maximum chunk size minus 200, with a lower bound of 50. """ super().__init__() diff --git a/libs/text-splitters/langchain_text_splitters/markdown.py b/libs/text-splitters/langchain_text_splitters/markdown.py index e0e4d55e1f8..c654e4ca098 100644 --- a/libs/text-splitters/langchain_text_splitters/markdown.py +++ b/libs/text-splitters/langchain_text_splitters/markdown.py @@ -340,13 +340,13 @@ class ExperimentalMarkdownSyntaxTextSplitter: Args: headers_to_split_on (Union[list[tuple[str, str]], None]): A list of tuples, where each tuple contains a header tag (e.g., "h1") - and its corresponding metadata key. If None, default headers are used. + and its corresponding metadata key. If `None`, default headers are used. return_each_line (bool): Whether to return each line as an individual chunk. - Defaults to False, which aggregates lines into larger chunks. + Defaults to `False`, which aggregates lines into larger chunks. strip_headers (bool): Whether to exclude headers from the resulting chunks. - Defaults to True. + Defaults to `True`. """ self.chunks: list[Document] = [] self.current_chunk = Document(page_content="")