From b6132fc23eef12389e5fa4af18615e6131a5b4b4 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 8 Oct 2025 23:28:43 -0400 Subject: [PATCH] style: remove more `Optional` syntax (#33371) --- .../integration_template/chat_models.py | 34 ++--- .../integration_template/tools.py | 8 +- .../integration_template/vectorstores.py | 21 ++- libs/core/langchain_core/callbacks/base.py | 83 ++++++----- libs/core/langchain_core/callbacks/manager.py | 133 +++++++----------- libs/core/langchain_core/callbacks/stdout.py | 12 +- .../langchain_core/language_models/_utils.py | 2 +- .../language_models/chat_models.py | 2 +- libs/core/langchain_core/runnables/base.py | 4 +- libs/core/langchain_core/runnables/config.py | 26 ++-- libs/core/langchain_core/runnables/history.py | 2 +- libs/core/langchain_core/runnables/utils.py | 6 +- libs/core/langchain_core/tools/base.py | 8 +- libs/core/langchain_core/tracers/context.py | 13 +- libs/core/langchain_core/tracers/schemas.py | 2 - .../langchain_core/utils/function_calling.py | 6 +- libs/core/langchain_core/vectorstores/base.py | 13 +- .../unit_tests/utils/test_function_calling.py | 4 +- .../core/tests/unit_tests/utils/test_utils.py | 2 +- .../langchain_classic/agents/agent.py | 2 +- .../agents/agent_iterator.py | 23 ++- .../chains/openai_functions/base.py | 6 +- .../chains/structured_output/base.py | 12 +- .../agents/trajectory_eval_chain.py | 10 +- .../evaluation/embedding_distance/base.py | 5 +- .../evaluation/qa/eval_chain.py | 4 +- .../langchain_classic/evaluation/schema.py | 40 +++--- .../evaluation/string_distance/base.py | 14 +- .../langchain_classic/model_laboratory.py | 6 +- .../smith/evaluation/config.py | 20 +-- .../langchain_classic/storage/file_system.py | 2 +- .../unit_tests/agents/test_responses_spec.py | 6 +- .../agents/test_return_direct_spec.py | 4 +- .../langchain_anthropic/chat_models.py | 12 +- .../chroma/langchain_chroma/vectorstores.py | 49 +++---- .../langchain_deepseek/chat_models.py | 10 +- .../langchain_fireworks/chat_models.py | 6 +- .../groq/langchain_groq/chat_models.py | 24 ++-- .../chat_models/huggingface.py | 8 +- .../langchain_mistralai/chat_models.py | 6 +- .../langchain_mistralai/embeddings.py | 2 +- .../ollama/langchain_ollama/chat_models.py | 12 +- .../ollama/langchain_ollama/embeddings.py | 2 +- libs/partners/ollama/langchain_ollama/llms.py | 16 +-- .../langchain_openai/chat_models/azure.py | 22 +-- .../langchain_openai/embeddings/azure.py | 6 +- .../langchain_openai/embeddings/base.py | 12 +- .../openai/langchain_openai/llms/base.py | 22 +-- .../langchain_perplexity/chat_models.py | 8 +- .../qdrant/langchain_qdrant/vectorstores.py | 8 +- .../partners/xai/langchain_xai/chat_models.py | 10 +- .../integration_tests/chat_models.py | 6 +- .../langchain_tests/unit_tests/chat_models.py | 2 +- .../langchain_text_splitters/html.py | 4 +- 54 files changed, 360 insertions(+), 422 deletions(-) diff --git a/libs/cli/langchain_cli/integration_template/integration_template/chat_models.py b/libs/cli/langchain_cli/integration_template/integration_template/chat_models.py index 51a1a405cfe..830fe9b54a7 100644 --- a/libs/cli/langchain_cli/integration_template/integration_template/chat_models.py +++ b/libs/cli/langchain_cli/integration_template/integration_template/chat_models.py @@ -1,6 +1,6 @@ """__ModuleName__ chat models.""" -from typing import Any, Dict, Iterator, List, Optional +from typing import Any, Dict, Iterator, List from langchain_core.callbacks import ( CallbackManagerForLLMRun, @@ -40,16 +40,16 @@ class Chat__ModuleName__(BaseChatModel): Name of __ModuleName__ model to use. temperature: float Sampling temperature. - max_tokens: Optional[int] + max_tokens: int | None Max number of tokens to generate. # TODO: Populate with relevant params. Key init args — client params: - timeout: Optional[float] + timeout: float | None Timeout for requests. max_retries: int Max number of retries. - api_key: Optional[str] + api_key: str | None __ModuleName__ API key. If not passed in will be read from env var __MODULE_NAME___API_KEY. @@ -162,7 +162,7 @@ class Chat__ModuleName__(BaseChatModel): setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10") + rating: int | None = Field(description="How funny the joke is, from 1 to 10") structured_llm = llm.with_structured_output(Joke) structured_llm.invoke("Tell me a joke about cats") @@ -273,10 +273,10 @@ class Chat__ModuleName__(BaseChatModel): """The name of the model""" parrot_buffer_length: int """The number of characters from the last message of the prompt to be echoed.""" - temperature: Optional[float] = None - max_tokens: Optional[int] = None - timeout: Optional[int] = None - stop: Optional[List[str]] = None + temperature: float | None = None + max_tokens: int | None = None + timeout: int | None = None + stop: list[str] | None = None max_retries: int = 2 @property @@ -302,8 +302,8 @@ class Chat__ModuleName__(BaseChatModel): def _generate( self, messages: List[BaseMessage], - stop: Optional[List[str]] = None, - run_manager: Optional[CallbackManagerForLLMRun] = None, + stop: list[str] | None = None, + run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> ChatResult: """Override the _generate method to implement the chat model logic. @@ -348,8 +348,8 @@ class Chat__ModuleName__(BaseChatModel): def _stream( self, messages: List[BaseMessage], - stop: Optional[List[str]] = None, - run_manager: Optional[CallbackManagerForLLMRun] = None, + stop: list[str] | None = None, + run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> Iterator[ChatGenerationChunk]: """Stream the output of the model. @@ -410,8 +410,8 @@ class Chat__ModuleName__(BaseChatModel): # async def _astream( # self, # messages: List[BaseMessage], - # stop: Optional[List[str]] = None, - # run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + # stop: list[str] | None = None, + # run_manager: AsyncCallbackManagerForLLMRun | None = None, # **kwargs: Any, # ) -> AsyncIterator[ChatGenerationChunk]: @@ -419,7 +419,7 @@ class Chat__ModuleName__(BaseChatModel): # async def _agenerate( # self, # messages: List[BaseMessage], - # stop: Optional[List[str]] = None, - # run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + # stop: list[str] | None = None, + # run_manager: AsyncCallbackManagerForLLMRun | None = None, # **kwargs: Any, # ) -> ChatResult: diff --git a/libs/cli/langchain_cli/integration_template/integration_template/tools.py b/libs/cli/langchain_cli/integration_template/integration_template/tools.py index 15047236714..fe8281187e8 100644 --- a/libs/cli/langchain_cli/integration_template/integration_template/tools.py +++ b/libs/cli/langchain_cli/integration_template/integration_template/tools.py @@ -1,6 +1,6 @@ """__ModuleName__ tools.""" -from typing import Optional, Type +from typing import Type from langchain_core.callbacks import ( CallbackManagerForToolRun, @@ -74,12 +74,12 @@ class __ModuleName__Tool(BaseTool): # type: ignore[override] """The schema that is passed to the model when performing tool calling.""" # TODO: Add any other init params for the tool. - # param1: Optional[str] + # param1: str | None # """param1 determines foobar""" # TODO: Replaced (a, b) with real tool arguments. def _run( - self, a: int, b: int, *, run_manager: Optional[CallbackManagerForToolRun] = None + self, a: int, b: int, *, run_manager: CallbackManagerForToolRun | None = None ) -> str: return str(a + b + 80) @@ -90,6 +90,6 @@ class __ModuleName__Tool(BaseTool): # type: ignore[override] # a: int, # b: int, # *, - # run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + # run_manager: AsyncCallbackManagerForToolRun | None = None, # ) -> str: # ... diff --git a/libs/cli/langchain_cli/integration_template/integration_template/vectorstores.py b/libs/cli/langchain_cli/integration_template/integration_template/vectorstores.py index cef35ecaf44..bc88dd8e3b8 100644 --- a/libs/cli/langchain_cli/integration_template/integration_template/vectorstores.py +++ b/libs/cli/langchain_cli/integration_template/integration_template/vectorstores.py @@ -8,7 +8,6 @@ from typing import ( Callable, Iterator, List, - Optional, Sequence, Tuple, Type, @@ -45,9 +44,9 @@ class __ModuleName__VectorStore(VectorStore): # TODO: Populate with relevant params. Key init args — client params: - client: Optional[Client] + client: Client | None Client to use. - connection_args: Optional[dict] + connection_args: dict | None Connection arguments. # TODO: Replace with relevant init params. @@ -172,7 +171,7 @@ class __ModuleName__VectorStore(VectorStore): cls: Type[__ModuleName__VectorStore], texts: List[str], embedding: Embeddings, - metadatas: Optional[List[dict]] = None, + metadatas: list[dict] | None = None, **kwargs: Any, ) -> __ModuleName__VectorStore: store = cls( @@ -187,7 +186,7 @@ class __ModuleName__VectorStore(VectorStore): # cls: Type[VST], # texts: List[str], # embedding: Embeddings, - # metadatas: Optional[List[dict]] = None, + # metadatas: list[dict] | None = None, # **kwargs: Any, # ) -> VST: # return await asyncio.get_running_loop().run_in_executor( @@ -201,7 +200,7 @@ class __ModuleName__VectorStore(VectorStore): def add_documents( self, documents: List[Document], - ids: Optional[List[str]] = None, + ids: list[str] | None = None, **kwargs: Any, ) -> List[str]: """Add documents to the store.""" @@ -215,7 +214,7 @@ class __ModuleName__VectorStore(VectorStore): ) raise ValueError(msg) - id_iterator: Iterator[Optional[str]] = ( + id_iterator: Iterator[str | None] = ( iter(ids) if ids else iter(doc.id for doc in documents) ) @@ -238,19 +237,19 @@ class __ModuleName__VectorStore(VectorStore): # async def aadd_documents( # self, # documents: List[Document], - # ids: Optional[List[str]] = None, + # ids: list[str] | None = None, # **kwargs: Any, # ) -> List[str]: # raise NotImplementedError - def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + def delete(self, ids: list[str] | None = None, **kwargs: Any) -> None: if ids: for _id in ids: self._database.pop(_id, None) # optional: add custom async implementations # async def adelete( - # self, ids: Optional[List[str]] = None, **kwargs: Any + # self, ids: list[str] | None = None, **kwargs: Any # ) -> None: # raise NotImplementedError @@ -287,7 +286,7 @@ class __ModuleName__VectorStore(VectorStore): self, embedding: List[float], k: int = 4, - filter: Optional[Callable[[Document], bool]] = None, + filter: Callable[[Document], bool] | None = None, **kwargs: Any, ) -> List[tuple[Document, float, List[float]]]: # get all docs with fixed order in list diff --git a/libs/core/langchain_core/callbacks/base.py b/libs/core/langchain_core/callbacks/base.py index 6d3cf7b9629..022c3d867ee 100644 --- a/libs/core/langchain_core/callbacks/base.py +++ b/libs/core/langchain_core/callbacks/base.py @@ -255,8 +255,8 @@ class CallbackManagerMixin: prompts (list[str]): The prompts. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -282,8 +282,8 @@ class CallbackManagerMixin: messages (list[list[BaseMessage]]): The messages. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ # NotImplementedError is thrown intentionally @@ -309,8 +309,8 @@ class CallbackManagerMixin: query (str): The query. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -332,8 +332,8 @@ class CallbackManagerMixin: inputs (dict[str, Any]): The inputs. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -356,9 +356,9 @@ class CallbackManagerMixin: input_str (str): The input string. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. - inputs (Optional[dict[str, Any]]): The inputs. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. + inputs (dict[str, Any] | None): The inputs. kwargs (Any): Additional keyword arguments. """ @@ -504,8 +504,8 @@ class AsyncCallbackHandler(BaseCallbackHandler): prompts (list[str]): The prompts. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -531,8 +531,8 @@ class AsyncCallbackHandler(BaseCallbackHandler): messages (list[list[BaseMessage]]): The messages. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ # NotImplementedError is thrown intentionally @@ -560,7 +560,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): containing content and other information. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -579,7 +579,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): response (LLMResult): The response which was generated. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -622,8 +622,8 @@ class AsyncCallbackHandler(BaseCallbackHandler): inputs (dict[str, Any]): The inputs. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -642,7 +642,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): outputs (dict[str, Any]): The outputs of the chain. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -661,7 +661,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): error (BaseException): The error that occurred. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -684,9 +684,9 @@ class AsyncCallbackHandler(BaseCallbackHandler): input_str (str): The input string. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. - inputs (Optional[dict[str, Any]]): The inputs. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. + inputs (dict[str, Any] | None): The inputs. kwargs (Any): Additional keyword arguments. """ @@ -705,7 +705,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): output (Any): The output of the tool. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -724,7 +724,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): error (BaseException): The error that occurred. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -743,7 +743,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): text (str): The text. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -779,7 +779,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): action (AgentAction): The agent action. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -798,7 +798,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): finish (AgentFinish): The agent finish. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -820,8 +820,8 @@ class AsyncCallbackHandler(BaseCallbackHandler): query (str): The query. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. - metadata (Optional[dict[str, Any]]): The metadata. + tags (list[str] | None): The tags. + metadata (dict[str, Any] | None): The metadata. kwargs (Any): Additional keyword arguments. """ @@ -840,7 +840,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): documents (Sequence[Document]): The documents retrieved. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -859,7 +859,7 @@ class AsyncCallbackHandler(BaseCallbackHandler): error (BaseException): The error that occurred. run_id (UUID): The run ID. This is the ID of the current run. parent_run_id (UUID): The parent run ID. This is the ID of the parent run. - tags (Optional[list[str]]): The tags. + tags (list[str] | None): The tags. kwargs (Any): Additional keyword arguments. """ @@ -906,16 +906,13 @@ class BaseCallbackManager(CallbackManagerMixin): """Initialize callback manager. Args: - handlers (list[BaseCallbackHandler]): The handlers. - inheritable_handlers (Optional[list[BaseCallbackHandler]]): - The inheritable handlers. Default is None. - parent_run_id (Optional[UUID]): The parent run ID. Default is None. - tags (Optional[list[str]]): The tags. Default is None. - inheritable_tags (Optional[list[str]]): The inheritable tags. - Default is None. - metadata (Optional[dict[str, Any]]): The metadata. Default is None. - inheritable_metadata (Optional[dict[str, Any]]): The inheritable metadata. - Default is None. + handlers: The handlers. + inheritable_handlers: The inheritable handlers. + parent_run_id: The parent run ID. + tags: The tags. + inheritable_tags: The inheritable tags. + metadata: The metadata. + inheritable_metadata: The inheritable metadata. """ self.handlers: list[BaseCallbackHandler] = handlers self.inheritable_handlers: list[BaseCallbackHandler] = ( diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.py index d2e4754b633..5deddddaccd 100644 --- a/libs/core/langchain_core/callbacks/manager.py +++ b/libs/core/langchain_core/callbacks/manager.py @@ -481,12 +481,12 @@ class BaseRunManager(RunManagerMixin): 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`. - inheritable_tags (Optional[list[str]]): The list of inheritable tags. + tags (list[str] | None): The list of tags. Defaults to `None`. + inheritable_tags (list[str] | None): The list of inheritable tags. Defaults to `None`. - metadata (Optional[dict[str, Any]]): The metadata. + metadata (dict[str, Any] | None): The metadata. Defaults to `None`. - inheritable_metadata (Optional[dict[str, Any]]): The inheritable metadata. + inheritable_metadata (dict[str, Any] | None): The inheritable metadata. Defaults to `None`. """ @@ -692,10 +692,9 @@ class CallbackManagerForLLMRun(RunManager, LLMManagerMixin): """Run when LLM generates a new token. Args: - token (str): The new token. - chunk (Optional[Union[GenerationChunk, ChatGenerationChunk]], optional): - The chunk. Defaults to `None`. - **kwargs (Any): Additional keyword arguments. + token: The new token. + chunk: The chunk. + **kwargs: Additional keyword arguments. """ if not self.handlers: @@ -791,10 +790,9 @@ class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin): """Run when LLM generates a new token. Args: - token (str): The new token. - chunk (Optional[Union[GenerationChunk, ChatGenerationChunk]], optional): - The chunk. Defaults to `None`. - **kwargs (Any): Additional keyword arguments. + token: The new token. + chunk: The chunk. + **kwargs: Additional keyword arguments. """ if not self.handlers: @@ -1433,7 +1431,7 @@ class CallbackManager(BaseCallbackManager): """Run when chain starts running. Args: - serialized (Optional[dict[str, Any]]): The serialized chain. + serialized (dict[str, Any] | None): 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`. **kwargs (Any): Additional keyword arguments. @@ -1537,7 +1535,7 @@ class CallbackManager(BaseCallbackManager): """Run when the retriever starts running. Args: - serialized (Optional[dict[str, Any]]): The serialized retriever. + serialized (dict[str, Any] | None): 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 @@ -1635,24 +1633,16 @@ class CallbackManager(BaseCallbackManager): """Configure the callback manager. Args: - inheritable_callbacks (Optional[Callbacks], optional): The inheritable - 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`. - inheritable_tags (Optional[list[str]], optional): The inheritable tags. - 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`. - local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to `None`. + inheritable_callbacks: The inheritable callbacks. + local_callbacks: The local callbacks. + verbose: Whether to enable verbose mode. + inheritable_tags: The inheritable tags. + local_tags: The local tags. + inheritable_metadata: The inheritable metadata. + local_metadata: The local metadata. Returns: CallbackManager: The configured callback manager. - """ return _configure( cls, @@ -1681,13 +1671,11 @@ class CallbackManagerForChainGroup(CallbackManager): """Initialize the callback manager. 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`. - parent_run_manager (CallbackManagerForChainRun): The parent run manager. - **kwargs (Any): Additional keyword arguments. + handlers: The list of handlers. + inheritable_handlers: The list of inheritable handlers. + parent_run_id: The ID of the parent run. + parent_run_manager: The parent run manager. + **kwargs: Additional keyword arguments. """ super().__init__( @@ -1984,7 +1972,7 @@ class AsyncCallbackManager(BaseCallbackManager): """Async run when chain starts running. Args: - serialized (Optional[dict[str, Any]]): The serialized chain. + serialized (dict[str, Any] | None): 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`. **kwargs (Any): Additional keyword arguments. @@ -2032,7 +2020,7 @@ class AsyncCallbackManager(BaseCallbackManager): """Run when the tool starts running. Args: - serialized (Optional[dict[str, Any]]): The serialized tool. + serialized (dict[str, Any] | None): The serialized tool. input_str (str): The input to the tool. run_id (UUID, optional): The ID of the run. Defaults to `None`. parent_run_id (UUID, optional): The ID of the parent run. @@ -2128,7 +2116,7 @@ class AsyncCallbackManager(BaseCallbackManager): """Run when the retriever starts running. Args: - serialized (Optional[dict[str, Any]]): The serialized retriever. + serialized (dict[str, Any] | None): 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 @@ -2180,20 +2168,13 @@ class AsyncCallbackManager(BaseCallbackManager): """Configure the async callback manager. Args: - inheritable_callbacks (Optional[Callbacks], optional): The inheritable - 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`. - inheritable_tags (Optional[list[str]], optional): The inheritable tags. - 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`. - local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to `None`. + inheritable_callbacks: The inheritable callbacks. + local_callbacks: The local callbacks. + verbose: Whether to enable verbose mode. + inheritable_tags: The inheritable tags. + local_tags: The local tags. + inheritable_metadata: The inheritable metadata. + local_metadata: The local metadata. Returns: AsyncCallbackManager: The configured async callback manager. @@ -2225,14 +2206,11 @@ class AsyncCallbackManagerForChainGroup(AsyncCallbackManager): """Initialize the async callback manager. 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`. - parent_run_manager (AsyncCallbackManagerForChainRun): - The parent run manager. - **kwargs (Any): Additional keyword arguments. + handlers: The list of handlers. + inheritable_handlers: The list of inheritable handlers. + parent_run_id: The ID of the parent run. + parent_run_manager: The parent run manager. + **kwargs: Additional keyword arguments. """ super().__init__( handlers, @@ -2364,19 +2342,14 @@ def _configure( """Configure the callback manager. Args: - callback_manager_cls (Type[T]): The callback manager class. - inheritable_callbacks (Optional[Callbacks], optional): The inheritable - 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`. - inheritable_tags (Optional[list[str]], optional): The inheritable tags. - 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`. - local_metadata (Optional[dict[str, Any]], optional): The local metadata. - Defaults to `None`. + callback_manager_cls: The callback manager class. + inheritable_callbacks: The inheritable callbacks. + local_callbacks: The local callbacks. + inheritable_tags: The inheritable tags. + local_tags: The local tags. + inheritable_metadata: The inheritable metadata. + local_metadata: The local metadata. + verbose: Whether to enable verbose mode. Raises: RuntimeError: If `LANGCHAIN_TRACING` is set but `LANGCHAIN_TRACING_V2` is not. @@ -2564,8 +2537,8 @@ async def adispatch_custom_event( data: Any, *, run_id: UUID, - tags: Optional[list[str]] = None, - metadata: Optional[dict[str, Any]] = None, + tags: list[str] | None = None, + metadata: dict[str, Any] | None = None, **kwargs: Any, ) -> None: print(f"Received custom event: {name} with data: {data}") @@ -2596,8 +2569,8 @@ async def adispatch_custom_event( data: Any, *, run_id: UUID, - tags: Optional[list[str]] = None, - metadata: Optional[dict[str, Any]] = None, + tags: list[str] | None = None, + metadata: dict[str, Any] | None = None, **kwargs: Any, ) -> None: print(f"Received custom event: {name} with data: {data}") @@ -2688,8 +2661,8 @@ def dispatch_custom_event( data: Any, *, run_id: UUID, - tags: Optional[list[str]] = None, - metadata: Optional[dict[str, Any]] = None, + tags: list[str] | None = None, + metadata: dict[str, Any] | None = None, **kwargs: Any, ) -> None: print(f"Received custom event: {name} with data: {data}") diff --git a/libs/core/langchain_core/callbacks/stdout.py b/libs/core/langchain_core/callbacks/stdout.py index c2b4b973ff5..30a5e2b1253 100644 --- a/libs/core/langchain_core/callbacks/stdout.py +++ b/libs/core/langchain_core/callbacks/stdout.py @@ -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 (str | None): 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`. - observation_prefix (Optional[str]): The observation prefix. + color (str | None): The color to use for the text. Defaults to `None`. + observation_prefix (str | None): The observation prefix. Defaults to `None`. - llm_prefix (Optional[str]): The LLM prefix. Defaults to `None`. + llm_prefix (str | None): 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 (str | None): 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 (str | None): 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/language_models/_utils.py b/libs/core/langchain_core/language_models/_utils.py index 8f66693a412..51ad689db20 100644 --- a/libs/core/langchain_core/language_models/_utils.py +++ b/libs/core/langchain_core/language_models/_utils.py @@ -222,7 +222,7 @@ def _normalize_messages( "type": Literal['file'], "file": Union[ { - "filename": Optional[str] = "$FILENAME", + "filename": str | None = "$FILENAME", "file_data": str = "$BASE64_ENCODED_FILE", }, { diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py index 6994fa41cc2..16ce918baa0 100644 --- a/libs/core/langchain_core/language_models/chat_models.py +++ b/libs/core/langchain_core/language_models/chat_models.py @@ -1563,7 +1563,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None Example: Pydantic schema (include_raw=False): .. code-block:: python diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py index bec65321aa7..d5a1efb14b4 100644 --- a/libs/core/langchain_core/runnables/base.py +++ b/libs/core/langchain_core/runnables/base.py @@ -1284,9 +1284,9 @@ class Runnable(ABC, Generic[Input, Output]): 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``: **list[str] | None** - The tags of the `Runnable` that generated the event. - - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the `Runnable` that + - ``metadata``: **dict[str, Any] | None** - The metadata of the `Runnable` that generated the event. - ``data``: **dict[str, Any]** diff --git a/libs/core/langchain_core/runnables/config.py b/libs/core/langchain_core/runnables/config.py index c14b114a5ad..646c68da701 100644 --- a/libs/core/langchain_core/runnables/config.py +++ b/libs/core/langchain_core/runnables/config.py @@ -193,8 +193,7 @@ def ensure_config(config: RunnableConfig | None = None) -> RunnableConfig: """Ensure that a config is a dict with all keys present. Args: - config (Optional[RunnableConfig], optional): The config to ensure. - Defaults to `None`. + config: The config to ensure. Defaults to `None`. Returns: RunnableConfig: The ensured config. @@ -251,9 +250,8 @@ def get_config_list( It is useful for subclasses overriding batch() or abatch(). Args: - config (Optional[Union[RunnableConfig, list[RunnableConfig]]]): - The config or list of configs. - length (int): The length of the list. + config: The config or list of configs. + length: The length of the list. Returns: list[RunnableConfig]: The list of configs. @@ -302,16 +300,12 @@ def patch_config( """Patch a config with new values. Args: - config (Optional[RunnableConfig]): The config to patch. - callbacks (Optional[BaseCallbackManager], optional): The callbacks to set. - Defaults to `None`. - recursion_limit (Optional[int], optional): The recursion limit to set. - 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`. - configurable (Optional[dict[str, Any]], optional): The configurable to set. - Defaults to `None`. + config: The config to patch. + callbacks: The callbacks to set. + recursion_limit: The recursion limit to set. + max_concurrency: The max concurrency to set. + run_name: The run name to set. + configurable: The configurable to set. Returns: RunnableConfig: The patched config. @@ -340,7 +334,7 @@ def merge_configs(*configs: RunnableConfig | None) -> RunnableConfig: """Merge multiple configs into one. Args: - *configs (Optional[RunnableConfig]): The configs to merge. + *configs: The configs to merge. Returns: RunnableConfig: The merged config. diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.py index 96e92e8a897..2a149531853 100644 --- a/libs/core/langchain_core/runnables/history.py +++ b/libs/core/langchain_core/runnables/history.py @@ -279,7 +279,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef] chat message history instance. ```python def get_session_history( - session_id: str, *, user_id: Optional[str] = None + session_id: str, *, user_id: str | None = None ) -> BaseChatMessageHistory: ... ``` diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.py index 017f4e1783a..9386db7190d 100644 --- a/libs/core/langchain_core/runnables/utils.py +++ b/libs/core/langchain_core/runnables/utils.py @@ -363,7 +363,7 @@ def get_function_first_arg_dict_keys(func: Callable) -> list[str] | None: func: The function to check. Returns: - Optional[list[str]]: The keys of the first argument if it is a dict, + list[str] | None: The keys of the first argument if it is a dict, None otherwise. """ try: @@ -525,7 +525,7 @@ def add(addables: Iterable[Addable]) -> Addable | None: addables: The addable objects to add. Returns: - Optional[Addable]: The result of adding the addable objects. + The result of adding the addable objects. """ final: Addable | None = None for chunk in addables: @@ -540,7 +540,7 @@ async def aadd(addables: AsyncIterable[Addable]) -> Addable | None: addables: The addable objects to add. Returns: - Optional[Addable]: The result of adding the addable objects. + The result of adding the addable objects. """ final: Addable | None = None async for chunk in addables: diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py index ebe370bc303..6825f816e1c 100644 --- a/libs/core/langchain_core/tools/base.py +++ b/libs/core/langchain_core/tools/base.py @@ -686,8 +686,8 @@ class ChildTool(BaseTool): def _run(self, *args: Any, **kwargs: Any) -> Any: """Use the tool. - Add run_manager: Optional[CallbackManagerForToolRun] = None - to child implementations to enable tracing. + Add `run_manager: CallbackManagerForToolRun | None = None` to child + implementations to enable tracing. Returns: The result of the tool execution. @@ -696,8 +696,8 @@ class ChildTool(BaseTool): async def _arun(self, *args: Any, **kwargs: Any) -> Any: """Use the tool asynchronously. - Add run_manager: Optional[AsyncCallbackManagerForToolRun] = None - to child implementations to enable tracing. + Add `run_manager: AsyncCallbackManagerForToolRun | None = None` to child + implementations to enable tracing. Returns: The result of the tool execution. diff --git a/libs/core/langchain_core/tracers/context.py b/libs/core/langchain_core/tracers/context.py index d09ba5f40e1..8a6953593f4 100644 --- a/libs/core/langchain_core/tracers/context.py +++ b/libs/core/langchain_core/tracers/context.py @@ -179,15 +179,14 @@ def register_configure_hook( """Register a configure hook. Args: - 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`. + context_var: The context variable. + inheritable: Whether the context variable is inheritable. + handle_class: The callback handler class. + env_var: The environment variable. Raises: - ValueError: If env_var is set, handle_class must also be set - to a non-None value. + ValueError: If env_var is set, handle_class must also be set to a non-None + value. """ if env_var is not None and handle_class is None: msg = "If env_var is set, handle_class must also be set to a non-None value." diff --git a/libs/core/langchain_core/tracers/schemas.py b/libs/core/langchain_core/tracers/schemas.py index 4ec415a5e34..03ecc39e741 100644 --- a/libs/core/langchain_core/tracers/schemas.py +++ b/libs/core/langchain_core/tracers/schemas.py @@ -88,8 +88,6 @@ class LLMRun(BaseRun): """Class for LLMRun.""" prompts: list[str] - # Temporarily, remove but we will completely remove LLMRun - # response: Optional[LLMResult] = None @deprecated("0.1.0", alternative="Run", removal="1.0") diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.py index 8c9edb57373..7c1f3a93cc2 100644 --- a/libs/core/langchain_core/utils/function_calling.py +++ b/libs/core/langchain_core/utils/function_calling.py @@ -683,11 +683,11 @@ def tool_example_to_messages( class Person(BaseModel): '''Information about a person.''' - name: Optional[str] = Field(..., description="The name of the person") - hair_color: Optional[str] = Field( + name: str | None = Field(..., description="The name of the person") + hair_color: str | None = Field( ..., description="The color of the person's hair if known" ) - height_in_meters: Optional[str] = Field( + height_in_meters: str | None = Field( ..., description="Height in METERS" ) diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.py index 3addb5d2322..540a0b2ea14 100644 --- a/libs/core/langchain_core/vectorstores/base.py +++ b/libs/core/langchain_core/vectorstores/base.py @@ -127,7 +127,7 @@ class VectorStore(ABC): **kwargs: Other keyword arguments that subclasses might use. Returns: - Optional[bool]: True if deletion is successful, + bool | None: True if deletion is successful, False otherwise, None if not implemented. """ msg = "delete method must be implemented by subclass." @@ -195,7 +195,7 @@ class VectorStore(ABC): **kwargs: Other keyword arguments that subclasses might use. Returns: - Optional[bool]: True if deletion is successful, + bool | None: True if deletion is successful, False otherwise, None if not implemented. """ return await run_in_executor(None, self.delete, ids, **kwargs) @@ -930,12 +930,11 @@ class VectorStore(ABC): Args: **kwargs: Keyword arguments to pass to the search function. Can include: - search_type (Optional[str]): Defines the type of search that - the Retriever should perform. - Can be "similarity" (default), "mmr", or + search_type: Defines the type of search that the Retriever should + perform. Can be "similarity" (default), "mmr", or "similarity_score_threshold". - search_kwargs (Optional[Dict]): Keyword arguments to pass to the - search function. Can include things like: + search_kwargs: Keyword arguments to pass to the search function. Can + include things like: k: Amount of documents to return (Default: 4) score_threshold: Minimum relevance threshold for similarity_score_threshold diff --git a/libs/core/tests/unit_tests/utils/test_function_calling.py b/libs/core/tests/unit_tests/utils/test_function_calling.py index 60747910589..6ee128a46ab 100644 --- a/libs/core/tests/unit_tests/utils/test_function_calling.py +++ b/libs/core/tests/unit_tests/utils/test_function_calling.py @@ -676,9 +676,7 @@ def test_convert_to_openai_function_no_description_no_params(func: dict) -> None assert actual == expected -@pytest.mark.xfail( - reason="Pydantic converts Optional[str] to str in .model_json_schema()" -) +@pytest.mark.xfail(reason="Pydantic converts str | None to str in .model_json_schema()") def test_function_optional_param() -> None: @tool def func5( diff --git a/libs/core/tests/unit_tests/utils/test_utils.py b/libs/core/tests/unit_tests/utils/test_utils.py index e01103688a8..8cc1c559ecc 100644 --- a/libs/core/tests/unit_tests/utils/test_utils.py +++ b/libs/core/tests/unit_tests/utils/test_utils.py @@ -362,7 +362,7 @@ def test_using_secret_from_env_as_default_factory( default_factory=secret_from_env("TEST_KEY_2", default="hello") ) - # We know it will be SecretStr rather than Optional[SecretStr] + # We know it will be SecretStr rather than SecretStr | None assert Buzz().secret.get_secret_value() == "hello" # type: ignore[union-attr] class OhMy(BaseModel): diff --git a/libs/langchain/langchain_classic/agents/agent.py b/libs/langchain/langchain_classic/agents/agent.py index 53091eb079c..00b674b5745 100644 --- a/libs/langchain/langchain_classic/agents/agent.py +++ b/libs/langchain/langchain_classic/agents/agent.py @@ -234,7 +234,7 @@ class BaseMultiActionAgent(BaseModel): """Get allowed tools. Returns: - Optional[List[str]]: Allowed tools. + list[str] | None: Allowed tools. """ return None diff --git a/libs/langchain/langchain_classic/agents/agent_iterator.py b/libs/langchain/langchain_classic/agents/agent_iterator.py index 75dc4b7cdc7..f9ed911c91e 100644 --- a/libs/langchain/langchain_classic/agents/agent_iterator.py +++ b/libs/langchain/langchain_classic/agents/agent_iterator.py @@ -59,20 +59,15 @@ class AgentExecutorIterator: inputs, and optional callbacks. Args: - 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`. - tags (Optional[list[str]], optional): The tags to use during iteration. - 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`. - include_run_info (bool, optional): Whether to include run info - in the output. Defaults to `False`. - yield_actions (bool, optional): Whether to yield actions as they - are generated. Defaults to `False`. + agent_executor: The `AgentExecutor` to iterate over. + inputs: The inputs to the `AgentExecutor`. + callbacks: The callbacks to use during iteration. + tags: The tags to use during iteration. + metadata: The metadata to use during iteration. + run_name: The name of the run. + run_id: The ID of the run. + include_run_info: Whether to include run info in the output. + yield_actions: Whether to yield actions as they are generated. """ self._agent_executor = agent_executor self.inputs = inputs diff --git a/libs/langchain/langchain_classic/chains/openai_functions/base.py b/libs/langchain/langchain_classic/chains/openai_functions/base.py index e4e1c992ba1..bda045a7931 100644 --- a/libs/langchain/langchain_classic/chains/openai_functions/base.py +++ b/libs/langchain/langchain_classic/chains/openai_functions/base.py @@ -97,7 +97,7 @@ def create_openai_fn_chain( name: str = Field(..., description="The person's name") age: int = Field(..., description="The person's age") - fav_food: Optional[str] = Field(None, description="The person's favorite food") + fav_food: str | None = Field(None, description="The person's favorite food") class RecordDog(BaseModel): @@ -105,7 +105,7 @@ def create_openai_fn_chain( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-4", temperature=0) @@ -190,7 +190,7 @@ def create_structured_output_chain( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0613", temperature=0) prompt = ChatPromptTemplate.from_messages( diff --git a/libs/langchain/langchain_classic/chains/structured_output/base.py b/libs/langchain/langchain_classic/chains/structured_output/base.py index 555ed69a75b..34ab4232084 100644 --- a/libs/langchain/langchain_classic/chains/structured_output/base.py +++ b/libs/langchain/langchain_classic/chains/structured_output/base.py @@ -117,7 +117,7 @@ def create_openai_fn_runnable( name: str = Field(..., description="The person's name") age: int = Field(..., description="The person's age") - fav_food: Optional[str] = Field(None, description="The person's favorite food") + fav_food: str | None = Field(None, description="The person's favorite food") class RecordDog(BaseModel): @@ -125,7 +125,7 @@ def create_openai_fn_runnable( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-4", temperature=0) @@ -249,7 +249,7 @@ def create_structured_output_runnable( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) prompt = ChatPromptTemplate.from_messages( @@ -329,7 +329,7 @@ def create_structured_output_runnable( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions") @@ -351,7 +351,7 @@ def create_structured_output_runnable( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions") @@ -377,7 +377,7 @@ def create_structured_output_runnable( name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") - fav_food: Optional[str] = Field(None, description="The dog's favorite food") + fav_food: str | None = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-json") diff --git a/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py b/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py index 49b144a36e2..412b3f37627 100644 --- a/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py +++ b/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py @@ -286,9 +286,8 @@ The following is the expected answer. Use this to measure correctness: """Run the chain and generate the output. Args: - inputs (Dict[str, str]): The input values for the chain. - run_manager (Optional[CallbackManagerForChainRun]): The callback - manager for the chain run. + inputs: The input values for the chain. + run_manager: The callback manager for the chain run. Returns: Dict[str, Any]: The output values of the chain. @@ -311,9 +310,8 @@ The following is the expected answer. Use this to measure correctness: """Run the chain and generate the output. Args: - inputs (Dict[str, str]): The input values for the chain. - run_manager (Optional[CallbackManagerForChainRun]): The callback - manager for the chain run. + inputs: The input values for the chain. + run_manager: The callback manager for the chain run. Returns: Dict[str, Any]: The output values of the chain. diff --git a/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py b/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py index 35f994a2afb..58b7f032ff2 100644 --- a/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py +++ b/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py @@ -389,9 +389,8 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator): """Compute the score for a prediction and reference. Args: - inputs (Dict[str, Any]): The input data. - run_manager (Optional[CallbackManagerForChainRun], optional): - The callback manager. + inputs: The input data. + run_manager: The callback manager. Returns: Dict[str, Any]: The computed score. diff --git a/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py b/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py index eaea6f41065..1a2d8a7681a 100644 --- a/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py +++ b/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py @@ -178,9 +178,9 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain): Args: prediction (str): the LLM or chain prediction to evaluate. - reference (Optional[str], optional): the reference label + reference (str | None, optional): the reference label to evaluate against. - input (Optional[str], optional): the input to consider during evaluation + input (str | None, optional): the input to consider during evaluation callbacks (Callbacks, optional): the callbacks to use for tracing. include_run_info (bool, optional): whether to include run info in the returned results. diff --git a/libs/langchain/langchain_classic/evaluation/schema.py b/libs/langchain/langchain_classic/evaluation/schema.py index 5e8139e5bc7..25d2b0b028f 100644 --- a/libs/langchain/langchain_classic/evaluation/schema.py +++ b/libs/langchain/langchain_classic/evaluation/schema.py @@ -114,8 +114,8 @@ class _EvalArgsMixin: """Check if the evaluation arguments are valid. Args: - reference (Optional[str], optional): The reference label. - input_ (Optional[str], optional): The input string. + reference (str | None, optional): The reference label. + input_ (str | None, optional): The input string. Raises: ValueError: If the evaluator requires an input string but none is provided, @@ -163,8 +163,8 @@ class StringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The LLM or chain prediction to evaluate. - reference (Optional[str], optional): The reference label to evaluate against. - input (Optional[str], optional): The input to consider during evaluation. + reference (str | None, optional): The reference label to evaluate against. + input (str | None, optional): The input to consider during evaluation. kwargs: Additional keyword arguments, including callbacks, tags, etc. Returns: @@ -173,7 +173,7 @@ class StringEvaluator(_EvalArgsMixin, ABC): - score: the score of the evaluation, if applicable. - value: the string value of the evaluation, if applicable. - reasoning: the reasoning for the evaluation, if applicable. - """ # noqa: E501 + """ async def _aevaluate_strings( self, @@ -187,8 +187,8 @@ class StringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The LLM or chain prediction to evaluate. - reference (Optional[str], optional): The reference label to evaluate against. - input (Optional[str], optional): The input to consider during evaluation. + reference (str | None, optional): The reference label to evaluate against. + input (str | None, optional): The input to consider during evaluation. kwargs: Additional keyword arguments, including callbacks, tags, etc. Returns: @@ -219,13 +219,13 @@ class StringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The LLM or chain prediction to evaluate. - reference (Optional[str], optional): The reference label to evaluate against. - input (Optional[str], optional): The input to consider during evaluation. + reference (str | None, optional): The reference label to evaluate against. + input (str | None, optional): The input to consider during evaluation. kwargs: Additional keyword arguments, including callbacks, tags, etc. Returns: dict: The evaluation results containing the score or value. - """ # noqa: E501 + """ self._check_evaluation_args(reference=reference, input_=input) return self._evaluate_strings( prediction=prediction, @@ -246,8 +246,8 @@ class StringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The LLM or chain prediction to evaluate. - reference (Optional[str], optional): The reference label to evaluate against. - input (Optional[str], optional): The input to consider during evaluation. + reference (str | None, optional): The reference label to evaluate against. + input (str | None, optional): The input to consider during evaluation. kwargs: Additional keyword arguments, including callbacks, tags, etc. Returns: @@ -280,8 +280,8 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The output string from the first model. prediction_b (str): The output string from the second model. - reference (Optional[str], optional): The expected output / reference string. - input (Optional[str], optional): The input string. + reference (str | None, optional): The expected output / reference string. + input (str | None, optional): The input string. kwargs: Additional keyword arguments, such as callbacks and optional reference strings. Returns: @@ -302,8 +302,8 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The output string from the first model. prediction_b (str): The output string from the second model. - reference (Optional[str], optional): The expected output / reference string. - input (Optional[str], optional): The input string. + reference (str | None, optional): The expected output / reference string. + input (str | None, optional): The input string. kwargs: Additional keyword arguments, such as callbacks and optional reference strings. Returns: @@ -333,8 +333,8 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The output string from the first model. prediction_b (str): The output string from the second model. - reference (Optional[str], optional): The expected output / reference string. - input (Optional[str], optional): The input string. + reference (str | None, optional): The expected output / reference string. + input (str | None, optional): The input string. kwargs: Additional keyword arguments, such as callbacks and optional reference strings. Returns: @@ -363,8 +363,8 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC): Args: prediction (str): The output string from the first model. prediction_b (str): The output string from the second model. - reference (Optional[str], optional): The expected output / reference string. - input (Optional[str], optional): The input string. + reference (str | None, optional): The expected output / reference string. + input (str | None, optional): The input string. kwargs: Additional keyword arguments, such as callbacks and optional reference strings. Returns: diff --git a/libs/langchain/langchain_classic/evaluation/string_distance/base.py b/libs/langchain/langchain_classic/evaluation/string_distance/base.py index acb8cc52ec2..24136e3be0d 100644 --- a/libs/langchain/langchain_classic/evaluation/string_distance/base.py +++ b/libs/langchain/langchain_classic/evaluation/string_distance/base.py @@ -221,12 +221,11 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin): """Compute the string distance between the prediction and the reference. Args: - inputs (Dict[str, Any]): The input values. - run_manager (Optional[CallbackManagerForChainRun]): - The callback manager. + inputs: The input values. + run_manager: The callback manager. Returns: - Dict[str, Any]: The evaluation results containing the score. + The evaluation results containing the score. """ return {"score": self.compute_metric(inputs["reference"], inputs["prediction"])} @@ -239,12 +238,11 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin): """Compute the string distance between the prediction and the reference. Args: - inputs (Dict[str, Any]): The input values. - run_manager (Optional[CallbackManagerForChainRun]): - The callback manager. + inputs: The input values. + run_manager: The callback manager. Returns: - Dict[str, Any]: The evaluation results containing the score. + The evaluation results containing the score. """ return {"score": self.compute_metric(inputs["reference"], inputs["prediction"])} diff --git a/libs/langchain/langchain_classic/model_laboratory.py b/libs/langchain/langchain_classic/model_laboratory.py index ae4494aefb0..81f903a51be 100644 --- a/libs/langchain/langchain_classic/model_laboratory.py +++ b/libs/langchain/langchain_classic/model_laboratory.py @@ -21,7 +21,7 @@ class ModelLaboratory: Args: chains: A sequence of chains to experiment with. Each chain must have exactly one input and one output variable. - names (Optional[List[str]]): Optional list of names corresponding to each + names (list[str] | None): Optional list of names corresponding to each chain. If provided, its length must match the number of chains. @@ -67,8 +67,8 @@ class ModelLaboratory: """Initialize the ModelLaboratory with LLMs and an optional prompt. Args: - llms (List[BaseLLM]): A list of LLMs to experiment with. - prompt (Optional[PromptTemplate]): An optional prompt to use with the LLMs. + llms: A list of LLMs to experiment with. + prompt: An optional prompt to use with the LLMs. If provided, the prompt must contain exactly one input variable. Returns: diff --git a/libs/langchain/langchain_classic/smith/evaluation/config.py b/libs/langchain/langchain_classic/smith/evaluation/config.py index d190d03299d..6f3063ce6f2 100644 --- a/libs/langchain/langchain_classic/smith/evaluation/config.py +++ b/libs/langchain/langchain_classic/smith/evaluation/config.py @@ -136,9 +136,9 @@ class RunEvalConfig(BaseModel): Parameters ---------- - criteria : Optional[CRITERIA_TYPE] + criteria : CRITERIA_TYPE | None The criteria to evaluate. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. """ @@ -152,9 +152,9 @@ class RunEvalConfig(BaseModel): Parameters ---------- - criteria : Optional[CRITERIA_TYPE] + criteria : CRITERIA_TYPE | None The criteria to evaluate. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. """ @@ -212,7 +212,7 @@ class RunEvalConfig(BaseModel): ---------- prompt : Optional[BasePromptTemplate] The prompt template to use for generating the question. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. """ @@ -227,7 +227,7 @@ class RunEvalConfig(BaseModel): ---------- prompt : Optional[BasePromptTemplate] The prompt template to use for generating the question. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. """ @@ -243,7 +243,7 @@ class RunEvalConfig(BaseModel): ---------- prompt : Optional[BasePromptTemplate] The prompt template to use for generating the question. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. """ @@ -311,11 +311,11 @@ class RunEvalConfig(BaseModel): Parameters ---------- - criteria : Optional[CRITERIA_TYPE] + criteria : CRITERIA_TYPE | None The criteria to evaluate. - llm : Optional[BaseLanguageModel] + llm : BaseLanguageModel | None The language model to use for the evaluation chain. - normalize_by: Optional[int] = None + normalize_by: int | None = None If you want to normalize the score, the denominator to use. If not provided, the score will be between 1 and 10 (by default). prompt : Optional[BasePromptTemplate] diff --git a/libs/langchain/langchain_classic/storage/file_system.py b/libs/langchain/langchain_classic/storage/file_system.py index 5618ff3cec1..66b6b97fcbc 100644 --- a/libs/langchain/langchain_classic/storage/file_system.py +++ b/libs/langchain/langchain_classic/storage/file_system.py @@ -163,7 +163,7 @@ class LocalFileStore(ByteStore): """Get an iterator over keys that match the given prefix. Args: - prefix (Optional[str]): The prefix to match. + prefix (str | None): The prefix to match. Returns: Iterator[str]: An iterator over keys that match the given prefix. diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py b/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py index 3a3fd76f54b..7d9d97ca64a 100644 --- a/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py +++ b/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py @@ -24,7 +24,7 @@ class AssertionByInvocation(BaseSchema): prompt: str tools_with_expected_calls: ToolCalls expected_last_message: str - expected_structured_response: Optional[Dict[str, Any]] + expected_structured_response: dict[str, Any] | None llm_request_count: int @@ -68,13 +68,13 @@ def test_responses_integration_matrix(case: TestCase) -> None: "currently failing due to undefined behavior when model cannot conform to any of the structured response formats." ) - def get_employee_role(*, name: str) -> Optional[str]: + def get_employee_role(*, name: str) -> str | None: for e in EMPLOYEES: if e.name == name: return e.role return None - def get_employee_department(*, name: str) -> Optional[str]: + def get_employee_department(*, name: str) -> str | None: for e in EMPLOYEES: if e.name == name: return e.department diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py b/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py index f52e1f01f64..4bdd2e8fd86 100644 --- a/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py +++ b/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py @@ -24,10 +24,10 @@ You are a strict polling bot. class TestCase(BaseSchema): name: str return_direct: bool - response_format: Optional[Dict[str, Any]] + response_format: dict[str, Any] | None expected_tool_calls: int expected_last_message: str - expected_structured_response: Optional[Dict[str, Any]] + expected_structured_response: dict[str, Any] | None TEST_CASES = load_spec("return_direct", as_model=TestCase) diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py index 99c91a0075f..62d29ac1cc7 100644 --- a/libs/partners/anthropic/langchain_anthropic/chat_models.py +++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py @@ -585,17 +585,17 @@ class ChatAnthropic(BaseChatModel): Max number of tokens to generate. Key init args — client params: - timeout: Optional[float] + timeout: float | None Timeout for requests. - anthropic_proxy: Optional[str] + anthropic_proxy: str | None Proxy to use for the Anthropic clients, will be used for every API call. If not passed in will be read from env var ``ANTHROPIC_PROXY``. max_retries: int Max number of retries if a request fails. - api_key: Optional[str] + api_key: str | None Anthropic API key. If not passed in will be read from env var ``ANTHROPIC_API_KEY``. - base_url: Optional[str] + base_url: str | None Base URL for API requests. Only specify if using a proxy or service emulator. @@ -788,7 +788,7 @@ class ChatAnthropic(BaseChatModel): setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10") + rating: int | None = Field(description="How funny the joke is, from 1 to 10") structured_llm = llm.with_structured_output(Joke) @@ -2210,7 +2210,7 @@ class ChatAnthropic(BaseChatModel): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None Example: Pydantic schema (include_raw=False): diff --git a/libs/partners/chroma/langchain_chroma/vectorstores.py b/libs/partners/chroma/langchain_chroma/vectorstores.py index 036d69aab50..da9d2de74a5 100644 --- a/libs/partners/chroma/langchain_chroma/vectorstores.py +++ b/libs/partners/chroma/langchain_chroma/vectorstores.py @@ -163,25 +163,25 @@ class Chroma(VectorStore): Embedding function to use. Key init args — client params: - client: Optional[Client] + client: Client | None Chroma client to use. - client_settings: Optional[chromadb.config.Settings] + client_settings: chromadb.config.Settings | None Chroma client settings. - persist_directory: Optional[str] + persist_directory: str | None Directory to persist the collection. - host: Optional[str] + host: str | None Hostname of a deployed Chroma server. - port: Optional[int] + port: int | None Connection port for a deployed Chroma server. Default is 8000. - ssl: Optional[bool] + ssl: bool | None Whether to establish an SSL connection with a deployed Chroma server. Default is False. - headers: Optional[dict[str, str]] + headers: dict[str, str] | None HTTP headers to send to a deployed Chroma server. - chroma_cloud_api_key: Optional[str] + chroma_cloud_api_key: str | None Chroma Cloud API key. - tenant: Optional[str] + tenant: str | None Tenant ID. Required for Chroma Cloud connections. Default is 'default_tenant' for local Chroma servers. - database: Optional[str] + database: str | None Database name. Required for Chroma Cloud connections. Default is 'default_database'. Instantiate: @@ -904,17 +904,16 @@ class Chroma(VectorStore): """Search for similar images based on the given image URI. Args: - uri (str): URI of the image to search for. - k (int, optional): Number of results to return. Defaults to ``DEFAULT_K``. - filter (Optional[Dict[str, str]], optional): Filter by metadata. - **kwargs (Any): Additional arguments to pass to function. + uri: URI of the image to search for. + k: Number of results to return. + filter: Filter by metadata. + **kwargs: Additional arguments to pass to function. Returns: - List of Images most similar to the provided image. - Each element in list is a LangChain Document Object. - The page content is b64 encoded image, metadata is default or - as defined by user. + List of Images most similar to the provided image. Each element in list is a + LangChain Document Object. The page content is b64 encoded image, metadata + is default or as defined by user. Raises: ValueError: If the embedding function does not support image embeddings. @@ -946,16 +945,14 @@ class Chroma(VectorStore): """Search for similar images based on the given image URI. Args: - uri (str): URI of the image to search for. - k (int, optional): Number of results to return. - Defaults to DEFAULT_K. - filter (Optional[Dict[str, str]], optional): Filter by metadata. - **kwargs (Any): Additional arguments to pass to function. + uri: URI of the image to search for. + k: Number of results to return. + filter: Filter by metadata. + **kwargs: Additional arguments to pass to function. Returns: - List[Tuple[Document, float]]: List of tuples containing documents similar - to the query image and their similarity scores. - 0th element in each tuple is a LangChain Document Object. + List of tuples containing documents similar to the query image and their + similarity scores. 0th element in each tuple is a LangChain Document Object. The page content is b64 encoded img, metadata is default or defined by user. Raises: diff --git a/libs/partners/deepseek/langchain_deepseek/chat_models.py b/libs/partners/deepseek/langchain_deepseek/chat_models.py index daa42659267..e4d1fb8cd97 100644 --- a/libs/partners/deepseek/langchain_deepseek/chat_models.py +++ b/libs/partners/deepseek/langchain_deepseek/chat_models.py @@ -42,15 +42,15 @@ class ChatDeepSeek(BaseChatOpenAI): Name of DeepSeek model to use, e.g. "deepseek-chat". temperature: float Sampling temperature. - max_tokens: Optional[int] + max_tokens: int | None Max number of tokens to generate. Key init args — client params: - timeout: Optional[float] + timeout: float | None Timeout for requests. max_retries: int Max number of retries. - api_key: Optional[str] + api_key: str | None DeepSeek API key. If not passed in will be read from env var DEEPSEEK_API_KEY. See full list of supported init args and their descriptions in the params section. @@ -141,7 +141,7 @@ class ChatDeepSeek(BaseChatOpenAI): setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10") + rating: int | None = Field(description="How funny the joke is, from 1 to 10") structured_llm = llm.with_structured_output(Joke) @@ -429,7 +429,7 @@ class ChatDeepSeek(BaseChatOpenAI): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None """ # noqa: E501 # Some applications require that incompatible parameters (e.g., unsupported diff --git a/libs/partners/fireworks/langchain_fireworks/chat_models.py b/libs/partners/fireworks/langchain_fireworks/chat_models.py index f63e0fe4741..a4636641d5c 100644 --- a/libs/partners/fireworks/langchain_fireworks/chat_models.py +++ b/libs/partners/fireworks/langchain_fireworks/chat_models.py @@ -726,7 +726,7 @@ class ChatFireworks(BaseChatModel): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None Example: schema=Pydantic class, method="function_calling", include_raw=False: @@ -745,7 +745,7 @@ class ChatFireworks(BaseChatModel): # If we provide default values and/or descriptions for fields, these will be passed # to the model. This is an important part of improving a model's ability to # correctly return structured outputs. - justification: Optional[str] = Field( + justification: str | None = Field( default=None, description="A justification for the answer." ) @@ -813,7 +813,7 @@ class ChatFireworks(BaseChatModel): answer: str justification: Annotated[ - Optional[str], None, "A justification for the answer." + str | None, None, "A justification for the answer." ] diff --git a/libs/partners/groq/langchain_groq/chat_models.py b/libs/partners/groq/langchain_groq/chat_models.py index 4567b41ebab..0b06c4d4006 100644 --- a/libs/partners/groq/langchain_groq/chat_models.py +++ b/libs/partners/groq/langchain_groq/chat_models.py @@ -83,9 +83,9 @@ class ChatGroq(BaseChatModel): Name of Groq model to use, e.g. ``llama-3.1-8b-instant``. temperature: float Sampling temperature. Ranges from ``0.0`` to ``1.0``. - max_tokens: Optional[int] + max_tokens: int | None Max number of tokens to generate. - reasoning_format: Optional[Literal["parsed", "raw", "hidden]] + reasoning_format: Literal["parsed", "raw", "hidden] | None The format for reasoning output. Groq will default to ``raw`` if left undefined. @@ -110,12 +110,12 @@ class ChatGroq(BaseChatModel): Timeout for requests. max_retries: int Max number of retries. - api_key: Optional[str] + api_key: str | None Groq API key. If not passed in will be read from env var ``GROQ_API_KEY``. - base_url: Optional[str] + base_url: str | None Base URL path for API requests, leave blank if not using a proxy or service emulator. - custom_get_token_ids: Optional[Callable[[str], List[int]]] + custom_get_token_ids: Callable[[str], list[int]] | None Optional encoder to use for counting tokens. See full list of supported init args and their descriptions in the params @@ -260,7 +260,7 @@ class ChatGroq(BaseChatModel): setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10") + rating: int | None = Field(description="How funny the joke is, from 1 to 10") structured_model = llm.with_structured_output(Joke) @@ -904,7 +904,7 @@ class ChatGroq(BaseChatModel): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None Example: schema=Pydantic class, method="function_calling", include_raw=False: @@ -923,9 +923,7 @@ class ChatGroq(BaseChatModel): # If we provide default values and/or descriptions for fields, these will be passed # to the model. This is an important part of improving a model's ability to # correctly return structured outputs. - justification: Optional[str] = Field( - default=None, description="A justification for the answer." - ) + justification: str | None = Field(default=None, description="A justification for the answer.") llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0) @@ -979,7 +977,7 @@ class ChatGroq(BaseChatModel): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Annotated[Optional[str], None, "A justification for the answer."] + justification: Annotated[str | None, None, "A justification for the answer."] llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0) @@ -1036,9 +1034,7 @@ class ChatGroq(BaseChatModel): # If we provide default values and/or descriptions for fields, these will be passed # to the model. This is an important part of improving a model's ability to # correctly return structured outputs. - justification: Optional[str] = Field( - default=None, description="A justification for the answer." - ) + justification: str | None = Field(default=None, description="A justification for the answer.") llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0) diff --git a/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py b/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py index 24048c245f3..2d6ff6b11c8 100644 --- a/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py +++ b/libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py @@ -334,11 +334,11 @@ class ChatHuggingFace(BaseChatModel): 'HuggingFacePipeline' LLM to be used. Key init args — client params: - custom_get_token_ids: Optional[Callable[[str], list[int]]] + custom_get_token_ids: Callable[[str], list[int]] | None Optional encoder to use for counting tokens. - metadata: Optional[dict[str, Any]] + metadata: dict[str, Any] | None Metadata to add to the run trace. - tags: Optional[list[str]] + tags: list[str] | None Tags to add to the run trace. tokenizer: Any verbose: bool @@ -918,7 +918,7 @@ class ChatHuggingFace(BaseChatModel): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None """ # noqa: E501 _ = kwargs.pop("strict", None) diff --git a/libs/partners/mistralai/langchain_mistralai/chat_models.py b/libs/partners/mistralai/langchain_mistralai/chat_models.py index ff46ad35c75..8b7f0c70962 100644 --- a/libs/partners/mistralai/langchain_mistralai/chat_models.py +++ b/libs/partners/mistralai/langchain_mistralai/chat_models.py @@ -805,7 +805,7 @@ class ChatMistralAI(BaseChatModel): If ``include_raw`` is True, then Runnable outputs a dict with keys: - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None Example: schema=Pydantic class, method="function_calling", include_raw=False: .. code-block:: python @@ -823,7 +823,7 @@ class ChatMistralAI(BaseChatModel): # If we provide default values and/or descriptions for fields, these will be passed # to the model. This is an important part of improving a model's ability to # correctly return structured outputs. - justification: Optional[str] = Field( + justification: str | None = Field( default=None, description="A justification for the answer." ) @@ -883,7 +883,7 @@ class ChatMistralAI(BaseChatModel): answer: str justification: Annotated[ - Optional[str], None, "A justification for the answer." + str | None, None, "A justification for the answer." ] diff --git a/libs/partners/mistralai/langchain_mistralai/embeddings.py b/libs/partners/mistralai/langchain_mistralai/embeddings.py index 77a5575a80d..4c41edba113 100644 --- a/libs/partners/mistralai/langchain_mistralai/embeddings.py +++ b/libs/partners/mistralai/langchain_mistralai/embeddings.py @@ -54,7 +54,7 @@ class MistralAIEmbeddings(BaseModel, Embeddings): Name of MistralAI model to use. Key init args — client params: - api_key: Optional[SecretStr] + api_key: SecretStr | None The API key for the MistralAI API. If not provided, it will be read from the environment variable ``MISTRAL_API_KEY``. max_retries: int diff --git a/libs/partners/ollama/langchain_ollama/chat_models.py b/libs/partners/ollama/langchain_ollama/chat_models.py index 358741cd8b9..a8618bb82b2 100644 --- a/libs/partners/ollama/langchain_ollama/chat_models.py +++ b/libs/partners/ollama/langchain_ollama/chat_models.py @@ -269,7 +269,7 @@ class ChatOllama(BaseChatModel): Key init args — completion params: model: str Name of Ollama model to use. - reasoning: Optional[bool] + reasoning: bool | None Controls the reasoning/thinking mode for `supported models `__. @@ -285,7 +285,7 @@ class ChatOllama(BaseChatModel): unless you set ``reasoning`` to `True`. temperature: float Sampling temperature. Ranges from ``0.0`` to ``1.0``. - num_predict: Optional[int] + num_predict: int | None Max number of tokens to generate. See full list of supported init args and their descriptions in the params section. @@ -1302,7 +1302,7 @@ class ChatOllama(BaseChatModel): - ``'raw'``: `BaseMessage` - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None !!! warning "Behavior changed in 0.2.2" Added support for structured output API via ``format`` parameter. @@ -1324,7 +1324,7 @@ class ChatOllama(BaseChatModel): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Optional[str] = Field( + justification: str | None = Field( default=..., description="A justification for the answer.", ) @@ -1382,7 +1382,7 @@ class ChatOllama(BaseChatModel): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Optional[str] = Field( + justification: str | None = Field( default=..., description="A justification for the answer.", ) @@ -1416,7 +1416,7 @@ class ChatOllama(BaseChatModel): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Annotated[Optional[str], None, "A justification for the answer."] + justification: Annotated[str | None, None, "A justification for the answer."] llm = ChatOllama(model="llama3.1", temperature=0) diff --git a/libs/partners/ollama/langchain_ollama/embeddings.py b/libs/partners/ollama/langchain_ollama/embeddings.py index e6e0a3dec4d..96c84b04b8a 100644 --- a/libs/partners/ollama/langchain_ollama/embeddings.py +++ b/libs/partners/ollama/langchain_ollama/embeddings.py @@ -66,7 +66,7 @@ class OllamaEmbeddings(BaseModel, Embeddings): Key init args — completion params: model: str Name of Ollama model to use. - base_url: Optional[str] + base_url: str | None Base url the model is hosted under. See full list of supported init args and their descriptions in the params section. diff --git a/libs/partners/ollama/langchain_ollama/llms.py b/libs/partners/ollama/langchain_ollama/llms.py index 69f16e4a357..e59d9fda1bd 100644 --- a/libs/partners/ollama/langchain_ollama/llms.py +++ b/libs/partners/ollama/langchain_ollama/llms.py @@ -39,23 +39,23 @@ class OllamaLLM(BaseLLM): Key init args — generation params: model: str Name of the Ollama model to use (e.g. ``'llama4'``). - temperature: Optional[float] + temperature: float | None Sampling temperature. Higher values make output more creative. - num_predict: Optional[int] + num_predict: int | None Maximum number of tokens to predict. - top_k: Optional[int] + top_k: int | None Limits the next token selection to the K most probable tokens. - top_p: Optional[float] + top_p: float | None Nucleus sampling parameter. Higher values lead to more diverse text. - mirostat: Optional[int] + mirostat: int | None Enable Mirostat sampling for controlling perplexity. - seed: Optional[int] + seed: int | None Random number seed for generation reproducibility. Key init args — client params: - base_url: Optional[str] + base_url: str | None Base URL where Ollama server is hosted. - keep_alive: Optional[Union[int, str]] + keep_alive: int | str | None How long the model stays loaded into memory. format: Literal["", "json"] Specify the format of the output. diff --git a/libs/partners/openai/langchain_openai/chat_models/azure.py b/libs/partners/openai/langchain_openai/chat_models/azure.py index 22dd4328c50..467d2caac7d 100644 --- a/libs/partners/openai/langchain_openai/chat_models/azure.py +++ b/libs/partners/openai/langchain_openai/chat_models/azure.py @@ -53,9 +53,9 @@ class AzureChatOpenAI(BaseChatOpenAI): Name of Azure OpenAI deployment to use. temperature: float Sampling temperature. - max_tokens: Optional[int] + max_tokens: int | None Max number of tokens to generate. - logprobs: Optional[bool] + logprobs: bool | None Whether to return logprobs. Key init args — client params: @@ -64,15 +64,15 @@ class AzureChatOpenAI(BaseChatOpenAI): underlying model). `See more on the different versions. `__ timeout: Union[float, Tuple[float, float], Any, None] Timeout for requests. - max_retries: Optional[int] + max_retries: int | None Max number of retries. - organization: Optional[str] + organization: str | None OpenAI organization ID. If not passed in will be read from env var ``OPENAI_ORG_ID``. - model: Optional[str] + model: str | None The name of the underlying OpenAI model. Used for tracing and token counting. Does not affect completion. E.g. ``'gpt-4'``, ``'gpt-35-turbo'``, etc. - model_version: Optional[str] + model_version: str | None The version of the underlying OpenAI model. Used for tracing and token counting. Does not affect completion. E.g., ``'0125'``, ``'0125-preview'``, etc. @@ -298,7 +298,7 @@ class AzureChatOpenAI(BaseChatOpenAI): setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field( + rating: int | None = Field( description="How funny the joke is, from 1 to 10" ) @@ -947,7 +947,7 @@ class AzureChatOpenAI(BaseChatOpenAI): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None !!! warning "Behavior changed in 0.1.20" Added support for TypedDict class ``schema``. @@ -986,7 +986,7 @@ class AzureChatOpenAI(BaseChatOpenAI): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Optional[str] = Field( + justification: str | None = Field( default=..., description="A justification for the answer." ) @@ -1019,7 +1019,7 @@ class AzureChatOpenAI(BaseChatOpenAI): '''An answer to the user question along with justification for the answer.''' answer: str - justification: Optional[str] = Field( + justification: str | None = Field( default=..., description="A justification for the answer." ) @@ -1085,7 +1085,7 @@ class AzureChatOpenAI(BaseChatOpenAI): answer: str justification: Annotated[ - Optional[str], None, "A justification for the answer." + str | None, None, "A justification for the answer." ] diff --git a/libs/partners/openai/langchain_openai/embeddings/azure.py b/libs/partners/openai/langchain_openai/embeddings/azure.py index c74d70fe8e6..e0a9cfc3a69 100644 --- a/libs/partners/openai/langchain_openai/embeddings/azure.py +++ b/libs/partners/openai/langchain_openai/embeddings/azure.py @@ -40,12 +40,12 @@ class AzureOpenAIEmbeddings(OpenAIEmbeddings): # type: ignore[override] Key init args — completion params: model: str Name of AzureOpenAI model to use. - dimensions: Optional[int] + dimensions: int | None Number of dimensions for the embeddings. Can be specified only if the underlying model supports it. Key init args — client params: - api_key: Optional[SecretStr] + api_key: SecretStr | None See full list of supported init args and their descriptions in the params section. @@ -56,7 +56,7 @@ class AzureOpenAIEmbeddings(OpenAIEmbeddings): # type: ignore[override] embeddings = AzureOpenAIEmbeddings( model="text-embedding-3-large" - # dimensions: Optional[int] = None, # Can specify dimensions with new text-embedding-3 models + # dimensions: int | None = None, # Can specify dimensions with new text-embedding-3 models # azure_endpoint="https://.openai.azure.com/", If not provided, will read env variable AZURE_OPENAI_ENDPOINT # api_key=... # Can provide an API key directly. If missing read env variable AZURE_OPENAI_API_KEY # openai_api_version=..., # If not provided, will read env variable AZURE_OPENAI_API_VERSION diff --git a/libs/partners/openai/langchain_openai/embeddings/base.py b/libs/partners/openai/langchain_openai/embeddings/base.py index 4c5e8ecfae3..4d7b46e4e9d 100644 --- a/libs/partners/openai/langchain_openai/embeddings/base.py +++ b/libs/partners/openai/langchain_openai/embeddings/base.py @@ -92,19 +92,19 @@ class OpenAIEmbeddings(BaseModel, Embeddings): Key init args — embedding params: model: str Name of OpenAI model to use. - dimensions: Optional[int] = None + dimensions: int | None = None The number of dimensions the resulting output embeddings should have. Only supported in ``'text-embedding-3'`` and later models. Key init args — client params: - api_key: Optional[SecretStr] = None + api_key: SecretStr | None = None OpenAI API key. - organization: Optional[str] = None + organization: str | None = None OpenAI organization ID. If not passed in will be read from env var ``OPENAI_ORG_ID``. max_retries: int = 2 Maximum number of retries to make when generating. - request_timeout: Optional[Union[float, Tuple[float, float], Any]] = None + request_timeout: float | Tuple[float, float] | Any | None = None Timeout for requests to OpenAI completion API See full list of supported init args and their descriptions in the params section. @@ -472,7 +472,7 @@ class OpenAIEmbeddings(BaseModel, Embeddings): Args: texts (List[str]): A list of texts to embed. engine (str): The engine or model to use for embeddings. - chunk_size (Optional[int]): The size of chunks for processing embeddings. + chunk_size (int | None): The size of chunks for processing embeddings. Returns: List[List[float]]: A list of embeddings for each input text. @@ -524,7 +524,7 @@ class OpenAIEmbeddings(BaseModel, Embeddings): Args: texts (List[str]): A list of texts to embed. engine (str): The engine or model to use for embeddings. - chunk_size (Optional[int]): The size of chunks for processing embeddings. + chunk_size (int | None): The size of chunks for processing embeddings. Returns: List[List[float]]: A list of embeddings for each input text. diff --git a/libs/partners/openai/langchain_openai/llms/base.py b/libs/partners/openai/langchain_openai/llms/base.py index 233afeddf71..271aea9ad4e 100644 --- a/libs/partners/openai/langchain_openai/llms/base.py +++ b/libs/partners/openai/langchain_openai/llms/base.py @@ -78,23 +78,23 @@ class BaseOpenAI(BaseLLM): How many completions to generate for each prompt. best_of: int Generates best_of completions server-side and returns the "best". - logit_bias: Optional[dict[str, float]] + logit_bias: dict[str, float] | None Adjust the probability of specific tokens being generated. - seed: Optional[int] + seed: int | None Seed for generation. - logprobs: Optional[int] + logprobs: int | None Include the log probabilities on the logprobs most likely output tokens. streaming: bool Whether to stream the results or not. Key init args — client params: - openai_api_key: Optional[SecretStr] + openai_api_key: SecretStr | None OpenAI API key. If not passed in will be read from env var ``OPENAI_API_KEY``. - openai_api_base: Optional[str] + openai_api_base: str | None Base URL path for API requests, leave blank if not using a proxy or service emulator. - openai_organization: Optional[str] + openai_organization: str | None OpenAI organization ID. If not passed in will be read from env var ``OPENAI_ORG_ID``. request_timeout: Union[float, tuple[float, float], Any, None] @@ -716,9 +716,9 @@ class OpenAI(BaseOpenAI): Name of OpenAI model to use. temperature: float Sampling temperature. - max_tokens: Optional[int] + max_tokens: int | None Max number of tokens to generate. - logprobs: Optional[bool] + logprobs: bool | None Whether to return logprobs. stream_options: Dict Configure streaming outputs, like whether to return token usage when @@ -729,12 +729,12 @@ class OpenAI(BaseOpenAI): Timeout for requests. max_retries: int Max number of retries. - api_key: Optional[str] + api_key: str | None OpenAI API key. If not passed in will be read from env var ``OPENAI_API_KEY``. - base_url: Optional[str] + base_url: str | None Base URL for API requests. Only specify if using a proxy or service emulator. - organization: Optional[str] + organization: str | None OpenAI organization ID. If not passed in will be read from env var ``OPENAI_ORG_ID``. diff --git a/libs/partners/perplexity/langchain_perplexity/chat_models.py b/libs/partners/perplexity/langchain_perplexity/chat_models.py index 2893f538ba7..541eedf6380 100644 --- a/libs/partners/perplexity/langchain_perplexity/chat_models.py +++ b/libs/partners/perplexity/langchain_perplexity/chat_models.py @@ -76,15 +76,15 @@ class ChatPerplexity(BaseChatModel): Name of the model to use. e.g. "sonar" temperature: float Sampling temperature to use. Default is 0.7 - max_tokens: Optional[int] + max_tokens: int | None Maximum number of tokens to generate. streaming: bool Whether to stream the results or not. Key init args - client params: - pplx_api_key: Optional[str] + pplx_api_key: str | None API key for PerplexityChat API. Default is None. - request_timeout: Optional[Union[float, Tuple[float, float]]] + request_timeout: float | Tuple[float, float] | None Timeout for requests to PerplexityChat completion API. Default is None. max_retries: int Maximum number of retries to make when generating. @@ -444,7 +444,7 @@ class ChatPerplexity(BaseChatModel): - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None """ # noqa: E501 if method in ("function_calling", "json_mode"): diff --git a/libs/partners/qdrant/langchain_qdrant/vectorstores.py b/libs/partners/qdrant/langchain_qdrant/vectorstores.py index efeaee74337..33ff8228ad0 100644 --- a/libs/partners/qdrant/langchain_qdrant/vectorstores.py +++ b/libs/partners/qdrant/langchain_qdrant/vectorstores.py @@ -1253,8 +1253,8 @@ class Qdrant(VectorStore): If ':memory:' - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - fallback to relying on `host` and `port` parameters. - url: either host or str of "Optional[scheme], host, Optional[port], - Optional[prefix]". Default: `None` + url: either host or str of "scheme | None, host, port | None, + prefix | None". port: Port of the REST API interface. Default: 6333 grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: @@ -1491,8 +1491,8 @@ class Qdrant(VectorStore): If ':memory:' - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - fallback to relying on `host` and `port` parameters. - url: either host or str of "Optional[scheme], host, Optional[port], - Optional[prefix]". Default: `None` + url: either host or str of "scheme | None, host, port | None, + prefix | None". port: Port of the REST API interface. Default: 6333 grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: diff --git a/libs/partners/xai/langchain_xai/chat_models.py b/libs/partners/xai/langchain_xai/chat_models.py index 8283b3362a7..d301df5f37a 100644 --- a/libs/partners/xai/langchain_xai/chat_models.py +++ b/libs/partners/xai/langchain_xai/chat_models.py @@ -45,10 +45,10 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] 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] + max_tokens: int | None Max number of tokens to generate. Refer to your `model's documentation `__ for the maximum number of tokens it can generate. - logprobs: Optional[bool] + logprobs: bool | None Whether to return logprobs. Key init args — client params: @@ -56,7 +56,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] Timeout for requests. max_retries: int Max number of retries. - api_key: Optional[str] + api_key: str | None xAI API key. If not passed in will be read from env var `XAI_API_KEY`. Instantiate: @@ -308,7 +308,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke") - rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10") + rating: int | None = Field(description="How funny the joke is, from 1 to 10") structured_llm = llm.with_structured_output(Joke) @@ -639,7 +639,7 @@ class ChatXAI(BaseChatOpenAI): # type: ignore[override] - ``'raw'``: BaseMessage - ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above. - - ``'parsing_error'``: Optional[BaseException] + - ``'parsing_error'``: BaseException | None """ # noqa: E501 # Some applications require that incompatible parameters (e.g., unsupported 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 b87f2ded3f1..8649a2bd0e7 100644 --- a/libs/standard-tests/langchain_tests/integration_tests/chat_models.py +++ b/libs/standard-tests/langchain_tests/integration_tests/chat_models.py @@ -232,7 +232,7 @@ class ChatModelIntegrationTests(ChatModelTests): .. code-block:: python @property - def tool_choice_value(self) -> Optional[str]: + def tool_choice_value(self) -> str | None: return "any" ??? note "`has_tool_choice`" @@ -1344,8 +1344,8 @@ class ChatModelIntegrationTests(ChatModelTests): def _generate( self, messages: List[BaseMessage], - stop: Optional[List[str]] = None, - run_manager: Optional[CallbackManagerForLLMRun] = None, + stop: list[str] | None = None, + run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> ChatResult: 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 9990e688d85..2c073d8693f 100644 --- a/libs/standard-tests/langchain_tests/unit_tests/chat_models.py +++ b/libs/standard-tests/langchain_tests/unit_tests/chat_models.py @@ -349,7 +349,7 @@ class ChatModelUnitTests(ChatModelTests): .. code-block:: python @property - def tool_choice_value(self) -> Optional[str]: + def tool_choice_value(self) -> str | None: return "any" ??? note "`has_tool_choice`" diff --git a/libs/text-splitters/langchain_text_splitters/html.py b/libs/text-splitters/langchain_text_splitters/html.py index 8a9eccdaea7..daa4e46553f 100644 --- a/libs/text-splitters/langchain_text_splitters/html.py +++ b/libs/text-splitters/langchain_text_splitters/html.py @@ -413,9 +413,7 @@ class HTMLSectionSplitter: html_doc (str): The HTML document to be split into sections. Returns: - List[Dict[str, Optional[str]]]: A list of dictionaries representing - sections. - Each dictionary contains: + A list of dictionaries representing sections. Each dictionary contains: * 'header': The header text or a default title for the first section. * 'content': The content under the header.