langchain-core 1.0.0a1__py3-none-any.whl → 1.0.0a3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of langchain-core might be problematic. Click here for more details.

Files changed (131) hide show
  1. langchain_core/_api/beta_decorator.py +17 -40
  2. langchain_core/_api/deprecation.py +20 -7
  3. langchain_core/_api/path.py +19 -2
  4. langchain_core/_import_utils.py +7 -0
  5. langchain_core/agents.py +10 -6
  6. langchain_core/callbacks/base.py +28 -15
  7. langchain_core/callbacks/manager.py +81 -69
  8. langchain_core/callbacks/usage.py +4 -2
  9. langchain_core/chat_history.py +29 -21
  10. langchain_core/document_loaders/base.py +34 -9
  11. langchain_core/document_loaders/langsmith.py +3 -0
  12. langchain_core/documents/base.py +35 -10
  13. langchain_core/documents/transformers.py +4 -2
  14. langchain_core/embeddings/fake.py +8 -5
  15. langchain_core/env.py +2 -3
  16. langchain_core/example_selectors/base.py +12 -0
  17. langchain_core/exceptions.py +7 -0
  18. langchain_core/globals.py +17 -28
  19. langchain_core/indexing/api.py +57 -45
  20. langchain_core/indexing/base.py +5 -8
  21. langchain_core/indexing/in_memory.py +23 -3
  22. langchain_core/language_models/__init__.py +6 -2
  23. langchain_core/language_models/_utils.py +28 -4
  24. langchain_core/language_models/base.py +33 -21
  25. langchain_core/language_models/chat_models.py +103 -29
  26. langchain_core/language_models/fake_chat_models.py +5 -7
  27. langchain_core/language_models/llms.py +54 -20
  28. langchain_core/load/dump.py +2 -3
  29. langchain_core/load/load.py +15 -1
  30. langchain_core/load/serializable.py +38 -43
  31. langchain_core/memory.py +7 -3
  32. langchain_core/messages/__init__.py +7 -17
  33. langchain_core/messages/ai.py +41 -34
  34. langchain_core/messages/base.py +16 -7
  35. langchain_core/messages/block_translators/__init__.py +10 -8
  36. langchain_core/messages/block_translators/anthropic.py +3 -1
  37. langchain_core/messages/block_translators/bedrock.py +3 -1
  38. langchain_core/messages/block_translators/bedrock_converse.py +3 -1
  39. langchain_core/messages/block_translators/google_genai.py +3 -1
  40. langchain_core/messages/block_translators/google_vertexai.py +3 -1
  41. langchain_core/messages/block_translators/groq.py +3 -1
  42. langchain_core/messages/block_translators/langchain_v0.py +3 -136
  43. langchain_core/messages/block_translators/ollama.py +3 -1
  44. langchain_core/messages/block_translators/openai.py +252 -10
  45. langchain_core/messages/content.py +26 -124
  46. langchain_core/messages/human.py +2 -13
  47. langchain_core/messages/system.py +2 -6
  48. langchain_core/messages/tool.py +34 -14
  49. langchain_core/messages/utils.py +189 -74
  50. langchain_core/output_parsers/base.py +5 -2
  51. langchain_core/output_parsers/json.py +4 -4
  52. langchain_core/output_parsers/list.py +7 -22
  53. langchain_core/output_parsers/openai_functions.py +3 -0
  54. langchain_core/output_parsers/openai_tools.py +6 -1
  55. langchain_core/output_parsers/pydantic.py +4 -0
  56. langchain_core/output_parsers/string.py +5 -1
  57. langchain_core/output_parsers/xml.py +19 -19
  58. langchain_core/outputs/chat_generation.py +18 -7
  59. langchain_core/outputs/generation.py +14 -3
  60. langchain_core/outputs/llm_result.py +8 -1
  61. langchain_core/prompt_values.py +10 -4
  62. langchain_core/prompts/base.py +6 -11
  63. langchain_core/prompts/chat.py +88 -60
  64. langchain_core/prompts/dict.py +16 -8
  65. langchain_core/prompts/few_shot.py +9 -11
  66. langchain_core/prompts/few_shot_with_templates.py +5 -1
  67. langchain_core/prompts/image.py +12 -5
  68. langchain_core/prompts/loading.py +2 -2
  69. langchain_core/prompts/message.py +5 -6
  70. langchain_core/prompts/pipeline.py +13 -8
  71. langchain_core/prompts/prompt.py +22 -8
  72. langchain_core/prompts/string.py +18 -10
  73. langchain_core/prompts/structured.py +7 -2
  74. langchain_core/rate_limiters.py +2 -2
  75. langchain_core/retrievers.py +7 -6
  76. langchain_core/runnables/base.py +387 -246
  77. langchain_core/runnables/branch.py +11 -28
  78. langchain_core/runnables/config.py +20 -17
  79. langchain_core/runnables/configurable.py +34 -19
  80. langchain_core/runnables/fallbacks.py +20 -13
  81. langchain_core/runnables/graph.py +48 -38
  82. langchain_core/runnables/graph_ascii.py +40 -17
  83. langchain_core/runnables/graph_mermaid.py +54 -25
  84. langchain_core/runnables/graph_png.py +27 -31
  85. langchain_core/runnables/history.py +55 -58
  86. langchain_core/runnables/passthrough.py +44 -21
  87. langchain_core/runnables/retry.py +44 -23
  88. langchain_core/runnables/router.py +9 -8
  89. langchain_core/runnables/schema.py +9 -0
  90. langchain_core/runnables/utils.py +53 -90
  91. langchain_core/stores.py +19 -31
  92. langchain_core/sys_info.py +9 -8
  93. langchain_core/tools/base.py +36 -27
  94. langchain_core/tools/convert.py +25 -14
  95. langchain_core/tools/simple.py +36 -8
  96. langchain_core/tools/structured.py +25 -12
  97. langchain_core/tracers/base.py +2 -2
  98. langchain_core/tracers/context.py +5 -1
  99. langchain_core/tracers/core.py +110 -46
  100. langchain_core/tracers/evaluation.py +22 -26
  101. langchain_core/tracers/event_stream.py +97 -42
  102. langchain_core/tracers/langchain.py +12 -3
  103. langchain_core/tracers/langchain_v1.py +10 -2
  104. langchain_core/tracers/log_stream.py +56 -17
  105. langchain_core/tracers/root_listeners.py +4 -20
  106. langchain_core/tracers/run_collector.py +6 -16
  107. langchain_core/tracers/schemas.py +5 -1
  108. langchain_core/utils/aiter.py +14 -6
  109. langchain_core/utils/env.py +3 -0
  110. langchain_core/utils/function_calling.py +46 -20
  111. langchain_core/utils/interactive_env.py +6 -2
  112. langchain_core/utils/iter.py +12 -5
  113. langchain_core/utils/json.py +12 -3
  114. langchain_core/utils/json_schema.py +156 -40
  115. langchain_core/utils/loading.py +5 -1
  116. langchain_core/utils/mustache.py +25 -16
  117. langchain_core/utils/pydantic.py +38 -9
  118. langchain_core/utils/utils.py +25 -9
  119. langchain_core/vectorstores/base.py +7 -20
  120. langchain_core/vectorstores/in_memory.py +20 -14
  121. langchain_core/vectorstores/utils.py +18 -12
  122. langchain_core/version.py +1 -1
  123. langchain_core-1.0.0a3.dist-info/METADATA +77 -0
  124. langchain_core-1.0.0a3.dist-info/RECORD +181 -0
  125. langchain_core/beta/__init__.py +0 -1
  126. langchain_core/beta/runnables/__init__.py +0 -1
  127. langchain_core/beta/runnables/context.py +0 -448
  128. langchain_core-1.0.0a1.dist-info/METADATA +0 -106
  129. langchain_core-1.0.0a1.dist-info/RECORD +0 -184
  130. {langchain_core-1.0.0a1.dist-info → langchain_core-1.0.0a3.dist-info}/WHEEL +0 -0
  131. {langchain_core-1.0.0a1.dist-info → langchain_core-1.0.0a3.dist-info}/entry_points.txt +0 -0
@@ -20,7 +20,7 @@ from collections.abc import (
20
20
  )
21
21
  from concurrent.futures import FIRST_COMPLETED, wait
22
22
  from functools import wraps
23
- from itertools import groupby, tee
23
+ from itertools import tee
24
24
  from operator import itemgetter
25
25
  from types import GenericAlias
26
26
  from typing import (
@@ -28,19 +28,22 @@ from typing import (
28
28
  Any,
29
29
  Callable,
30
30
  Generic,
31
+ Literal,
31
32
  Optional,
32
33
  Protocol,
33
34
  TypeVar,
34
35
  Union,
35
36
  cast,
37
+ get_args,
36
38
  get_type_hints,
37
39
  overload,
38
40
  )
39
41
 
40
42
  from pydantic import BaseModel, ConfigDict, Field, RootModel
41
- from typing_extensions import Literal, get_args, override
43
+ from typing_extensions import override
42
44
 
43
45
  from langchain_core._api import beta_decorator
46
+ from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
44
47
  from langchain_core.load.serializable import (
45
48
  Serializable,
46
49
  SerializedConstructor,
@@ -60,7 +63,6 @@ from langchain_core.runnables.config import (
60
63
  run_in_executor,
61
64
  set_config_context,
62
65
  )
63
- from langchain_core.runnables.graph import Graph
64
66
  from langchain_core.runnables.utils import (
65
67
  AddableDict,
66
68
  AnyConfigurableField,
@@ -81,6 +83,19 @@ from langchain_core.runnables.utils import (
81
83
  is_async_callable,
82
84
  is_async_generator,
83
85
  )
86
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
87
+ from langchain_core.tracers.event_stream import (
88
+ _astream_events_implementation_v1,
89
+ _astream_events_implementation_v2,
90
+ )
91
+ from langchain_core.tracers.log_stream import (
92
+ LogStreamCallbackHandler,
93
+ _astream_log_implementation,
94
+ )
95
+ from langchain_core.tracers.root_listeners import (
96
+ AsyncRootListenersTracer,
97
+ RootListenersTracer,
98
+ )
84
99
  from langchain_core.utils.aiter import aclosing, atee, py_anext
85
100
  from langchain_core.utils.iter import safetee
86
101
  from langchain_core.utils.pydantic import create_model_v2
@@ -94,6 +109,7 @@ if TYPE_CHECKING:
94
109
  from langchain_core.runnables.fallbacks import (
95
110
  RunnableWithFallbacks as RunnableWithFallbacksT,
96
111
  )
112
+ from langchain_core.runnables.graph import Graph
97
113
  from langchain_core.runnables.retry import ExponentialJitterParams
98
114
  from langchain_core.runnables.schema import StreamEvent
99
115
  from langchain_core.tools import BaseTool
@@ -114,12 +130,13 @@ class Runnable(ABC, Generic[Input, Output]):
114
130
  - **``invoke``/``ainvoke``**: Transforms a single input into an output.
115
131
  - **``batch``/``abatch``**: Efficiently transforms multiple inputs into outputs.
116
132
  - **``stream``/``astream``**: Streams output from a single input as it's produced.
117
- - **``astream_log``**: Streams output and selected intermediate results from an input.
133
+ - **``astream_log``**: Streams output and selected intermediate results from an
134
+ input.
118
135
 
119
136
  Built-in optimizations:
120
137
 
121
- - **Batch**: By default, batch runs invoke() in parallel using a thread pool executor.
122
- Override to optimize batching.
138
+ - **Batch**: By default, batch runs invoke() in parallel using a thread pool
139
+ executor. Override to optimize batching.
123
140
 
124
141
  - **Async**: Methods with ``'a'`` suffix are asynchronous. By default, they execute
125
142
  the sync counterpart using asyncio's thread pool.
@@ -129,14 +146,16 @@ class Runnable(ABC, Generic[Input, Output]):
129
146
  execution, add tags and metadata for tracing and debugging etc.
130
147
 
131
148
  Runnables expose schematic information about their input, output and config via
132
- the ``input_schema`` property, the ``output_schema`` property and ``config_schema`` method.
149
+ the ``input_schema`` property, the ``output_schema`` property and ``config_schema``
150
+ method.
133
151
 
134
152
  LCEL and Composition
135
153
  ====================
136
154
 
137
- The LangChain Expression Language (LCEL) is a declarative way to compose ``Runnables``
138
- into chains. Any chain constructed this way will automatically have sync, async,
139
- batch, and streaming support.
155
+ The LangChain Expression Language (LCEL) is a declarative way to compose
156
+ ``Runnables``into chains.
157
+ Any chain constructed this way will automatically have sync, async, batch, and
158
+ streaming support.
140
159
 
141
160
  The main composition primitives are ``RunnableSequence`` and ``RunnableParallel``.
142
161
 
@@ -157,25 +176,27 @@ class Runnable(ABC, Generic[Input, Output]):
157
176
 
158
177
  # A RunnableSequence constructed using the `|` operator
159
178
  sequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)
160
- sequence.invoke(1) # 4
161
- sequence.batch([1, 2, 3]) # [4, 6, 8]
179
+ sequence.invoke(1) # 4
180
+ sequence.batch([1, 2, 3]) # [4, 6, 8]
162
181
 
163
182
 
164
183
  # A sequence that contains a RunnableParallel constructed using a dict literal
165
184
  sequence = RunnableLambda(lambda x: x + 1) | {
166
- 'mul_2': RunnableLambda(lambda x: x * 2),
167
- 'mul_5': RunnableLambda(lambda x: x * 5)
185
+ "mul_2": RunnableLambda(lambda x: x * 2),
186
+ "mul_5": RunnableLambda(lambda x: x * 5),
168
187
  }
169
- sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
188
+ sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
170
189
 
171
190
  Standard Methods
172
191
  ================
173
192
 
174
- All ``Runnable``s expose additional methods that can be used to modify their behavior
175
- (e.g., add a retry policy, add lifecycle listeners, make them configurable, etc.).
193
+ All ``Runnable``s expose additional methods that can be used to modify their
194
+ behavior (e.g., add a retry policy, add lifecycle listeners, make them
195
+ configurable, etc.).
176
196
 
177
- These methods will work on any ``Runnable``, including ``Runnable`` chains constructed
178
- by composing other ``Runnable``s. See the individual methods for details.
197
+ These methods will work on any ``Runnable``, including ``Runnable`` chains
198
+ constructed by composing other ``Runnable``s.
199
+ See the individual methods for details.
179
200
 
180
201
  For example,
181
202
 
@@ -219,6 +240,7 @@ class Runnable(ABC, Generic[Input, Output]):
219
240
  .. code-block:: python
220
241
 
221
242
  from langchain_core.globals import set_debug
243
+
222
244
  set_debug(True)
223
245
 
224
246
  Alternatively, you can pass existing or custom callbacks to any given chain:
@@ -227,14 +249,11 @@ class Runnable(ABC, Generic[Input, Output]):
227
249
 
228
250
  from langchain_core.tracers import ConsoleCallbackHandler
229
251
 
230
- chain.invoke(
231
- ...,
232
- config={'callbacks': [ConsoleCallbackHandler()]}
233
- )
252
+ chain.invoke(..., config={"callbacks": [ConsoleCallbackHandler()]})
234
253
 
235
254
  For a UI (and much more) checkout `LangSmith <https://docs.smith.langchain.com/>`__.
236
255
 
237
- """ # noqa: E501
256
+ """
238
257
 
239
258
  name: Optional[str]
240
259
  """The name of the ``Runnable``. Used for debugging and tracing."""
@@ -242,7 +261,15 @@ class Runnable(ABC, Generic[Input, Output]):
242
261
  def get_name(
243
262
  self, suffix: Optional[str] = None, *, name: Optional[str] = None
244
263
  ) -> str:
245
- """Get the name of the ``Runnable``."""
264
+ """Get the name of the ``Runnable``.
265
+
266
+ Args:
267
+ suffix: An optional suffix to append to the name.
268
+ name: An optional name to use instead of the ``Runnable``'s name.
269
+
270
+ Returns:
271
+ The name of the ``Runnable``.
272
+ """
246
273
  if name:
247
274
  name_ = name
248
275
  elif hasattr(self, "name") and self.name:
@@ -273,7 +300,13 @@ class Runnable(ABC, Generic[Input, Output]):
273
300
 
274
301
  @property
275
302
  def InputType(self) -> type[Input]: # noqa: N802
276
- """The type of input this ``Runnable`` accepts specified as a type annotation.""" # noqa: E501
303
+ """Input type.
304
+
305
+ The type of input this ``Runnable`` accepts specified as a type annotation.
306
+
307
+ Raises:
308
+ TypeError: If the input type cannot be inferred.
309
+ """
277
310
  # First loop through all parent classes and if any of them is
278
311
  # a pydantic model, we will pick up the generic parameterization
279
312
  # from that model via the __pydantic_generic_metadata__ attribute.
@@ -299,7 +332,13 @@ class Runnable(ABC, Generic[Input, Output]):
299
332
 
300
333
  @property
301
334
  def OutputType(self) -> type[Output]: # noqa: N802
302
- """The type of output this ``Runnable`` produces specified as a type annotation.""" # noqa: E501
335
+ """Output Type.
336
+
337
+ The type of output this ``Runnable`` produces specified as a type annotation.
338
+
339
+ Raises:
340
+ TypeError: If the output type cannot be inferred.
341
+ """
303
342
  # First loop through bases -- this will help generic
304
343
  # any pydantic models.
305
344
  for base in self.__class__.mro():
@@ -381,9 +420,11 @@ class Runnable(ABC, Generic[Input, Output]):
381
420
 
382
421
  from langchain_core.runnables import RunnableLambda
383
422
 
423
+
384
424
  def add_one(x: int) -> int:
385
425
  return x + 1
386
426
 
427
+
387
428
  runnable = RunnableLambda(add_one)
388
429
 
389
430
  print(runnable.get_input_jsonschema())
@@ -395,7 +436,10 @@ class Runnable(ABC, Generic[Input, Output]):
395
436
 
396
437
  @property
397
438
  def output_schema(self) -> type[BaseModel]:
398
- """The type of output this ``Runnable`` produces specified as a pydantic model.""" # noqa: E501
439
+ """Output schema.
440
+
441
+ The type of output this ``Runnable`` produces specified as a pydantic model.
442
+ """
399
443
  return self.get_output_schema()
400
444
 
401
445
  def get_output_schema(
@@ -455,9 +499,11 @@ class Runnable(ABC, Generic[Input, Output]):
455
499
 
456
500
  from langchain_core.runnables import RunnableLambda
457
501
 
502
+
458
503
  def add_one(x: int) -> int:
459
504
  return x + 1
460
505
 
506
+
461
507
  runnable = RunnableLambda(add_one)
462
508
 
463
509
  print(runnable.get_output_jsonschema())
@@ -535,6 +581,9 @@ class Runnable(ABC, Generic[Input, Output]):
535
581
 
536
582
  def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
537
583
  """Return a graph representation of this ``Runnable``."""
584
+ # Import locally to prevent circular import
585
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
586
+
538
587
  graph = Graph()
539
588
  try:
540
589
  input_node = graph.add_node(self.get_input_schema(config))
@@ -555,7 +604,8 @@ class Runnable(ABC, Generic[Input, Output]):
555
604
  self, config: Optional[RunnableConfig] = None
556
605
  ) -> list[BasePromptTemplate]:
557
606
  """Return a list of prompts used by this ``Runnable``."""
558
- from langchain_core.prompts.base import BasePromptTemplate
607
+ # Import locally to prevent circular import
608
+ from langchain_core.prompts.base import BasePromptTemplate # noqa: PLC0415
559
609
 
560
610
  return [
561
611
  node.data
@@ -573,7 +623,17 @@ class Runnable(ABC, Generic[Input, Output]):
573
623
  Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]],
574
624
  ],
575
625
  ) -> RunnableSerializable[Input, Other]:
576
- """Compose this ``Runnable`` with another object to create a ``RunnableSequence``.""" # noqa: E501
626
+ """Runnable "or" operator.
627
+
628
+ Compose this ``Runnable`` with another object to create a
629
+ ``RunnableSequence``.
630
+
631
+ Args:
632
+ other: Another ``Runnable`` or a ``Runnable``-like object.
633
+
634
+ Returns:
635
+ A new ``Runnable``.
636
+ """
577
637
  return RunnableSequence(self, coerce_to_runnable(other))
578
638
 
579
639
  def __ror__(
@@ -586,7 +646,17 @@ class Runnable(ABC, Generic[Input, Output]):
586
646
  Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]],
587
647
  ],
588
648
  ) -> RunnableSerializable[Other, Output]:
589
- """Compose this ``Runnable`` with another object to create a ``RunnableSequence``.""" # noqa: E501
649
+ """Runnable "reverse-or" operator.
650
+
651
+ Compose this ``Runnable`` with another object to create a
652
+ ``RunnableSequence``.
653
+
654
+ Args:
655
+ other: Another ``Runnable`` or a ``Runnable``-like object.
656
+
657
+ Returns:
658
+ A new ``Runnable``.
659
+ """
590
660
  return RunnableSequence(coerce_to_runnable(other), self)
591
661
 
592
662
  def pipe(
@@ -594,21 +664,28 @@ class Runnable(ABC, Generic[Input, Output]):
594
664
  *others: Union[Runnable[Any, Other], Callable[[Any], Other]],
595
665
  name: Optional[str] = None,
596
666
  ) -> RunnableSerializable[Input, Other]:
597
- """Compose this ``Runnable`` with ``Runnable``-like objects to make a ``RunnableSequence``.
667
+ """Pipe runnables.
668
+
669
+ Compose this ``Runnable`` with ``Runnable``-like objects to make a
670
+ ``RunnableSequence``.
598
671
 
599
672
  Equivalent to ``RunnableSequence(self, *others)`` or ``self | others[0] | ...``
600
673
 
601
674
  Example:
675
+
602
676
  .. code-block:: python
603
677
 
604
678
  from langchain_core.runnables import RunnableLambda
605
679
 
680
+
606
681
  def add_one(x: int) -> int:
607
682
  return x + 1
608
683
 
684
+
609
685
  def mul_two(x: int) -> int:
610
686
  return x * 2
611
687
 
688
+
612
689
  runnable_1 = RunnableLambda(add_one)
613
690
  runnable_2 = RunnableLambda(mul_two)
614
691
  sequence = runnable_1.pipe(runnable_2)
@@ -623,13 +700,20 @@ class Runnable(ABC, Generic[Input, Output]):
623
700
  await sequence.abatch([1, 2, 3])
624
701
  # -> [4, 6, 8]
625
702
 
626
- """ # noqa: E501
703
+ Args:
704
+ *others: Other ``Runnable`` or ``Runnable``-like objects to compose
705
+ name: An optional name for the resulting ``RunnableSequence``.
706
+
707
+ Returns:
708
+ A new ``Runnable``.
709
+ """
627
710
  return RunnableSequence(self, *others, name=name)
628
711
 
629
712
  def pick(self, keys: Union[str, list[str]]) -> RunnableSerializable[Any, Any]:
630
713
  """Pick keys from the output dict of this ``Runnable``.
631
714
 
632
715
  Pick single key:
716
+
633
717
  .. code-block:: python
634
718
 
635
719
  import json
@@ -648,6 +732,7 @@ class Runnable(ABC, Generic[Input, Output]):
648
732
  # -> [1, 2, 3]
649
733
 
650
734
  Pick list of keys:
735
+
651
736
  .. code-block:: python
652
737
 
653
738
  from typing import Any
@@ -658,13 +743,14 @@ class Runnable(ABC, Generic[Input, Output]):
658
743
 
659
744
  as_str = RunnableLambda(str)
660
745
  as_json = RunnableLambda(json.loads)
746
+
747
+
661
748
  def as_bytes(x: Any) -> bytes:
662
749
  return bytes(x, "utf-8")
663
750
 
751
+
664
752
  chain = RunnableMap(
665
- str=as_str,
666
- json=as_json,
667
- bytes=RunnableLambda(as_bytes)
753
+ str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)
668
754
  )
669
755
 
670
756
  chain.invoke("[1, 2, 3]")
@@ -674,8 +760,15 @@ class Runnable(ABC, Generic[Input, Output]):
674
760
  json_and_bytes_chain.invoke("[1, 2, 3]")
675
761
  # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
676
762
 
763
+ Args:
764
+ keys: A key or list of keys to pick from the output dict.
765
+
766
+ Returns:
767
+ a new ``Runnable``.
768
+
677
769
  """
678
- from langchain_core.runnables.passthrough import RunnablePick
770
+ # Import locally to prevent circular import
771
+ from langchain_core.runnables.passthrough import RunnablePick # noqa: PLC0415
679
772
 
680
773
  return self | RunnablePick(keys)
681
774
 
@@ -692,8 +785,6 @@ class Runnable(ABC, Generic[Input, Output]):
692
785
  ) -> RunnableSerializable[Any, Any]:
693
786
  """Assigns new fields to the dict output of this ``Runnable``.
694
787
 
695
- Returns a new ``Runnable``.
696
-
697
788
  .. code-block:: python
698
789
 
699
790
  from langchain_community.llms.fake import FakeStreamingListLLM
@@ -720,8 +811,16 @@ class Runnable(ABC, Generic[Input, Output]):
720
811
  {'str': {'title': 'Str',
721
812
  'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
722
813
 
814
+ Args:
815
+ **kwargs: A mapping of keys to ``Runnable`` or ``Runnable``-like objects
816
+ that will be invoked with the entire output dict of this ``Runnable``.
817
+
818
+ Returns:
819
+ A new ``Runnable``.
820
+
723
821
  """
724
- from langchain_core.runnables.passthrough import RunnableAssign
822
+ # Import locally to prevent circular import
823
+ from langchain_core.runnables.passthrough import RunnableAssign # noqa: PLC0415
725
824
 
726
825
  return self | RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
727
826
 
@@ -755,12 +854,18 @@ class Runnable(ABC, Generic[Input, Output]):
755
854
  config: Optional[RunnableConfig] = None,
756
855
  **kwargs: Any,
757
856
  ) -> Output:
758
- """Default implementation of ``ainvoke``, calls ``invoke`` from a thread.
857
+ """Transform a single input into an output.
759
858
 
760
- The default implementation allows usage of async code even if
761
- the ``Runnable`` did not implement a native async version of ``invoke``.
859
+ Args:
860
+ input: The input to the ``Runnable``.
861
+ config: A config to use when invoking the ``Runnable``.
862
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
863
+ tracing purposes, ``'max_concurrency'`` for controlling how much work to
864
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
865
+ for more details. Defaults to None.
762
866
 
763
- Subclasses should override this method if they can run asynchronously.
867
+ Returns:
868
+ The output of the ``Runnable``.
764
869
 
765
870
  """
766
871
  return await run_in_executor(config, self.invoke, input, config, **kwargs)
@@ -780,6 +885,20 @@ class Runnable(ABC, Generic[Input, Output]):
780
885
  Subclasses should override this method if they can batch more efficiently;
781
886
  e.g., if the underlying ``Runnable`` uses an API which supports a batch mode.
782
887
 
888
+ Args:
889
+ inputs: A list of inputs to the ``Runnable``.
890
+ config: A config to use when invoking the ``Runnable``.
891
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
892
+ tracing purposes, ``'max_concurrency'`` for controlling how much work
893
+ to do in parallel, and other keys. Please refer to the
894
+ ``RunnableConfig`` for more details. Defaults to None.
895
+ return_exceptions: Whether to return exceptions instead of raising them.
896
+ Defaults to False.
897
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
898
+
899
+ Returns:
900
+ A list of outputs from the ``Runnable``.
901
+
783
902
  """
784
903
  if not inputs:
785
904
  return []
@@ -834,6 +953,20 @@ class Runnable(ABC, Generic[Input, Output]):
834
953
 
835
954
  Yields results as they complete.
836
955
 
956
+ Args:
957
+ inputs: A list of inputs to the ``Runnable``.
958
+ config: A config to use when invoking the ``Runnable``.
959
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
960
+ tracing purposes, ``'max_concurrency'`` for controlling how much work to
961
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
962
+ for more details. Defaults to None.
963
+ return_exceptions: Whether to return exceptions instead of raising them.
964
+ Defaults to False.
965
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
966
+
967
+ Yields:
968
+ Tuples of the index of the input and the output from the ``Runnable``.
969
+
837
970
  """
838
971
  if not inputs:
839
972
  return
@@ -898,7 +1031,7 @@ class Runnable(ABC, Generic[Input, Output]):
898
1031
  for more details. Defaults to None.
899
1032
  return_exceptions: Whether to return exceptions instead of raising them.
900
1033
  Defaults to False.
901
- kwargs: Additional keyword arguments to pass to the ``Runnable``.
1034
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
902
1035
 
903
1036
  Returns:
904
1037
  A list of outputs from the ``Runnable``.
@@ -1120,11 +1253,6 @@ class Runnable(ABC, Generic[Input, Output]):
1120
1253
  A ``RunLogPatch`` or ``RunLog`` object.
1121
1254
 
1122
1255
  """
1123
- from langchain_core.tracers.log_stream import (
1124
- LogStreamCallbackHandler,
1125
- _astream_log_implementation,
1126
- )
1127
-
1128
1256
  stream = LogStreamCallbackHandler(
1129
1257
  auto_close=False,
1130
1258
  include_names=include_names,
@@ -1254,6 +1382,7 @@ class Runnable(ABC, Generic[Input, Output]):
1254
1382
  '''Format the docs.'''
1255
1383
  return ", ".join([doc.page_content for doc in docs])
1256
1384
 
1385
+
1257
1386
  format_docs = RunnableLambda(format_docs)
1258
1387
 
1259
1388
  ``some_tool``:
@@ -1280,9 +1409,11 @@ class Runnable(ABC, Generic[Input, Output]):
1280
1409
 
1281
1410
  from langchain_core.runnables import RunnableLambda
1282
1411
 
1412
+
1283
1413
  async def reverse(s: str) -> str:
1284
1414
  return s[::-1]
1285
1415
 
1416
+
1286
1417
  chain = RunnableLambda(func=reverse)
1287
1418
 
1288
1419
  events = [
@@ -1375,11 +1506,6 @@ class Runnable(ABC, Generic[Input, Output]):
1375
1506
  NotImplementedError: If the version is not ``'v1'`` or ``'v2'``.
1376
1507
 
1377
1508
  """ # noqa: E501
1378
- from langchain_core.tracers.event_stream import (
1379
- _astream_events_implementation_v1,
1380
- _astream_events_implementation_v2,
1381
- )
1382
-
1383
1509
  if version == "v2":
1384
1510
  event_stream = _astream_events_implementation_v2(
1385
1511
  self,
@@ -1422,7 +1548,9 @@ class Runnable(ABC, Generic[Input, Output]):
1422
1548
  config: Optional[RunnableConfig] = None,
1423
1549
  **kwargs: Optional[Any],
1424
1550
  ) -> Iterator[Output]:
1425
- """Default implementation of transform, which buffers input and calls ``astream``.
1551
+ """Transform inputs to outputs.
1552
+
1553
+ Default implementation of transform, which buffers input and calls ``astream``.
1426
1554
 
1427
1555
  Subclasses should override this method if they can start producing output while
1428
1556
  input is still being generated.
@@ -1435,7 +1563,7 @@ class Runnable(ABC, Generic[Input, Output]):
1435
1563
  Yields:
1436
1564
  The output of the ``Runnable``.
1437
1565
 
1438
- """ # noqa: E501
1566
+ """
1439
1567
  final: Input
1440
1568
  got_first_val = False
1441
1569
 
@@ -1465,7 +1593,9 @@ class Runnable(ABC, Generic[Input, Output]):
1465
1593
  config: Optional[RunnableConfig] = None,
1466
1594
  **kwargs: Optional[Any],
1467
1595
  ) -> AsyncIterator[Output]:
1468
- """Default implementation of atransform, which buffers input and calls ``astream``.
1596
+ """Transform inputs to outputs.
1597
+
1598
+ Default implementation of atransform, which buffers input and calls ``astream``.
1469
1599
 
1470
1600
  Subclasses should override this method if they can start producing output while
1471
1601
  input is still being generated.
@@ -1478,7 +1608,7 @@ class Runnable(ABC, Generic[Input, Output]):
1478
1608
  Yields:
1479
1609
  The output of the ``Runnable``.
1480
1610
 
1481
- """ # noqa: E501
1611
+ """
1482
1612
  final: Input
1483
1613
  got_first_val = False
1484
1614
 
@@ -1522,22 +1652,16 @@ class Runnable(ABC, Generic[Input, Output]):
1522
1652
  from langchain_ollama import ChatOllama
1523
1653
  from langchain_core.output_parsers import StrOutputParser
1524
1654
 
1525
- llm = ChatOllama(model='llama2')
1655
+ llm = ChatOllama(model="llama2")
1526
1656
 
1527
1657
  # Without bind.
1528
- chain = (
1529
- llm
1530
- | StrOutputParser()
1531
- )
1658
+ chain = llm | StrOutputParser()
1532
1659
 
1533
1660
  chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
1534
1661
  # Output is 'One two three four five.'
1535
1662
 
1536
1663
  # With bind.
1537
- chain = (
1538
- llm.bind(stop=["three"])
1539
- | StrOutputParser()
1540
- )
1664
+ chain = llm.bind(stop=["three"]) | StrOutputParser()
1541
1665
 
1542
1666
  chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
1543
1667
  # Output is 'One two'
@@ -1609,24 +1733,25 @@ class Runnable(ABC, Generic[Input, Output]):
1609
1733
 
1610
1734
  import time
1611
1735
 
1612
- def test_runnable(time_to_sleep : int):
1736
+
1737
+ def test_runnable(time_to_sleep: int):
1613
1738
  time.sleep(time_to_sleep)
1614
1739
 
1740
+
1615
1741
  def fn_start(run_obj: Run):
1616
1742
  print("start_time:", run_obj.start_time)
1617
1743
 
1744
+
1618
1745
  def fn_end(run_obj: Run):
1619
1746
  print("end_time:", run_obj.end_time)
1620
1747
 
1748
+
1621
1749
  chain = RunnableLambda(test_runnable).with_listeners(
1622
- on_start=fn_start,
1623
- on_end=fn_end
1750
+ on_start=fn_start, on_end=fn_end
1624
1751
  )
1625
1752
  chain.invoke(2)
1626
1753
 
1627
1754
  """
1628
- from langchain_core.tracers.root_listeners import RootListenersTracer
1629
-
1630
1755
  return RunnableBinding(
1631
1756
  bound=self,
1632
1757
  config_factories=[
@@ -1650,7 +1775,9 @@ class Runnable(ABC, Generic[Input, Output]):
1650
1775
  on_end: Optional[AsyncListener] = None,
1651
1776
  on_error: Optional[AsyncListener] = None,
1652
1777
  ) -> Runnable[Input, Output]:
1653
- """Bind async lifecycle listeners to a ``Runnable``, returning a new ``Runnable``.
1778
+ """Bind async lifecycle listeners to a ``Runnable``.
1779
+
1780
+ Returns a new ``Runnable``.
1654
1781
 
1655
1782
  The Run object contains information about the run, including its ``id``,
1656
1783
  ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
@@ -1716,9 +1843,7 @@ class Runnable(ABC, Generic[Input, Output]):
1716
1843
  on end callback ends at 2025-03-01T07:05:29.883893+00:00
1717
1844
  on end callback ends at 2025-03-01T07:05:30.884831+00:00
1718
1845
 
1719
- """ # noqa: E501
1720
- from langchain_core.tracers.root_listeners import AsyncRootListenersTracer
1721
-
1846
+ """
1722
1847
  return RunnableBinding(
1723
1848
  bound=self,
1724
1849
  config_factories=[
@@ -1796,7 +1921,7 @@ class Runnable(ABC, Generic[Input, Output]):
1796
1921
  if x == 1:
1797
1922
  raise ValueError("x is 1")
1798
1923
  else:
1799
- pass
1924
+ pass
1800
1925
 
1801
1926
 
1802
1927
  runnable = RunnableLambda(_lambda)
@@ -1808,10 +1933,11 @@ class Runnable(ABC, Generic[Input, Output]):
1808
1933
  except ValueError:
1809
1934
  pass
1810
1935
 
1811
- assert (count == 2)
1936
+ assert count == 2
1812
1937
 
1813
1938
  """
1814
- from langchain_core.runnables.retry import RunnableRetry
1939
+ # Import locally to prevent circular import
1940
+ from langchain_core.runnables.retry import RunnableRetry # noqa: PLC0415
1815
1941
 
1816
1942
  return RunnableRetry(
1817
1943
  bound=self,
@@ -1837,11 +1963,13 @@ class Runnable(ABC, Generic[Input, Output]):
1837
1963
 
1838
1964
  from langchain_core.runnables import RunnableLambda
1839
1965
 
1966
+
1840
1967
  def _lambda(x: int) -> int:
1841
1968
  return x + 1
1842
1969
 
1970
+
1843
1971
  runnable = RunnableLambda(_lambda)
1844
- print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
1972
+ print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
1845
1973
 
1846
1974
  """
1847
1975
  return RunnableEach(bound=self)
@@ -1859,13 +1987,15 @@ class Runnable(ABC, Generic[Input, Output]):
1859
1987
  in order, upon failures.
1860
1988
 
1861
1989
  Args:
1862
- fallbacks: A sequence of runnables to try if the original ``Runnable`` fails.
1990
+ fallbacks: A sequence of runnables to try if the original ``Runnable``
1991
+ fails.
1863
1992
  exceptions_to_handle: A tuple of exception types to handle.
1864
1993
  Defaults to ``(Exception,)``.
1865
1994
  exception_key: If string is specified then handled exceptions will be passed
1866
- to fallbacks as part of the input under the specified key. If None,
1867
- exceptions will not be passed to fallbacks. If used, the base ``Runnable``
1868
- and its fallbacks must accept a dictionary as input. Defaults to None.
1995
+ to fallbacks as part of the input under the specified key.
1996
+ If None, exceptions will not be passed to fallbacks.
1997
+ If used, the base ``Runnable`` and its fallbacks must accept a
1998
+ dictionary as input. Defaults to None.
1869
1999
 
1870
2000
  Returns:
1871
2001
  A new ``Runnable`` that will try the original ``Runnable``, and then each
@@ -1891,23 +2021,28 @@ class Runnable(ABC, Generic[Input, Output]):
1891
2021
 
1892
2022
  runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
1893
2023
  [RunnableGenerator(_generate)]
1894
- )
1895
- print(''.join(runnable.stream({}))) #foo bar
2024
+ )
2025
+ print("".join(runnable.stream({}))) # foo bar
1896
2026
 
1897
2027
  Args:
1898
- fallbacks: A sequence of runnables to try if the original ``Runnable`` fails.
2028
+ fallbacks: A sequence of runnables to try if the original ``Runnable``
2029
+ fails.
1899
2030
  exceptions_to_handle: A tuple of exception types to handle.
1900
2031
  exception_key: If string is specified then handled exceptions will be passed
1901
- to fallbacks as part of the input under the specified key. If None,
1902
- exceptions will not be passed to fallbacks. If used, the base ``Runnable``
1903
- and its fallbacks must accept a dictionary as input.
2032
+ to fallbacks as part of the input under the specified key.
2033
+ If None, exceptions will not be passed to fallbacks.
2034
+ If used, the base ``Runnable`` and its fallbacks must accept a
2035
+ dictionary as input.
1904
2036
 
1905
2037
  Returns:
1906
2038
  A new ``Runnable`` that will try the original ``Runnable``, and then each
1907
2039
  fallback in order, upon failures.
1908
2040
 
1909
- """ # noqa: E501
1910
- from langchain_core.runnables.fallbacks import RunnableWithFallbacks
2041
+ """
2042
+ # Import locally to prevent circular import
2043
+ from langchain_core.runnables.fallbacks import ( # noqa: PLC0415
2044
+ RunnableWithFallbacks,
2045
+ )
1911
2046
 
1912
2047
  return RunnableWithFallbacks(
1913
2048
  runnable=self,
@@ -1931,11 +2066,14 @@ class Runnable(ABC, Generic[Input, Output]):
1931
2066
  serialized: Optional[dict[str, Any]] = None,
1932
2067
  **kwargs: Optional[Any],
1933
2068
  ) -> Output:
1934
- """Helper method to transform an ``Input`` value to an ``Output`` value, with callbacks.
2069
+ """Call with config.
2070
+
2071
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2072
+ with callbacks.
1935
2073
 
1936
2074
  Use this method to implement ``invoke`` in subclasses.
1937
2075
 
1938
- """ # noqa: E501
2076
+ """
1939
2077
  config = ensure_config(config)
1940
2078
  callback_manager = get_callback_manager_for_config(config)
1941
2079
  run_manager = callback_manager.on_chain_start(
@@ -1982,10 +2120,13 @@ class Runnable(ABC, Generic[Input, Output]):
1982
2120
  serialized: Optional[dict[str, Any]] = None,
1983
2121
  **kwargs: Optional[Any],
1984
2122
  ) -> Output:
1985
- """Helper method to transform an ``Input`` value to an ``Output`` value, with callbacks.
2123
+ """Async call with config.
2124
+
2125
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2126
+ with callbacks.
1986
2127
 
1987
2128
  Use this method to implement ``ainvoke`` in subclasses.
1988
- """ # noqa: E501
2129
+ """
1989
2130
  config = ensure_config(config)
1990
2131
  callback_manager = get_async_callback_manager_for_config(config)
1991
2132
  run_manager = await callback_manager.on_chain_start(
@@ -2187,9 +2328,6 @@ class Runnable(ABC, Generic[Input, Output]):
2187
2328
  Use this to implement ``stream`` or ``transform`` in ``Runnable`` subclasses.
2188
2329
 
2189
2330
  """
2190
- # Mixin that is used by both astream log and astream events implementation
2191
- from langchain_core.tracers._streaming import _StreamingCallbackHandler
2192
-
2193
2331
  # tee the input so we can iterate over it twice
2194
2332
  input_for_tracing, input_for_transform = tee(inputs, 2)
2195
2333
  # Start the input iterator to ensure the input Runnable starts before this one
@@ -2293,9 +2431,6 @@ class Runnable(ABC, Generic[Input, Output]):
2293
2431
  Use this to implement ``astream`` or ``atransform`` in ``Runnable`` subclasses.
2294
2432
 
2295
2433
  """
2296
- # Mixin that is used by both astream log and astream events implementation
2297
- from langchain_core.tracers._streaming import _StreamingCallbackHandler
2298
-
2299
2434
  # tee the input so we can iterate over it twice
2300
2435
  input_for_tracing, input_for_transform = atee(inputs, 2)
2301
2436
  # Start the input iterator to ensure the input Runnable starts before this one
@@ -2411,13 +2546,16 @@ class Runnable(ABC, Generic[Input, Output]):
2411
2546
  from typing_extensions import TypedDict
2412
2547
  from langchain_core.runnables import RunnableLambda
2413
2548
 
2549
+
2414
2550
  class Args(TypedDict):
2415
2551
  a: int
2416
2552
  b: list[int]
2417
2553
 
2554
+
2418
2555
  def f(x: Args) -> str:
2419
2556
  return str(x["a"] * max(x["b"]))
2420
2557
 
2558
+
2421
2559
  runnable = RunnableLambda(f)
2422
2560
  as_tool = runnable.as_tool()
2423
2561
  as_tool.invoke({"a": 3, "b": [1, 2]})
@@ -2450,9 +2588,11 @@ class Runnable(ABC, Generic[Input, Output]):
2450
2588
  from typing import Any
2451
2589
  from langchain_core.runnables import RunnableLambda
2452
2590
 
2591
+
2453
2592
  def f(x: dict[str, Any]) -> str:
2454
2593
  return str(x["a"] * max(x["b"]))
2455
2594
 
2595
+
2456
2596
  runnable = RunnableLambda(f)
2457
2597
  as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]})
2458
2598
  as_tool.invoke({"a": 3, "b": [1, 2]})
@@ -2463,12 +2603,15 @@ class Runnable(ABC, Generic[Input, Output]):
2463
2603
 
2464
2604
  from langchain_core.runnables import RunnableLambda
2465
2605
 
2606
+
2466
2607
  def f(x: str) -> str:
2467
2608
  return x + "a"
2468
2609
 
2610
+
2469
2611
  def g(x: str) -> str:
2470
2612
  return x + "z"
2471
2613
 
2614
+
2472
2615
  runnable = RunnableLambda(f) | g
2473
2616
  as_tool = runnable.as_tool()
2474
2617
  as_tool.invoke("b")
@@ -2477,7 +2620,7 @@ class Runnable(ABC, Generic[Input, Output]):
2477
2620
 
2478
2621
  """
2479
2622
  # Avoid circular import
2480
- from langchain_core.tools import convert_runnable_to_tool
2623
+ from langchain_core.tools import convert_runnable_to_tool # noqa: PLC0415
2481
2624
 
2482
2625
  return convert_runnable_to_tool(
2483
2626
  self,
@@ -2520,6 +2663,9 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2520
2663
  Args:
2521
2664
  **kwargs: A dictionary of ``ConfigurableField`` instances to configure.
2522
2665
 
2666
+ Raises:
2667
+ ValueError: If a configuration key is not found in the ``Runnable``.
2668
+
2523
2669
  Returns:
2524
2670
  A new ``Runnable`` with the fields configured.
2525
2671
 
@@ -2538,18 +2684,22 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2538
2684
 
2539
2685
  # max_tokens = 20
2540
2686
  print(
2541
- "max_tokens_20: ",
2542
- model.invoke("tell me something about chess").content
2687
+ "max_tokens_20: ", model.invoke("tell me something about chess").content
2543
2688
  )
2544
2689
 
2545
2690
  # max_tokens = 200
2546
- print("max_tokens_200: ", model.with_config(
2547
- configurable={"output_token_number": 200}
2548
- ).invoke("tell me something about chess").content
2691
+ print(
2692
+ "max_tokens_200: ",
2693
+ model.with_config(configurable={"output_token_number": 200})
2694
+ .invoke("tell me something about chess")
2695
+ .content,
2549
2696
  )
2550
2697
 
2551
2698
  """
2552
- from langchain_core.runnables.configurable import RunnableConfigurableFields
2699
+ # Import locally to prevent circular import
2700
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
2701
+ RunnableConfigurableFields,
2702
+ )
2553
2703
 
2554
2704
  model_fields = type(self).model_fields
2555
2705
  for key in kwargs:
@@ -2596,7 +2746,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2596
2746
  ).configurable_alternatives(
2597
2747
  ConfigurableField(id="llm"),
2598
2748
  default_key="anthropic",
2599
- openai=ChatOpenAI()
2749
+ openai=ChatOpenAI(),
2600
2750
  )
2601
2751
 
2602
2752
  # uses the default model ChatAnthropic
@@ -2604,13 +2754,14 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2604
2754
 
2605
2755
  # uses ChatOpenAI
2606
2756
  print(
2607
- model.with_config(
2608
- configurable={"llm": "openai"}
2609
- ).invoke("which organization created you?").content
2757
+ model.with_config(configurable={"llm": "openai"})
2758
+ .invoke("which organization created you?")
2759
+ .content
2610
2760
  )
2611
2761
 
2612
2762
  """
2613
- from langchain_core.runnables.configurable import (
2763
+ # Import locally to prevent circular import
2764
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
2614
2765
  RunnableConfigurableAlternatives,
2615
2766
  )
2616
2767
 
@@ -2626,7 +2777,11 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2626
2777
  def _seq_input_schema(
2627
2778
  steps: list[Runnable[Any, Any]], config: Optional[RunnableConfig]
2628
2779
  ) -> type[BaseModel]:
2629
- from langchain_core.runnables.passthrough import RunnableAssign, RunnablePick
2780
+ # Import locally to prevent circular import
2781
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
2782
+ RunnableAssign,
2783
+ RunnablePick,
2784
+ )
2630
2785
 
2631
2786
  first = steps[0]
2632
2787
  if len(steps) == 1:
@@ -2652,7 +2807,11 @@ def _seq_input_schema(
2652
2807
  def _seq_output_schema(
2653
2808
  steps: list[Runnable[Any, Any]], config: Optional[RunnableConfig]
2654
2809
  ) -> type[BaseModel]:
2655
- from langchain_core.runnables.passthrough import RunnableAssign, RunnablePick
2810
+ # Import locally to prevent circular import
2811
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
2812
+ RunnableAssign,
2813
+ RunnablePick,
2814
+ )
2656
2815
 
2657
2816
  last = steps[-1]
2658
2817
  if len(steps) == 1:
@@ -2739,12 +2898,15 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2739
2898
 
2740
2899
  from langchain_core.runnables import RunnableLambda
2741
2900
 
2901
+
2742
2902
  def add_one(x: int) -> int:
2743
2903
  return x + 1
2744
2904
 
2905
+
2745
2906
  def mul_two(x: int) -> int:
2746
2907
  return x * 2
2747
2908
 
2909
+
2748
2910
  runnable_1 = RunnableLambda(add_one)
2749
2911
  runnable_2 = RunnableLambda(mul_two)
2750
2912
  sequence = runnable_1 | runnable_2
@@ -2764,17 +2926,17 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2764
2926
  from langchain_openai import ChatOpenAI
2765
2927
 
2766
2928
  prompt = PromptTemplate.from_template(
2767
- 'In JSON format, give me a list of {topic} and their '
2768
- 'corresponding names in French, Spanish and in a '
2769
- 'Cat Language.'
2929
+ "In JSON format, give me a list of {topic} and their "
2930
+ "corresponding names in French, Spanish and in a "
2931
+ "Cat Language."
2770
2932
  )
2771
2933
 
2772
2934
  model = ChatOpenAI()
2773
2935
  chain = prompt | model | SimpleJsonOutputParser()
2774
2936
 
2775
- async for chunk in chain.astream({'topic': 'colors'}):
2776
- print('-') # noqa: T201
2777
- print(chunk, sep='', flush=True) # noqa: T201
2937
+ async for chunk in chain.astream({"topic": "colors"}):
2938
+ print("-") # noqa: T201
2939
+ print(chunk, sep="", flush=True) # noqa: T201
2778
2940
 
2779
2941
  """
2780
2942
 
@@ -2829,6 +2991,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2829
2991
  @classmethod
2830
2992
  @override
2831
2993
  def get_lc_namespace(cls) -> list[str]:
2994
+ """Get the namespace of the langchain object.
2995
+
2996
+ Returns:
2997
+ ``["langchain", "schema", "runnable"]``
2998
+ """
2832
2999
  return ["langchain", "schema", "runnable"]
2833
3000
 
2834
3001
  @property
@@ -2843,14 +3010,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2843
3010
  @classmethod
2844
3011
  @override
2845
3012
  def is_lc_serializable(cls) -> bool:
2846
- """Check if the object is serializable.
2847
-
2848
- Returns:
2849
- True if the object is serializable, False otherwise.
2850
-
2851
- Defaults to True.
2852
-
2853
- """
3013
+ """Return True as this class is serializable."""
2854
3014
  return True
2855
3015
 
2856
3016
  model_config = ConfigDict(
@@ -2908,49 +3068,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2908
3068
  The config specs of the ``Runnable``.
2909
3069
 
2910
3070
  """
2911
- from langchain_core.beta.runnables.context import (
2912
- CONTEXT_CONFIG_PREFIX,
2913
- _key_from_id,
2914
- )
2915
-
2916
- # get all specs
2917
- all_specs = [
2918
- (spec, idx)
2919
- for idx, step in enumerate(self.steps)
2920
- for spec in step.config_specs
2921
- ]
2922
- # calculate context dependencies
2923
- specs_by_pos = groupby(
2924
- [tup for tup in all_specs if tup[0].id.startswith(CONTEXT_CONFIG_PREFIX)],
2925
- itemgetter(1),
3071
+ # Import locally to prevent circular import
3072
+ return get_unique_config_specs(
3073
+ [spec for step in self.steps for spec in step.config_specs]
2926
3074
  )
2927
- next_deps: set[str] = set()
2928
- deps_by_pos: dict[int, set[str]] = {}
2929
- for pos, specs in specs_by_pos:
2930
- deps_by_pos[pos] = next_deps
2931
- next_deps = next_deps | {spec[0].id for spec in specs}
2932
- # assign context dependencies
2933
- for pos, (spec, idx) in enumerate(all_specs):
2934
- if spec.id.startswith(CONTEXT_CONFIG_PREFIX):
2935
- all_specs[pos] = (
2936
- ConfigurableFieldSpec(
2937
- id=spec.id,
2938
- annotation=spec.annotation,
2939
- name=spec.name,
2940
- default=spec.default,
2941
- description=spec.description,
2942
- is_shared=spec.is_shared,
2943
- dependencies=[
2944
- d
2945
- for d in deps_by_pos[idx]
2946
- if _key_from_id(d) != _key_from_id(spec.id)
2947
- ]
2948
- + (spec.dependencies or []),
2949
- ),
2950
- idx,
2951
- )
2952
-
2953
- return get_unique_config_specs(spec for spec, _ in all_specs)
2954
3075
 
2955
3076
  @override
2956
3077
  def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
@@ -2966,7 +3087,8 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2966
3087
  ValueError: If a ``Runnable`` has no first or last node.
2967
3088
 
2968
3089
  """
2969
- from langchain_core.runnables.graph import Graph
3090
+ # Import locally to prevent circular import
3091
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
2970
3092
 
2971
3093
  graph = Graph()
2972
3094
  for step in self.steps:
@@ -3054,10 +3176,8 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3054
3176
  def invoke(
3055
3177
  self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
3056
3178
  ) -> Output:
3057
- from langchain_core.beta.runnables.context import config_with_context
3058
-
3059
3179
  # setup callbacks and context
3060
- config = config_with_context(ensure_config(config), self.steps)
3180
+ config = ensure_config(config)
3061
3181
  callback_manager = get_callback_manager_for_config(config)
3062
3182
  # start the root run
3063
3183
  run_manager = callback_manager.on_chain_start(
@@ -3095,10 +3215,8 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3095
3215
  config: Optional[RunnableConfig] = None,
3096
3216
  **kwargs: Optional[Any],
3097
3217
  ) -> Output:
3098
- from langchain_core.beta.runnables.context import aconfig_with_context
3099
-
3100
3218
  # setup callbacks and context
3101
- config = aconfig_with_context(ensure_config(config), self.steps)
3219
+ config = ensure_config(config)
3102
3220
  callback_manager = get_async_callback_manager_for_config(config)
3103
3221
  # start the root run
3104
3222
  run_manager = await callback_manager.on_chain_start(
@@ -3139,17 +3257,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3139
3257
  return_exceptions: bool = False,
3140
3258
  **kwargs: Optional[Any],
3141
3259
  ) -> list[Output]:
3142
- from langchain_core.beta.runnables.context import config_with_context
3143
- from langchain_core.callbacks.manager import CallbackManager
3144
-
3145
3260
  if not inputs:
3146
3261
  return []
3147
3262
 
3148
3263
  # setup callbacks and context
3149
- configs = [
3150
- config_with_context(c, self.steps)
3151
- for c in get_config_list(config, len(inputs))
3152
- ]
3264
+ configs = get_config_list(config, len(inputs))
3153
3265
  callback_managers = [
3154
3266
  CallbackManager.configure(
3155
3267
  inheritable_callbacks=config.get("callbacks"),
@@ -3269,17 +3381,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3269
3381
  return_exceptions: bool = False,
3270
3382
  **kwargs: Optional[Any],
3271
3383
  ) -> list[Output]:
3272
- from langchain_core.beta.runnables.context import aconfig_with_context
3273
- from langchain_core.callbacks.manager import AsyncCallbackManager
3274
-
3275
3384
  if not inputs:
3276
3385
  return []
3277
3386
 
3278
3387
  # setup callbacks and context
3279
- configs = [
3280
- aconfig_with_context(c, self.steps)
3281
- for c in get_config_list(config, len(inputs))
3282
- ]
3388
+ configs = get_config_list(config, len(inputs))
3283
3389
  callback_managers = [
3284
3390
  AsyncCallbackManager.configure(
3285
3391
  inheritable_callbacks=config.get("callbacks"),
@@ -3400,11 +3506,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3400
3506
  config: RunnableConfig,
3401
3507
  **kwargs: Any,
3402
3508
  ) -> Iterator[Output]:
3403
- from langchain_core.beta.runnables.context import config_with_context
3404
-
3405
3509
  steps = [self.first, *self.middle, self.last]
3406
- config = config_with_context(config, self.steps)
3407
-
3408
3510
  # transform the input stream of each step with the next
3409
3511
  # steps that don't natively support transforming an input stream will
3410
3512
  # buffer input in memory until all available, and then start emitting output
@@ -3427,11 +3529,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3427
3529
  config: RunnableConfig,
3428
3530
  **kwargs: Any,
3429
3531
  ) -> AsyncIterator[Output]:
3430
- from langchain_core.beta.runnables.context import aconfig_with_context
3431
-
3432
3532
  steps = [self.first, *self.middle, self.last]
3433
- config = aconfig_with_context(config, self.steps)
3434
-
3435
3533
  # stream the last steps
3436
3534
  # transform the input stream of each step with the next
3437
3535
  # steps that don't natively support transforming an input stream will
@@ -3520,15 +3618,19 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3520
3618
 
3521
3619
  from langchain_core.runnables import RunnableLambda
3522
3620
 
3621
+
3523
3622
  def add_one(x: int) -> int:
3524
3623
  return x + 1
3525
3624
 
3625
+
3526
3626
  def mul_two(x: int) -> int:
3527
3627
  return x * 2
3528
3628
 
3629
+
3529
3630
  def mul_three(x: int) -> int:
3530
3631
  return x * 3
3531
3632
 
3633
+
3532
3634
  runnable_1 = RunnableLambda(add_one)
3533
3635
  runnable_2 = RunnableLambda(mul_two)
3534
3636
  runnable_3 = RunnableLambda(mul_three)
@@ -3564,8 +3666,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3564
3666
 
3565
3667
  model = ChatOpenAI()
3566
3668
  joke_chain = (
3567
- ChatPromptTemplate.from_template("tell me a joke about {topic}")
3568
- | model
3669
+ ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
3569
3670
  )
3570
3671
  poem_chain = (
3571
3672
  ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
@@ -3619,11 +3720,17 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3619
3720
  @classmethod
3620
3721
  @override
3621
3722
  def is_lc_serializable(cls) -> bool:
3723
+ """Return True as this class is serializable."""
3622
3724
  return True
3623
3725
 
3624
3726
  @classmethod
3625
3727
  @override
3626
3728
  def get_lc_namespace(cls) -> list[str]:
3729
+ """Get the namespace of the langchain object.
3730
+
3731
+ Returns:
3732
+ ``["langchain", "schema", "runnable"]``
3733
+ """
3627
3734
  return ["langchain", "schema", "runnable"]
3628
3735
 
3629
3736
  model_config = ConfigDict(
@@ -3731,7 +3838,8 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3731
3838
  ValueError: If a ``Runnable`` has no first or last node.
3732
3839
 
3733
3840
  """
3734
- from langchain_core.runnables.graph import Graph
3841
+ # Import locally to prevent circular import
3842
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
3735
3843
 
3736
3844
  graph = Graph()
3737
3845
  input_node = graph.add_node(self.get_input_schema(config))
@@ -3767,8 +3875,6 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3767
3875
  def invoke(
3768
3876
  self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
3769
3877
  ) -> dict[str, Any]:
3770
- from langchain_core.callbacks.manager import CallbackManager
3771
-
3772
3878
  # setup callbacks
3773
3879
  config = ensure_config(config)
3774
3880
  callback_manager = CallbackManager.configure(
@@ -4068,9 +4174,10 @@ class RunnableGenerator(Runnable[Input, Output]):
4068
4174
  for token in ["Have", " a", " nice", " day"]:
4069
4175
  yield token
4070
4176
 
4177
+
4071
4178
  runnable = RunnableGenerator(agen)
4072
4179
  await runnable.ainvoke(None) # "Have a nice day"
4073
- [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
4180
+ [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
4074
4181
 
4075
4182
  ``RunnableGenerator`` makes it easy to implement custom behavior within a streaming
4076
4183
  context. Below we show an example:
@@ -4090,6 +4197,7 @@ class RunnableGenerator(Runnable[Input, Output]):
4090
4197
  | StrOutputParser()
4091
4198
  )
4092
4199
 
4200
+
4093
4201
  def character_generator(input: Iterator[str]) -> Iterator[str]:
4094
4202
  for token in input:
4095
4203
  if "," in token or "." in token:
@@ -4100,7 +4208,10 @@ class RunnableGenerator(Runnable[Input, Output]):
4100
4208
 
4101
4209
  runnable = chant_chain | character_generator
4102
4210
  assert type(runnable.last) is RunnableGenerator
4103
- "".join(runnable.stream({"topic": "waste"})) # Reduce👏, Reuse👏, Recycle👏.
4211
+ "".join(
4212
+ runnable.stream({"topic": "waste"})
4213
+ ) # Reduce👏, Reuse👏, Recycle👏.
4214
+
4104
4215
 
4105
4216
  # Note that RunnableLambda can be used to delay streaming of one step in a
4106
4217
  # sequence until the previous step is finished:
@@ -4109,6 +4220,7 @@ class RunnableGenerator(Runnable[Input, Output]):
4109
4220
  for character in input[::-1]:
4110
4221
  yield character
4111
4222
 
4223
+
4112
4224
  runnable = chant_chain | RunnableLambda(reverse_generator)
4113
4225
  "".join(runnable.stream({"topic": "waste"})) # ".elcycer ,esuer ,ecudeR"
4114
4226
 
@@ -4353,26 +4465,29 @@ class RunnableLambda(Runnable[Input, Output]):
4353
4465
  # This is a RunnableLambda
4354
4466
  from langchain_core.runnables import RunnableLambda
4355
4467
 
4468
+
4356
4469
  def add_one(x: int) -> int:
4357
4470
  return x + 1
4358
4471
 
4472
+
4359
4473
  runnable = RunnableLambda(add_one)
4360
4474
 
4361
- runnable.invoke(1) # returns 2
4362
- runnable.batch([1, 2, 3]) # returns [2, 3, 4]
4475
+ runnable.invoke(1) # returns 2
4476
+ runnable.batch([1, 2, 3]) # returns [2, 3, 4]
4363
4477
 
4364
4478
  # Async is supported by default by delegating to the sync implementation
4365
- await runnable.ainvoke(1) # returns 2
4366
- await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
4479
+ await runnable.ainvoke(1) # returns 2
4480
+ await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
4367
4481
 
4368
4482
 
4369
4483
  # Alternatively, can provide both synd and sync implementations
4370
4484
  async def add_one_async(x: int) -> int:
4371
4485
  return x + 1
4372
4486
 
4487
+
4373
4488
  runnable = RunnableLambda(add_one, afunc=add_one_async)
4374
- runnable.invoke(1) # Uses add_one
4375
- await runnable.ainvoke(1) # Uses add_one_async
4489
+ runnable.invoke(1) # Uses add_one
4490
+ await runnable.ainvoke(1) # Uses add_one_async
4376
4491
 
4377
4492
  """
4378
4493
 
@@ -4607,6 +4722,9 @@ class RunnableLambda(Runnable[Input, Output]):
4607
4722
  @override
4608
4723
  def get_graph(self, config: RunnableConfig | None = None) -> Graph:
4609
4724
  if deps := self.deps:
4725
+ # Import locally to prevent circular import
4726
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
4727
+
4610
4728
  graph = Graph()
4611
4729
  input_node = graph.add_node(self.get_input_schema(config))
4612
4730
  output_node = graph.add_node(self.get_output_schema(config))
@@ -4644,7 +4762,7 @@ class RunnableLambda(Runnable[Input, Output]):
4644
4762
  __hash__ = None # type: ignore[assignment]
4645
4763
 
4646
4764
  def __repr__(self) -> str:
4647
- """A string representation of this ``Runnable``."""
4765
+ """Return a string representation of this ``Runnable``."""
4648
4766
  if self._repr is None:
4649
4767
  if hasattr(self, "func") and isinstance(self.func, itemgetter):
4650
4768
  self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})"
@@ -5080,13 +5198,16 @@ class RunnableLambda(Runnable[Input, Output]):
5080
5198
 
5081
5199
 
5082
5200
  class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5083
- """``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5201
+ """RunnableEachBase class.
5202
+
5203
+ ``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5084
5204
 
5085
- Use only if creating a new ``RunnableEach`` subclass with different ``__init__`` args.
5205
+ Use only if creating a new ``RunnableEach`` subclass with different ``__init__``
5206
+ args.
5086
5207
 
5087
5208
  See documentation for ``RunnableEach`` for more details.
5088
5209
 
5089
- """ # noqa: E501
5210
+ """
5090
5211
 
5091
5212
  bound: Runnable[Input, Output]
5092
5213
 
@@ -5154,11 +5275,17 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5154
5275
  @classmethod
5155
5276
  @override
5156
5277
  def is_lc_serializable(cls) -> bool:
5278
+ """Return True as this class is serializable."""
5157
5279
  return True
5158
5280
 
5159
5281
  @classmethod
5160
5282
  @override
5161
5283
  def get_lc_namespace(cls) -> list[str]:
5284
+ """Get the namespace of the langchain object.
5285
+
5286
+ Returns:
5287
+ ``["langchain", "schema", "runnable"]``
5288
+ """
5162
5289
  return ["langchain", "schema", "runnable"]
5163
5290
 
5164
5291
  def _invoke(
@@ -5204,14 +5331,19 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5204
5331
  config: Optional[RunnableConfig] = None,
5205
5332
  **kwargs: Optional[Any],
5206
5333
  ) -> AsyncIterator[StreamEvent]:
5334
+ def _error_stream_event(message: str) -> StreamEvent:
5335
+ raise NotImplementedError(message)
5336
+
5207
5337
  for _ in range(1):
5208
- msg = "RunnableEach does not support astream_events yet."
5209
- raise NotImplementedError(msg)
5210
- yield
5338
+ yield _error_stream_event(
5339
+ "RunnableEach does not support astream_events yet."
5340
+ )
5211
5341
 
5212
5342
 
5213
5343
  class RunnableEach(RunnableEachBase[Input, Output]):
5214
- """``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5344
+ """RunnableEach class.
5345
+
5346
+ ``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5215
5347
 
5216
5348
  It allows you to call multiple inputs with the bounded ``Runnable``.
5217
5349
 
@@ -5236,7 +5368,7 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5236
5368
  {'topic':'Biology'}])
5237
5369
  print(output) # noqa: T201
5238
5370
 
5239
- """ # noqa: E501
5371
+ """
5240
5372
 
5241
5373
  @override
5242
5374
  def get_name(
@@ -5300,7 +5432,9 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5300
5432
  on_end: Optional[AsyncListener] = None,
5301
5433
  on_error: Optional[AsyncListener] = None,
5302
5434
  ) -> RunnableEach[Input, Output]:
5303
- """Bind async lifecycle listeners to a ``Runnable``, returning a new ``Runnable``.
5435
+ """Bind async lifecycle listeners to a ``Runnable``.
5436
+
5437
+ Returns a new ``Runnable``.
5304
5438
 
5305
5439
  The ``Run`` object contains information about the run, including its ``id``,
5306
5440
  ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
@@ -5317,7 +5451,7 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5317
5451
  Returns:
5318
5452
  A new ``Runnable`` with the listeners bound.
5319
5453
 
5320
- """ # noqa: E501
5454
+ """
5321
5455
  return RunnableEach(
5322
5456
  bound=self.bound.with_alisteners(
5323
5457
  on_start=on_start, on_end=on_end, on_error=on_error
@@ -5388,22 +5522,23 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
5388
5522
  """Create a ``RunnableBinding`` from a ``Runnable`` and kwargs.
5389
5523
 
5390
5524
  Args:
5391
- bound: The underlying ``Runnable`` that this ``Runnable`` delegates calls to.
5525
+ bound: The underlying ``Runnable`` that this ``Runnable`` delegates calls
5526
+ to.
5392
5527
  kwargs: optional kwargs to pass to the underlying ``Runnable``, when running
5393
- the underlying ``Runnable`` (e.g., via ``invoke``, ``batch``,
5394
- ``transform``, or ``stream`` or async variants)
5395
- Defaults to None.
5528
+ the underlying ``Runnable`` (e.g., via ``invoke``, ``batch``,
5529
+ ``transform``, or ``stream`` or async variants)
5530
+ Defaults to None.
5396
5531
  config: optional config to bind to the underlying ``Runnable``.
5397
- Defaults to None.
5532
+ Defaults to None.
5398
5533
  config_factories: optional list of config factories to apply to the
5399
- config before binding to the underlying ``Runnable``.
5400
- Defaults to None.
5534
+ config before binding to the underlying ``Runnable``.
5535
+ Defaults to None.
5401
5536
  custom_input_type: Specify to override the input type of the underlying
5402
- ``Runnable`` with a custom type. Defaults to None.
5537
+ ``Runnable`` with a custom type. Defaults to None.
5403
5538
  custom_output_type: Specify to override the output type of the underlying
5404
- ``Runnable`` with a custom type. Defaults to None.
5539
+ ``Runnable`` with a custom type. Defaults to None.
5405
5540
  **other_kwargs: Unpacked into the base class.
5406
- """ # noqa: E501
5541
+ """
5407
5542
  super().__init__(
5408
5543
  bound=bound,
5409
5544
  kwargs=kwargs or {},
@@ -5470,6 +5605,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
5470
5605
  @classmethod
5471
5606
  @override
5472
5607
  def is_lc_serializable(cls) -> bool:
5608
+ """Return True as this class is serializable."""
5473
5609
  return True
5474
5610
 
5475
5611
  @classmethod
@@ -5477,7 +5613,8 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
5477
5613
  def get_lc_namespace(cls) -> list[str]:
5478
5614
  """Get the namespace of the langchain object.
5479
5615
 
5480
- Defaults to ``["langchain", "schema", "runnable"]``.
5616
+ Returns:
5617
+ ``["langchain", "schema", "runnable"]``
5481
5618
  """
5482
5619
  return ["langchain", "schema", "runnable"]
5483
5620
 
@@ -5744,9 +5881,11 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
5744
5881
  These methods include:
5745
5882
 
5746
5883
  - ``bind``: Bind kwargs to pass to the underlying ``Runnable`` when running it.
5747
- - ``with_config``: Bind config to pass to the underlying ``Runnable`` when running it.
5884
+ - ``with_config``: Bind config to pass to the underlying ``Runnable`` when running
5885
+ it.
5748
5886
  - ``with_listeners``: Bind lifecycle listeners to the underlying ``Runnable``.
5749
- - ``with_types``: Override the input and output types of the underlying ``Runnable``.
5887
+ - ``with_types``: Override the input and output types of the underlying
5888
+ ``Runnable``.
5750
5889
  - ``with_retry``: Bind a retry policy to the underlying ``Runnable``.
5751
5890
  - ``with_fallbacks``: Bind a fallback policy to the underlying ``Runnable``.
5752
5891
 
@@ -5758,12 +5897,13 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
5758
5897
  # Create a Runnable binding that invokes the ChatModel with the
5759
5898
  # additional kwarg `stop=['-']` when running it.
5760
5899
  from langchain_community.chat_models import ChatOpenAI
5900
+
5761
5901
  model = ChatOpenAI()
5762
- model.invoke('Say "Parrot-MAGIC"', stop=['-']) # Should return `Parrot`
5902
+ model.invoke('Say "Parrot-MAGIC"', stop=["-"]) # Should return `Parrot`
5763
5903
  # Using it the easy way via `bind` method which returns a new
5764
5904
  # RunnableBinding
5765
- runnable_binding = model.bind(stop=['-'])
5766
- runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5905
+ runnable_binding = model.bind(stop=["-"])
5906
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5767
5907
 
5768
5908
  Can also be done by instantiating a ``RunnableBinding`` directly (not
5769
5909
  recommended):
@@ -5771,13 +5911,14 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
5771
5911
  .. code-block:: python
5772
5912
 
5773
5913
  from langchain_core.runnables import RunnableBinding
5914
+
5774
5915
  runnable_binding = RunnableBinding(
5775
5916
  bound=model,
5776
- kwargs={'stop': ['-']} # <-- Note the additional kwargs
5917
+ kwargs={"stop": ["-"]}, # <-- Note the additional kwargs
5777
5918
  )
5778
- runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5919
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5779
5920
 
5780
- """ # noqa: E501
5921
+ """
5781
5922
 
5782
5923
  @override
5783
5924
  def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
@@ -5847,7 +5988,6 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
5847
5988
  Returns:
5848
5989
  A new ``Runnable`` with the listeners bound.
5849
5990
  """
5850
- from langchain_core.tracers.root_listeners import RootListenersTracer
5851
5991
 
5852
5992
  def listener_config_factory(config: RunnableConfig) -> RunnableConfig:
5853
5993
  return {
@@ -6050,6 +6190,7 @@ def chain(
6050
6190
  from langchain_core.prompts import PromptTemplate
6051
6191
  from langchain_openai import OpenAI
6052
6192
 
6193
+
6053
6194
  @chain
6054
6195
  def my_func(fields):
6055
6196
  prompt = PromptTemplate("Hello, {name}!")