The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(core): improve types for `RunnableLambda` (#34539)
Christophe Bornet8cb7dbd37b0e
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.pyindex 8e385a1a2b..9bd63e3bca 100644--- a/libs/core/langchain_core/runnables/base.py+++ b/libs/core/langchain_core/runnables/base.py@@ -4440,6 +4440,138 @@ class RunnableLambda(Runnable[Input, Output]):```"""+ @overload+ def __init__(+ self,+ func: Callable[[Input, RunnableConfig], Awaitable[Output]],+ afunc: None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input], Awaitable[Output]],+ afunc: None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input], AsyncIterator[Output]],+ afunc: None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],+ afunc: None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ],+ afunc: None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input, RunnableConfig], Output],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input], Iterator[Output]],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input], Runnable[Input, Output]],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input, CallbackManagerForChainRun], Output],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...++ @overload+ def __init__(+ self,+ func: Callable[[Input], Output],+ afunc: Callable[[Input], Awaitable[Output]]+ | Callable[[Input], AsyncIterator[Output]]+ | Callable[[Input, RunnableConfig], Awaitable[Output]]+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]+ | Callable[+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]+ ]+ | None = None,+ name: str | None = None,+ ) -> None: ...+def __init__(self,func: Callable[[Input], Iterator[Output]]diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.pyindex a4abbd3857..73c65fe787 100644--- a/libs/core/langchain_core/runnables/history.py+++ b/libs/core/langchain_core/runnables/history.py@@ -320,7 +320,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]`RunnableBindingBase` init."""- history_chain: Runnable = RunnableLambda(+ history_chain: Runnable[Any, Any] = RunnableLambda(self._enter_history, self._aenter_history).with_config(run_name="load_history")messages_key = history_messages_key or input_messages_key@@ -329,16 +329,16 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]**{messages_key: history_chain}).with_config(run_name="insert_history")- runnable_sync: Runnable = runnable.with_listeners(on_end=self._exit_history)- runnable_async: Runnable = runnable.with_alisteners(on_end=self._aexit_history)+ runnable_sync = runnable.with_listeners(on_end=self._exit_history)+ runnable_async = runnable.with_alisteners(on_end=self._aexit_history)- def _call_runnable_sync(_input: Any) -> Runnable:+ def _call_runnable_sync(_input: Any) -> Runnable[Any, Any]:return runnable_sync- async def _call_runnable_async(_input: Any) -> Runnable:+ async def _call_runnable_async(_input: Any) -> Runnable[Any, Any]:return runnable_async- bound: Runnable = (+ bound = (history_chain| RunnableLambda(_call_runnable_sync,diff --git a/libs/core/tests/unit_tests/callbacks/test_dispatch_custom_event.py b/libs/core/tests/unit_tests/callbacks/test_dispatch_custom_event.pyindex 7a6fa0f1bf..b27ec9a4c5 100644--- a/libs/core/tests/unit_tests/callbacks/test_dispatch_custom_event.py+++ b/libs/core/tests/unit_tests/callbacks/test_dispatch_custom_event.py@@ -70,9 +70,7 @@ async def test_async_custom_event_implicit_config() -> None:run_id = uuid.UUID(int=7)- # Typing not working well with RunnableLambda when used as- # a decorator for async functions- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def foo(x: int, config: RunnableConfig) -> int:assert "callbacks" in configawait adispatch_custom_event("event1", {"x": x})@@ -80,7 +78,7 @@ async def test_async_custom_event_implicit_config() -> None:return xawait foo.ainvoke(- 1, # type: ignore[arg-type]+ 1,{"callbacks": [callback], "run_id": run_id},)@@ -96,16 +94,14 @@ async def test_async_callback_manager() -> None:run_id = uuid.UUID(int=7)- # Typing not working well with RunnableLambda when used as- # a decorator for async functions- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def foo(x: int, config: RunnableConfig) -> int:await adispatch_custom_event("event1", {"x": x}, config=config)await adispatch_custom_event("event2", {"x": x}, config=config)return xawait foo.ainvoke(- 1, # type: ignore[arg-type]+ 1,{"callbacks": [callback], "run_id": run_id},)diff --git a/libs/core/tests/unit_tests/runnables/test_concurrency.py b/libs/core/tests/unit_tests/runnables/test_concurrency.pyindex 98144cad13..f3cdefaacb 100644--- a/libs/core/tests/unit_tests/runnables/test_concurrency.py+++ b/libs/core/tests/unit_tests/runnables/test_concurrency.py@@ -3,15 +3,12 @@import asyncioimport timefrom threading import Lock-from typing import TYPE_CHECKING, Any+from typing import Anyimport pytestfrom langchain_core.runnables import RunnableConfig, RunnableLambda-if TYPE_CHECKING:- from langchain_core.runnables.base import Runnable-@pytest.mark.asyncioasync def test_abatch_concurrency() -> None:@@ -33,7 +30,7 @@ async def test_abatch_concurrency() -> None:return f"Completed {x}"- runnable: Runnable = RunnableLambda(tracked_function)+ runnable = RunnableLambda(tracked_function)num_tasks = 10max_concurrency = 3@@ -64,7 +61,7 @@ async def test_abatch_as_completed_concurrency() -> None:return f"Completed {x}"- runnable: Runnable = RunnableLambda(tracked_function)+ runnable = RunnableLambda(tracked_function)num_tasks = 10max_concurrency = 3diff --git a/libs/core/tests/unit_tests/runnables/test_history.py b/libs/core/tests/unit_tests/runnables/test_history.pyindex 3d6abf4ccc..77509b79b5 100644--- a/libs/core/tests/unit_tests/runnables/test_history.py+++ b/libs/core/tests/unit_tests/runnables/test_history.py@@ -52,7 +52,7 @@ def _get_get_session_history(def test_input_messages() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda messages: ("you said: "+ "\n".join(str(m.content) for m in messages if isinstance(m, HumanMessage))@@ -83,7 +83,7 @@ def test_input_messages() -> None:async def test_input_messages_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda messages: ("you said: "+ "\n".join(str(m.content) for m in messages if isinstance(m, HumanMessage))@@ -117,7 +117,7 @@ async def test_input_messages_async() -> None:def test_input_dict() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda params: ("you said: "+ "\n".join(@@ -141,7 +141,7 @@ def test_input_dict() -> None:async def test_input_dict_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda params: ("you said: "+ "\n".join(@@ -167,7 +167,7 @@ async def test_input_dict_async() -> None:def test_input_dict_with_history_key() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda params: ("you said: "+ "\n".join(@@ -195,7 +195,7 @@ def test_input_dict_with_history_key() -> None:async def test_input_dict_with_history_key_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, str](lambda params: ("you said: "+ "\n".join(@@ -223,7 +223,7 @@ async def test_input_dict_with_history_key_async() -> None:def test_output_message() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, AIMessage](lambda params: AIMessage(content="you said: "+ "\n".join(@@ -251,7 +251,7 @@ def test_output_message() -> None:async def test_output_message_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, AIMessage](lambda params: AIMessage(content="you said: "+ "\n".join(@@ -328,7 +328,7 @@ async def test_input_messages_output_message_async() -> None:def test_output_messages() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, list[AIMessage]](lambda params: [AIMessage(content="you said: "@@ -358,7 +358,7 @@ def test_output_messages() -> None:async def test_output_messages_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, list[AIMessage]](lambda params: [AIMessage(content="you said: "@@ -388,7 +388,7 @@ async def test_output_messages_async() -> None:def test_output_dict() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, dict[str, list[AIMessage]]](lambda params: {"output": [AIMessage(@@ -421,7 +421,7 @@ def test_output_dict() -> None:async def test_output_dict_async() -> None:- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, dict[str, list[AIMessage]]](lambda params: {"output": [AIMessage(@@ -457,7 +457,7 @@ def test_get_input_schema_input_dict() -> None:class RunnableWithChatHistoryInput(BaseModel):input: str | BaseMessage | Sequence[BaseMessage]- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, dict[str, list[AIMessage]]](lambda params: {"output": [AIMessage(@@ -489,7 +489,7 @@ def test_get_input_schema_input_dict() -> None:def test_get_output_schema() -> None:"""Test get output schema."""- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, dict[str, list[AIMessage]]](lambda params: {"output": [AIMessage(@@ -526,7 +526,7 @@ def test_get_output_schema() -> None:def test_get_input_schema_input_messages() -> None:runnable_with_message_history_input = RootModel[Sequence[BaseMessage]]- runnable = RunnableLambda(+ runnable = RunnableLambda[Any, dict[str, list[AIMessage]]](lambda messages: {"output": [AIMessage(@@ -855,7 +855,7 @@ class _RunnableLambdaWithRaiseError(RunnableLambda[Input, Output]):def test_get_output_messages_no_value_error() -> None:- runnable = _RunnableLambdaWithRaiseError(+ runnable = _RunnableLambdaWithRaiseError[Any, str](lambda messages: ("you said: "+ "\n".join(str(m.content) for m in messages if isinstance(m, HumanMessage))@@ -876,7 +876,7 @@ def test_get_output_messages_no_value_error() -> None:def test_get_output_messages_with_value_error() -> None:illegal_bool_message = False- runnable = _RunnableLambdaWithRaiseError(lambda _: illegal_bool_message)+ runnable = _RunnableLambdaWithRaiseError[Any, bool](lambda _: illegal_bool_message)get_session_history = _get_get_session_history()with_history = RunnableWithMessageHistory(runnable, get_session_history) # type: ignore[arg-type]config: RunnableConfig = {@@ -893,7 +893,7 @@ def test_get_output_messages_with_value_error() -> None:with_history.bound.invoke([HumanMessage(content="hello")], config)illegal_int_message = 123- runnable2 = _RunnableLambdaWithRaiseError(lambda _: illegal_int_message)+ runnable2 = _RunnableLambdaWithRaiseError[Any, int](lambda _: illegal_int_message)with_history = RunnableWithMessageHistory(runnable2, get_session_history) # type: ignore[arg-type]with pytest.raises(diff --git a/libs/core/tests/unit_tests/runnables/test_runnable.py b/libs/core/tests/unit_tests/runnables/test_runnable.pyindex 5bcc059c7b..91702130ad 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable.py@@ -296,7 +296,7 @@ def test_schemas(snapshot: SnapshotAssertion) -> None:async def typed_async_lambda_impl(x: str) -> int:return len(x)- typed_async_lambda: Runnable = RunnableLambda(typed_async_lambda_impl) # str -> int+ typed_async_lambda = RunnableLambda(typed_async_lambda_impl) # str -> intassert typed_async_lambda.get_input_jsonschema() == {"title": "typed_async_lambda_impl_input",@@ -616,9 +616,7 @@ def test_lambda_schemas(snapshot: SnapshotAssertion) -> None:}assert _normalize_schema(- RunnableLambda(- aget_values_typed # type: ignore[arg-type]- ).get_input_jsonschema()+ RunnableLambda(aget_values_typed).get_input_jsonschema()) == _normalize_schema({"$defs": {@@ -642,7 +640,7 @@ def test_lambda_schemas(snapshot: SnapshotAssertion) -> None:if PYDANTIC_VERSION_AT_LEAST_29:assert _normalize_schema(- RunnableLambda(aget_values_typed).get_output_jsonschema() # type: ignore[arg-type]+ RunnableLambda(aget_values_typed).get_output_jsonschema()) == snapshot(name="schema8")@@ -666,7 +664,7 @@ def test_with_types_with_type_generics() -> None:def test_schema_with_itemgetter() -> None:"""Test runnable with itemgetter."""- foo: Runnable = RunnableLambda(itemgetter("hello"))+ foo = RunnableLambda(itemgetter("hello"))assert _schema(foo.input_schema) == {"properties": {"hello": {"title": "Hello"}},"required": ["hello"],@@ -2685,11 +2683,11 @@ def test_combining_sequences()chat2 = FakeListChatModel(responses=["baz, qux"])parser2 = CommaSeparatedListOutputParser()- input_formatter: RunnableLambda[list[str], dict[str, Any]] = RunnableLambda(+ input_formatter = RunnableLambda[list[str], dict[str, Any]](lambda x: {"question": x[0] + x[1]})- chain2 = cast("RunnableSequence", input_formatter | prompt2 | chat2 | parser2)+ chain2 = input_formatter | prompt2 | chat2 | parser2assert isinstance(chain2, RunnableSequence)assert chain2.first == input_formatter@@ -2697,7 +2695,7 @@ def test_combining_sequences(assert chain2.last == parser2assert dumps(chain2, pretty=True) == snapshot- combined_chain = cast("RunnableSequence", chain | chain2)+ combined_chain = chain | chain2assert isinstance(combined_chain, RunnableSequence)assert combined_chain.first == prompt@@ -4459,8 +4457,8 @@ async def test_seq_abatch_return_exceptions(mocker: MockerFixture) -> None:def test_runnable_branch_init() -> None:"""Verify that runnable branch gets initialized properly."""- add = RunnableLambda(lambda x: x + 1)- condition = RunnableLambda(lambda x: x > 0)+ add = RunnableLambda[int, int](lambda x: x + 1)+ condition = RunnableLambda[int, bool](lambda x: x > 0)# Test failure with less than 2 brancheswith pytest.raises(@@ -4512,9 +4510,9 @@ def test_runnable_branch_init_coercion(branches: Sequence[Any]) -> None:def test_runnable_branch_invoke_call_counts(mocker: MockerFixture) -> None:"""Verify that runnables are invoked only when necessary."""# Test with single branch- add = RunnableLambda(lambda x: x + 1)- sub = RunnableLambda(lambda x: x - 1)- condition = RunnableLambda(lambda x: x > 0)+ add = RunnableLambda[int, int](lambda x: x + 1)+ sub = RunnableLambda[int, int](lambda x: x - 1)+ condition = RunnableLambda[int, bool](lambda x: x > 0)spy = mocker.spy(condition, "invoke")add_spy = mocker.spy(add, "invoke")@@ -4801,7 +4799,7 @@ async def test_runnable_branch_astream_with_callbacks() -> None:def test_representation_of_runnables() -> None:"""Test representation of runnables."""- runnable = RunnableLambda(lambda x: x * 2)+ runnable = RunnableLambda[int, int](lambda x: x * 2)assert repr(runnable) == "RunnableLambda(lambda x: x * 2)"def f(_: int) -> int:@@ -5360,18 +5358,18 @@ async def test_ainvoke_on_returned_runnable() -> None:be runthroughaasync path (issue #13407)."""- def idchain_sync(_input: dict, /) -> bool:+ def idchain_sync(_input: dict[str, Any], /) -> bool:return False- async def idchain_async(_input: dict, /) -> bool:+ async def idchain_async(_input: dict[str, Any], /) -> bool:return Trueidchain = RunnableLambda(func=idchain_sync, afunc=idchain_async)- def func(_input: dict, /) -> Runnable:+ def func(_input: dict[str, Any], /) -> Runnable[dict[str, Any], bool]:return idchain- assert await RunnableLambda[dict, bool](func).ainvoke({})+ assert await RunnableLambda(func).ainvoke({})def test_invoke_stream_passthrough_assign_trace() -> None:@@ -5489,7 +5487,7 @@ async def test_atransform_of_runnable_lambda_with_dicts() -> None:"""Return x."""return x- runnable = RunnableLambda[dict[str, str], dict[str, str]](identity)+ runnable = RunnableLambda(identity)async def chunk_iterator() -> AsyncIterator[dict[str, str]]:yield {"foo": "a"}@@ -5734,22 +5732,24 @@ def test_runnable_assign() -> None:assert result == {"input": 5, "add_step": {"added": 15}}+class _Foo(TypedDict):+ foo: str+++class _InputData(_Foo):+ bar: str++def test_runnable_typed_dict_schema() -> None:"""Testing that the schema is generated properly(not empty) when using TypedDict.subclasses to annotate the arguments of a RunnableParallel children."""- class Foo(TypedDict):- foo: str-- class InputData(Foo):- bar: str-- def forward_foo(input_data: InputData) -> str:+ def forward_foo(input_data: _InputData) -> str:return input_data["foo"]- def transform_input(input_data: InputData) -> dict[str, str]:+ def transform_input(input_data: _InputData) -> dict[str, str]:foo = input_data["foo"]bar = input_data["bar"]diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.pyindex dbe06ce6c4..06f13e035b 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py@@ -431,9 +431,9 @@ async def test_event_stream_with_triple_lambda_test_filtering() -> None:async def test_event_stream_with_lambdas_from_lambda() -> None:- as_lambdas = RunnableLambda(lambda _: {"answer": "goodbye"}).with_config(- {"run_name": "my_lambda"}- )+ as_lambdas = RunnableLambda[Any, dict[str, str]](+ lambda _: {"answer": "goodbye"}+ ).with_config({"run_name": "my_lambda"})events = await _collect_events(as_lambdas.astream_events({"question": "hello"}, version="v1"))@@ -1866,7 +1866,7 @@ async def test_runnable_each() -> None:async def add_one(x: int) -> int:return x + 1- add_one_map = RunnableLambda(add_one).map() # type: ignore[arg-type,var-annotated]+ add_one_map = RunnableLambda(add_one).map()assert await add_one_map.ainvoke([1, 2, 3]) == [2, 3, 4]with pytest.raises(NotImplementedError):@@ -2108,7 +2108,7 @@ async def test_sync_in_async_stream_lambdas() -> None:results = list(streaming)return results[0]- add_one_proxy = RunnableLambda(add_one_proxy_) # type: ignore[arg-type,var-annotated]+ add_one_proxy = RunnableLambda(add_one_proxy_)events = await _collect_events(add_one_proxy.astream_events(1, version="v1"))_assert_events_equal_allow_superset_metadata(events, EXPECTED_EVENTS)@@ -2120,7 +2120,7 @@ async def test_async_in_async_stream_lambdas() -> None:async def add_one(x: int) -> int:return x + 1- add_one_ = RunnableLambda[int, int](add_one)+ add_one_ = RunnableLambda(add_one)async def add_one_proxy(x: int, config: RunnableConfig) -> int:# Use sync streamingdiff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.pyindex a74f72abed..4a99123a46 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py@@ -18,7 +18,9 @@ from pydantic import BaseModelfrom typing_extensions import overridefrom langchain_core.callbacks import CallbackManagerForRetrieverRun, Callbacks-from langchain_core.callbacks.manager import adispatch_custom_event+from langchain_core.callbacks.manager import (+ adispatch_custom_event,+)from langchain_core.chat_history import BaseChatMessageHistoryfrom langchain_core.documents import Documentfrom langchain_core.language_models import FakeStreamingListLLM, GenericFakeChatModel@@ -461,9 +463,9 @@ async def test_event_stream_with_triple_lambda_test_filtering() -> None:async def test_event_stream_with_lambdas_from_lambda() -> None:- as_lambdas = RunnableLambda(lambda _: {"answer": "goodbye"}).with_config(- {"run_name": "my_lambda"}- )+ as_lambdas = RunnableLambda[Any, dict[str, str]](+ lambda _: {"answer": "goodbye"}+ ).with_config({"run_name": "my_lambda"})events = await _collect_events(as_lambdas.astream_events({"question": "hello"}, version="v2"))@@ -1105,8 +1107,6 @@ async def test_event_streaming_with_tools() -> None:_ = callbacksreturn {"x": x, "y": y}- # type ignores below because the tools don't appear to be runnables to type checkers- # we can remove as soon as that's fixedevents = await _collect_events(parameterless.astream_events({}, version="v2"))_assert_events_equal_allow_superset_metadata(events,@@ -1399,8 +1399,6 @@ async def test_event_stream_on_chain_with_tool() -> None:"""Reverse a string."""return s[::-1]- # For whatever reason type annotations fail here because reverse- # does not appear to be a runnablechain = concat | reverseevents = await _collect_events(@@ -1816,7 +1814,7 @@ async def test_runnable_each() -> None:async def add_one(x: int) -> int:return x + 1- add_one_map = RunnableLambda(add_one).map() # type: ignore[arg-type,var-annotated]+ add_one_map = RunnableLambda(add_one).map()assert await add_one_map.ainvoke([1, 2, 3]) == [2, 3, 4]with pytest.raises(NotImplementedError):@@ -2074,7 +2072,7 @@ async def test_sync_in_async_stream_lambdas(blockbuster: BlockBuster) -> None:results = list(streaming)return results[0]- add_one_proxy_ = RunnableLambda(add_one_proxy) # type: ignore[arg-type,var-annotated]+ add_one_proxy_ = RunnableLambda(add_one_proxy)events = await _collect_events(add_one_proxy_.astream_events(1, version="v2"))_assert_events_equal_allow_superset_metadata(events, EXPECTED_EVENTS)@@ -2086,7 +2084,7 @@ async def test_async_in_async_stream_lambdas() -> None:async def add_one(x: int) -> int:return x + 1- add_one_ = RunnableLambda[int, int](add_one)+ add_one_ = RunnableLambda(add_one)async def add_one_proxy(x: int, config: RunnableConfig) -> int:# Use sync streaming@@ -2246,22 +2244,19 @@ async def test_astream_events_from_custom_runnable() -> None:async def test_parent_run_id_assignment() -> None:"""Test assignment of parent run id."""- # Type ignores in the code below need to be investigated.- # Looks like a typing issue when using RunnableLambda as a decorator- # with async functions.- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def grandchild(x: str) -> str:return x- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambda[str, str]async def child(x: str, config: RunnableConfig) -> str:config["run_id"] = uuid.UUID(int=9)- return await grandchild.ainvoke(x, config) # type: ignore[arg-type]+ return await grandchild.ainvoke(x, config)- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambda[str, str]async def parent(x: str, config: RunnableConfig) -> str:config["run_id"] = uuid.UUID(int=8)- return await child.ainvoke(x, config) # type: ignore[arg-type]+ return await child.ainvoke(x, config)bond = uuid.UUID(int=7)events = await _collect_events(@@ -2347,17 +2342,14 @@ async def test_parent_run_id_assignment() -> None:async def test_bad_parent_ids() -> None:"""Test handling of situation where a run id is duplicated in the run tree."""- # Type ignores in the code below need to be investigated.- # Looks like a typing issue when using RunnableLambda as a decorator- # with async functions.- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def child(x: str) -> str:return x- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def parent(x: str, config: RunnableConfig) -> str:config["run_id"] = uuid.UUID(int=7)- return await child.ainvoke(x, config) # type: ignore[arg-type]+ return await child.ainvoke(x, config)bond = uuid.UUID(int=7)events = await _collect_events(@@ -2607,9 +2599,7 @@ async def test_cancel_astream_events() -> None:async def test_custom_event() -> None:"""Test adhoc event."""- # Ignoring type due to RunnableLamdba being dynamic when it comes to being- # applied as a decorator to async functions.- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def foo(x: int, config: RunnableConfig) -> int:"""Simple function that emits some adhoc events."""await adispatch_custom_event("event1", {"x": x}, config=config)@@ -2683,9 +2673,7 @@ async def test_custom_event() -> None:async def test_custom_event_nested() -> None:"""Test adhoc event in a nested chain."""- # Ignoring type due to RunnableLamdba being dynamic when it comes to being- # applied as a decorator to async functions.- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambda[int, int]async def foo(x: int, config: RunnableConfig) -> int:"""Simple function that emits some adhoc events."""await adispatch_custom_event("event1", {"x": x}, config=config)@@ -2695,13 +2683,11 @@ async def test_custom_event_nested() -> None:run_id = uuid.UUID(int=7)child_run_id = uuid.UUID(int=8)- # Ignoring type due to RunnableLamdba being dynamic when it comes to being- # applied as a decorator to async functions.- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambda[int, int]async def bar(x: int, config: RunnableConfig) -> int:"""Simple function that emits some adhoc events."""return await foo.ainvoke(- x, # type: ignore[arg-type]+ x,{"run_id": child_run_id, **config},)@@ -2812,7 +2798,6 @@ async def test_custom_event_root_dispatch_with_in_tool() -> None:await adispatch_custom_event("event1", {"x": x})return x + 1- # Ignoring type due to @tool not returning correct type annotationsevents = await _collect_events(foo.astream_events({"x": 2}, version="v2"))_assert_events_equal_allow_superset_metadata(events,diff --git a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py b/libs/core/tests/unit_tests/runnables/test_tracing_interops.pyindex 6055ed21f8..b5fae902f7 100644--- a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py+++ b/libs/core/tests/unit_tests/runnables/test_tracing_interops.py@@ -170,13 +170,13 @@ async def test_config_traceable_async_handoff() -> None:def my_great_grandchild_function(a: int) -> int:return my_great_great_grandchild_function(a)- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def my_grandchild_function(a: int) -> int:return my_great_grandchild_function.invoke(a)@traceableasync def my_child_function(a: int) -> int:- return await my_grandchild_function.ainvoke(a) * 3 # type: ignore[arg-type]+ return await my_grandchild_function.ainvoke(a) * 3@traceable()async def my_function(a: int) -> int:@@ -185,7 +185,7 @@ async def test_config_traceable_async_handoff() -> None:async def my_parent_function(a: int) -> int:return await my_function(a)- my_parent_runnable = RunnableLambda(my_parent_function) # type: ignore[arg-type,var-annotated]+ my_parent_runnable = RunnableLambda(my_parent_function)result = await my_parent_runnable.ainvoke(1, {"callbacks": [tracer]})assert result == 6posts = _get_posts(tracer.client)@@ -288,7 +288,7 @@ class TestRunnableSequenceParallelTraceNesting:sequence = before | parallel | afterif isasyncgenfunction(other_thing):- @RunnableLambda # type: ignore[arg-type]+ @RunnableLambdaasync def parent(a: int) -> int:return await sequence.ainvoke(a)