langchain-core 0.3.74__py3-none-any.whl → 0.3.76__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 (122) hide show
  1. langchain_core/_api/beta_decorator.py +18 -41
  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/beta/runnables/context.py +2 -3
  7. langchain_core/callbacks/base.py +11 -4
  8. langchain_core/callbacks/file.py +13 -2
  9. langchain_core/callbacks/manager.py +129 -78
  10. langchain_core/callbacks/usage.py +4 -2
  11. langchain_core/chat_history.py +10 -12
  12. langchain_core/document_loaders/base.py +34 -9
  13. langchain_core/document_loaders/langsmith.py +3 -0
  14. langchain_core/documents/base.py +36 -11
  15. langchain_core/documents/compressor.py +9 -6
  16. langchain_core/documents/transformers.py +4 -2
  17. langchain_core/embeddings/fake.py +8 -5
  18. langchain_core/env.py +2 -3
  19. langchain_core/example_selectors/base.py +12 -0
  20. langchain_core/exceptions.py +7 -0
  21. langchain_core/globals.py +17 -28
  22. langchain_core/indexing/api.py +56 -44
  23. langchain_core/indexing/base.py +7 -10
  24. langchain_core/indexing/in_memory.py +23 -3
  25. langchain_core/language_models/__init__.py +3 -2
  26. langchain_core/language_models/base.py +64 -39
  27. langchain_core/language_models/chat_models.py +130 -42
  28. langchain_core/language_models/fake_chat_models.py +10 -11
  29. langchain_core/language_models/llms.py +49 -17
  30. langchain_core/load/dump.py +5 -7
  31. langchain_core/load/load.py +15 -1
  32. langchain_core/load/serializable.py +38 -43
  33. langchain_core/memory.py +7 -3
  34. langchain_core/messages/ai.py +36 -16
  35. langchain_core/messages/base.py +13 -6
  36. langchain_core/messages/content_blocks.py +23 -2
  37. langchain_core/messages/human.py +2 -6
  38. langchain_core/messages/modifier.py +1 -1
  39. langchain_core/messages/system.py +2 -6
  40. langchain_core/messages/tool.py +36 -16
  41. langchain_core/messages/utils.py +198 -87
  42. langchain_core/output_parsers/base.py +5 -2
  43. langchain_core/output_parsers/json.py +4 -4
  44. langchain_core/output_parsers/list.py +7 -22
  45. langchain_core/output_parsers/openai_functions.py +3 -0
  46. langchain_core/output_parsers/openai_tools.py +8 -1
  47. langchain_core/output_parsers/pydantic.py +4 -0
  48. langchain_core/output_parsers/string.py +5 -1
  49. langchain_core/output_parsers/transform.py +2 -2
  50. langchain_core/output_parsers/xml.py +23 -22
  51. langchain_core/outputs/chat_generation.py +18 -7
  52. langchain_core/outputs/generation.py +14 -3
  53. langchain_core/outputs/llm_result.py +8 -1
  54. langchain_core/prompt_values.py +10 -4
  55. langchain_core/prompts/base.py +4 -9
  56. langchain_core/prompts/chat.py +88 -61
  57. langchain_core/prompts/dict.py +16 -8
  58. langchain_core/prompts/few_shot.py +9 -11
  59. langchain_core/prompts/few_shot_with_templates.py +5 -1
  60. langchain_core/prompts/image.py +12 -5
  61. langchain_core/prompts/message.py +5 -6
  62. langchain_core/prompts/pipeline.py +13 -8
  63. langchain_core/prompts/prompt.py +22 -8
  64. langchain_core/prompts/string.py +18 -10
  65. langchain_core/prompts/structured.py +7 -2
  66. langchain_core/rate_limiters.py +2 -2
  67. langchain_core/retrievers.py +7 -6
  68. langchain_core/runnables/base.py +842 -567
  69. langchain_core/runnables/branch.py +15 -20
  70. langchain_core/runnables/config.py +11 -17
  71. langchain_core/runnables/configurable.py +34 -19
  72. langchain_core/runnables/fallbacks.py +24 -17
  73. langchain_core/runnables/graph.py +47 -40
  74. langchain_core/runnables/graph_ascii.py +40 -17
  75. langchain_core/runnables/graph_mermaid.py +27 -15
  76. langchain_core/runnables/graph_png.py +27 -31
  77. langchain_core/runnables/history.py +56 -59
  78. langchain_core/runnables/passthrough.py +47 -24
  79. langchain_core/runnables/retry.py +10 -6
  80. langchain_core/runnables/router.py +10 -9
  81. langchain_core/runnables/schema.py +2 -0
  82. langchain_core/runnables/utils.py +51 -89
  83. langchain_core/stores.py +13 -25
  84. langchain_core/structured_query.py +3 -7
  85. langchain_core/sys_info.py +9 -8
  86. langchain_core/tools/base.py +30 -23
  87. langchain_core/tools/convert.py +24 -13
  88. langchain_core/tools/simple.py +35 -3
  89. langchain_core/tools/structured.py +26 -3
  90. langchain_core/tracers/_streaming.py +6 -7
  91. langchain_core/tracers/base.py +2 -2
  92. langchain_core/tracers/context.py +5 -1
  93. langchain_core/tracers/core.py +109 -39
  94. langchain_core/tracers/evaluation.py +22 -26
  95. langchain_core/tracers/event_stream.py +41 -28
  96. langchain_core/tracers/langchain.py +12 -3
  97. langchain_core/tracers/langchain_v1.py +10 -2
  98. langchain_core/tracers/log_stream.py +57 -18
  99. langchain_core/tracers/root_listeners.py +4 -20
  100. langchain_core/tracers/run_collector.py +6 -16
  101. langchain_core/tracers/schemas.py +5 -1
  102. langchain_core/utils/aiter.py +14 -6
  103. langchain_core/utils/env.py +3 -0
  104. langchain_core/utils/function_calling.py +49 -30
  105. langchain_core/utils/interactive_env.py +6 -2
  106. langchain_core/utils/iter.py +11 -3
  107. langchain_core/utils/json.py +5 -2
  108. langchain_core/utils/json_schema.py +15 -5
  109. langchain_core/utils/loading.py +5 -1
  110. langchain_core/utils/mustache.py +24 -15
  111. langchain_core/utils/pydantic.py +32 -4
  112. langchain_core/utils/utils.py +24 -8
  113. langchain_core/vectorstores/base.py +7 -20
  114. langchain_core/vectorstores/in_memory.py +18 -12
  115. langchain_core/vectorstores/utils.py +18 -12
  116. langchain_core/version.py +1 -1
  117. langchain_core-0.3.76.dist-info/METADATA +77 -0
  118. langchain_core-0.3.76.dist-info/RECORD +174 -0
  119. langchain_core-0.3.74.dist-info/METADATA +0 -108
  120. langchain_core-0.3.74.dist-info/RECORD +0 -174
  121. {langchain_core-0.3.74.dist-info → langchain_core-0.3.76.dist-info}/WHEEL +0 -0
  122. {langchain_core-0.3.74.dist-info → langchain_core-0.3.76.dist-info}/entry_points.txt +0 -0
@@ -1,4 +1,4 @@
1
- """Base classes and utilities for Runnables."""
1
+ """Base classes and utilities for ``Runnable``s."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -41,6 +41,7 @@ from pydantic import BaseModel, ConfigDict, Field, RootModel
41
41
  from typing_extensions import Literal, get_args, override
42
42
 
43
43
  from langchain_core._api import beta_decorator
44
+ from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
44
45
  from langchain_core.load.serializable import (
45
46
  Serializable,
46
47
  SerializedConstructor,
@@ -60,7 +61,6 @@ from langchain_core.runnables.config import (
60
61
  run_in_executor,
61
62
  set_config_context,
62
63
  )
63
- from langchain_core.runnables.graph import Graph
64
64
  from langchain_core.runnables.utils import (
65
65
  AddableDict,
66
66
  AnyConfigurableField,
@@ -81,6 +81,19 @@ from langchain_core.runnables.utils import (
81
81
  is_async_callable,
82
82
  is_async_generator,
83
83
  )
84
+ from langchain_core.tracers._streaming import _StreamingCallbackHandler
85
+ from langchain_core.tracers.event_stream import (
86
+ _astream_events_implementation_v1,
87
+ _astream_events_implementation_v2,
88
+ )
89
+ from langchain_core.tracers.log_stream import (
90
+ LogStreamCallbackHandler,
91
+ _astream_log_implementation,
92
+ )
93
+ from langchain_core.tracers.root_listeners import (
94
+ AsyncRootListenersTracer,
95
+ RootListenersTracer,
96
+ )
84
97
  from langchain_core.utils.aiter import aclosing, atee, py_anext
85
98
  from langchain_core.utils.iter import safetee
86
99
  from langchain_core.utils.pydantic import create_model_v2
@@ -94,6 +107,7 @@ if TYPE_CHECKING:
94
107
  from langchain_core.runnables.fallbacks import (
95
108
  RunnableWithFallbacks as RunnableWithFallbacksT,
96
109
  )
110
+ from langchain_core.runnables.graph import Graph
97
111
  from langchain_core.runnables.retry import ExponentialJitterParams
98
112
  from langchain_core.runnables.schema import StreamEvent
99
113
  from langchain_core.tools import BaseTool
@@ -111,17 +125,18 @@ class Runnable(ABC, Generic[Input, Output]):
111
125
  Key Methods
112
126
  ===========
113
127
 
114
- - **invoke/ainvoke**: Transforms a single input into an output.
115
- - **batch/abatch**: Efficiently transforms multiple inputs into outputs.
116
- - **stream/astream**: Streams output from a single input as it's produced.
117
- - **astream_log**: Streams output and selected intermediate results from an input.
128
+ - **``invoke``/``ainvoke``**: Transforms a single input into an output.
129
+ - **``batch``/``abatch``**: Efficiently transforms multiple inputs into outputs.
130
+ - **``stream``/``astream``**: Streams output from a single input as it's produced.
131
+ - **``astream_log``**: Streams output and selected intermediate results from an
132
+ input.
118
133
 
119
134
  Built-in optimizations:
120
135
 
121
- - **Batch**: By default, batch runs invoke() in parallel using a thread pool executor.
122
- Override to optimize batching.
136
+ - **Batch**: By default, batch runs invoke() in parallel using a thread pool
137
+ executor. Override to optimize batching.
123
138
 
124
- - **Async**: Methods with "a" suffix are asynchronous. By default, they execute
139
+ - **Async**: Methods with ``'a'`` suffix are asynchronous. By default, they execute
125
140
  the sync counterpart using asyncio's thread pool.
126
141
  Override for native async.
127
142
 
@@ -129,24 +144,26 @@ class Runnable(ABC, Generic[Input, Output]):
129
144
  execution, add tags and metadata for tracing and debugging etc.
130
145
 
131
146
  Runnables expose schematic information about their input, output and config via
132
- the input_schema property, the output_schema property and config_schema method.
147
+ the ``input_schema`` property, the ``output_schema`` property and ``config_schema``
148
+ method.
133
149
 
134
150
  LCEL and Composition
135
151
  ====================
136
152
 
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.
153
+ The LangChain Expression Language (LCEL) is a declarative way to compose
154
+ ``Runnables``into chains.
155
+ Any chain constructed this way will automatically have sync, async, batch, and
156
+ streaming support.
140
157
 
141
- The main composition primitives are RunnableSequence and RunnableParallel.
158
+ The main composition primitives are ``RunnableSequence`` and ``RunnableParallel``.
142
159
 
143
- **RunnableSequence** invokes a series of runnables sequentially, with
160
+ **``RunnableSequence``** invokes a series of runnables sequentially, with
144
161
  one Runnable's output serving as the next's input. Construct using
145
- the `|` operator or by passing a list of runnables to RunnableSequence.
162
+ the ``|`` operator or by passing a list of runnables to ``RunnableSequence``.
146
163
 
147
- **RunnableParallel** invokes runnables concurrently, providing the same input
164
+ **``RunnableParallel``** invokes runnables concurrently, providing the same input
148
165
  to each. Construct it using a dict literal within a sequence or by passing a
149
- dict to RunnableParallel.
166
+ dict to ``RunnableParallel``.
150
167
 
151
168
 
152
169
  For example,
@@ -157,25 +174,27 @@ class Runnable(ABC, Generic[Input, Output]):
157
174
 
158
175
  # A RunnableSequence constructed using the `|` operator
159
176
  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]
177
+ sequence.invoke(1) # 4
178
+ sequence.batch([1, 2, 3]) # [4, 6, 8]
162
179
 
163
180
 
164
181
  # A sequence that contains a RunnableParallel constructed using a dict literal
165
182
  sequence = RunnableLambda(lambda x: x + 1) | {
166
- 'mul_2': RunnableLambda(lambda x: x * 2),
167
- 'mul_5': RunnableLambda(lambda x: x * 5)
183
+ "mul_2": RunnableLambda(lambda x: x * 2),
184
+ "mul_5": RunnableLambda(lambda x: x * 5),
168
185
  }
169
- sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
186
+ sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
170
187
 
171
188
  Standard Methods
172
189
  ================
173
190
 
174
- All Runnables 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.).
191
+ All ``Runnable``s expose additional methods that can be used to modify their
192
+ behavior (e.g., add a retry policy, add lifecycle listeners, make them
193
+ configurable, etc.).
176
194
 
177
- These methods will work on any Runnable, including Runnable chains constructed
178
- by composing other Runnables. See the individual methods for details.
195
+ These methods will work on any ``Runnable``, including ``Runnable`` chains
196
+ constructed by composing other ``Runnable``s.
197
+ See the individual methods for details.
179
198
 
180
199
  For example,
181
200
 
@@ -219,6 +238,7 @@ class Runnable(ABC, Generic[Input, Output]):
219
238
  .. code-block:: python
220
239
 
221
240
  from langchain_core.globals import set_debug
241
+
222
242
  set_debug(True)
223
243
 
224
244
  Alternatively, you can pass existing or custom callbacks to any given chain:
@@ -227,22 +247,27 @@ class Runnable(ABC, Generic[Input, Output]):
227
247
 
228
248
  from langchain_core.tracers import ConsoleCallbackHandler
229
249
 
230
- chain.invoke(
231
- ...,
232
- config={'callbacks': [ConsoleCallbackHandler()]}
233
- )
250
+ chain.invoke(..., config={"callbacks": [ConsoleCallbackHandler()]})
234
251
 
235
- For a UI (and much more) checkout LangSmith: https://docs.smith.langchain.com/
252
+ For a UI (and much more) checkout `LangSmith <https://docs.smith.langchain.com/>`__.
236
253
 
237
- """ # noqa: E501
254
+ """
238
255
 
239
256
  name: Optional[str]
240
- """The name of the Runnable. Used for debugging and tracing."""
257
+ """The name of the ``Runnable``. Used for debugging and tracing."""
241
258
 
242
259
  def get_name(
243
260
  self, suffix: Optional[str] = None, *, name: Optional[str] = None
244
261
  ) -> str:
245
- """Get the name of the Runnable."""
262
+ """Get the name of the ``Runnable``.
263
+
264
+ Args:
265
+ suffix: An optional suffix to append to the name.
266
+ name: An optional name to use instead of the ``Runnable``'s name.
267
+
268
+ Returns:
269
+ The name of the ``Runnable``.
270
+ """
246
271
  if name:
247
272
  name_ = name
248
273
  elif hasattr(self, "name") and self.name:
@@ -273,7 +298,13 @@ class Runnable(ABC, Generic[Input, Output]):
273
298
 
274
299
  @property
275
300
  def InputType(self) -> type[Input]: # noqa: N802
276
- """The type of input this Runnable accepts specified as a type annotation."""
301
+ """Input type.
302
+
303
+ The type of input this ``Runnable`` accepts specified as a type annotation.
304
+
305
+ Raises:
306
+ TypeError: If the input type cannot be inferred.
307
+ """
277
308
  # First loop through all parent classes and if any of them is
278
309
  # a pydantic model, we will pick up the generic parameterization
279
310
  # from that model via the __pydantic_generic_metadata__ attribute.
@@ -299,7 +330,13 @@ class Runnable(ABC, Generic[Input, Output]):
299
330
 
300
331
  @property
301
332
  def OutputType(self) -> type[Output]: # noqa: N802
302
- """The type of output this Runnable produces specified as a type annotation."""
333
+ """Output Type.
334
+
335
+ The type of output this ``Runnable`` produces specified as a type annotation.
336
+
337
+ Raises:
338
+ TypeError: If the output type cannot be inferred.
339
+ """
303
340
  # First loop through bases -- this will help generic
304
341
  # any pydantic models.
305
342
  for base in self.__class__.mro():
@@ -321,7 +358,7 @@ class Runnable(ABC, Generic[Input, Output]):
321
358
 
322
359
  @property
323
360
  def input_schema(self) -> type[BaseModel]:
324
- """The type of input this Runnable accepts specified as a pydantic model."""
361
+ """The type of input this ``Runnable`` accepts specified as a pydantic model."""
325
362
  return self.get_input_schema()
326
363
 
327
364
  def get_input_schema(
@@ -330,9 +367,9 @@ class Runnable(ABC, Generic[Input, Output]):
330
367
  ) -> type[BaseModel]:
331
368
  """Get a pydantic model that can be used to validate input to the Runnable.
332
369
 
333
- Runnables that leverage the configurable_fields and configurable_alternatives
334
- methods will have a dynamic input schema that depends on which
335
- configuration the Runnable is invoked with.
370
+ ``Runnable``s that leverage the ``configurable_fields`` and
371
+ ``configurable_alternatives`` methods will have a dynamic input schema that
372
+ depends on which configuration the ``Runnable`` is invoked with.
336
373
 
337
374
  This method allows to get an input schema for a specific configuration.
338
375
 
@@ -367,13 +404,13 @@ class Runnable(ABC, Generic[Input, Output]):
367
404
  def get_input_jsonschema(
368
405
  self, config: Optional[RunnableConfig] = None
369
406
  ) -> dict[str, Any]:
370
- """Get a JSON schema that represents the input to the Runnable.
407
+ """Get a JSON schema that represents the input to the ``Runnable``.
371
408
 
372
409
  Args:
373
410
  config: A config to use when generating the schema.
374
411
 
375
412
  Returns:
376
- A JSON schema that represents the input to the Runnable.
413
+ A JSON schema that represents the input to the ``Runnable``.
377
414
 
378
415
  Example:
379
416
 
@@ -381,9 +418,11 @@ class Runnable(ABC, Generic[Input, Output]):
381
418
 
382
419
  from langchain_core.runnables import RunnableLambda
383
420
 
421
+
384
422
  def add_one(x: int) -> int:
385
423
  return x + 1
386
424
 
425
+
387
426
  runnable = RunnableLambda(add_one)
388
427
 
389
428
  print(runnable.get_input_jsonschema())
@@ -395,18 +434,21 @@ class Runnable(ABC, Generic[Input, Output]):
395
434
 
396
435
  @property
397
436
  def output_schema(self) -> type[BaseModel]:
398
- """The type of output this Runnable produces specified as a pydantic model."""
437
+ """Output schema.
438
+
439
+ The type of output this ``Runnable`` produces specified as a pydantic model.
440
+ """
399
441
  return self.get_output_schema()
400
442
 
401
443
  def get_output_schema(
402
444
  self,
403
445
  config: Optional[RunnableConfig] = None, # noqa: ARG002
404
446
  ) -> type[BaseModel]:
405
- """Get a pydantic model that can be used to validate output to the Runnable.
447
+ """Get a pydantic model that can be used to validate output to the ``Runnable``.
406
448
 
407
- Runnables that leverage the configurable_fields and configurable_alternatives
408
- methods will have a dynamic output schema that depends on which
409
- configuration the Runnable is invoked with.
449
+ ``Runnable``s that leverage the ``configurable_fields`` and
450
+ ``configurable_alternatives`` methods will have a dynamic output schema that
451
+ depends on which configuration the ``Runnable`` is invoked with.
410
452
 
411
453
  This method allows to get an output schema for a specific configuration.
412
454
 
@@ -441,13 +483,13 @@ class Runnable(ABC, Generic[Input, Output]):
441
483
  def get_output_jsonschema(
442
484
  self, config: Optional[RunnableConfig] = None
443
485
  ) -> dict[str, Any]:
444
- """Get a JSON schema that represents the output of the Runnable.
486
+ """Get a JSON schema that represents the output of the ``Runnable``.
445
487
 
446
488
  Args:
447
489
  config: A config to use when generating the schema.
448
490
 
449
491
  Returns:
450
- A JSON schema that represents the output of the Runnable.
492
+ A JSON schema that represents the output of the ``Runnable``.
451
493
 
452
494
  Example:
453
495
 
@@ -455,9 +497,11 @@ class Runnable(ABC, Generic[Input, Output]):
455
497
 
456
498
  from langchain_core.runnables import RunnableLambda
457
499
 
500
+
458
501
  def add_one(x: int) -> int:
459
502
  return x + 1
460
503
 
504
+
461
505
  runnable = RunnableLambda(add_one)
462
506
 
463
507
  print(runnable.get_output_jsonschema())
@@ -469,22 +513,23 @@ class Runnable(ABC, Generic[Input, Output]):
469
513
 
470
514
  @property
471
515
  def config_specs(self) -> list[ConfigurableFieldSpec]:
472
- """List configurable fields for this Runnable."""
516
+ """List configurable fields for this ``Runnable``."""
473
517
  return []
474
518
 
475
519
  def config_schema(
476
520
  self, *, include: Optional[Sequence[str]] = None
477
521
  ) -> type[BaseModel]:
478
- """The type of config this Runnable accepts specified as a pydantic model.
522
+ """The type of config this ``Runnable`` accepts specified as a pydantic model.
479
523
 
480
- To mark a field as configurable, see the `configurable_fields`
481
- and `configurable_alternatives` methods.
524
+ To mark a field as configurable, see the ``configurable_fields``
525
+ and ``configurable_alternatives`` methods.
482
526
 
483
527
  Args:
484
528
  include: A list of fields to include in the config schema.
485
529
 
486
530
  Returns:
487
531
  A pydantic model that can be used to validate config.
532
+
488
533
  """
489
534
  include = include or []
490
535
  config_specs = self.config_specs
@@ -519,20 +564,24 @@ class Runnable(ABC, Generic[Input, Output]):
519
564
  def get_config_jsonschema(
520
565
  self, *, include: Optional[Sequence[str]] = None
521
566
  ) -> dict[str, Any]:
522
- """Get a JSON schema that represents the config of the Runnable.
567
+ """Get a JSON schema that represents the config of the ``Runnable``.
523
568
 
524
569
  Args:
525
570
  include: A list of fields to include in the config schema.
526
571
 
527
572
  Returns:
528
- A JSON schema that represents the config of the Runnable.
573
+ A JSON schema that represents the config of the ``Runnable``.
529
574
 
530
575
  .. versionadded:: 0.3.0
576
+
531
577
  """
532
578
  return self.config_schema(include=include).model_json_schema()
533
579
 
534
580
  def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
535
- """Return a graph representation of this Runnable."""
581
+ """Return a graph representation of this ``Runnable``."""
582
+ # Import locally to prevent circular import
583
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
584
+
536
585
  graph = Graph()
537
586
  try:
538
587
  input_node = graph.add_node(self.get_input_schema(config))
@@ -552,8 +601,9 @@ class Runnable(ABC, Generic[Input, Output]):
552
601
  def get_prompts(
553
602
  self, config: Optional[RunnableConfig] = None
554
603
  ) -> list[BasePromptTemplate]:
555
- """Return a list of prompts used by this Runnable."""
556
- from langchain_core.prompts.base import BasePromptTemplate
604
+ """Return a list of prompts used by this ``Runnable``."""
605
+ # Import locally to prevent circular import
606
+ from langchain_core.prompts.base import BasePromptTemplate # noqa: PLC0415
557
607
 
558
608
  return [
559
609
  node.data
@@ -571,7 +621,17 @@ class Runnable(ABC, Generic[Input, Output]):
571
621
  Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]],
572
622
  ],
573
623
  ) -> RunnableSerializable[Input, Other]:
574
- """Compose this Runnable with another object to create a RunnableSequence."""
624
+ """Runnable "or" operator.
625
+
626
+ Compose this ``Runnable`` with another object to create a
627
+ ``RunnableSequence``.
628
+
629
+ Args:
630
+ other: Another ``Runnable`` or a ``Runnable``-like object.
631
+
632
+ Returns:
633
+ A new ``Runnable``.
634
+ """
575
635
  return RunnableSequence(self, coerce_to_runnable(other))
576
636
 
577
637
  def __ror__(
@@ -584,7 +644,17 @@ class Runnable(ABC, Generic[Input, Output]):
584
644
  Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]],
585
645
  ],
586
646
  ) -> RunnableSerializable[Other, Output]:
587
- """Compose this Runnable with another object to create a RunnableSequence."""
647
+ """Runnable "reverse-or" operator.
648
+
649
+ Compose this ``Runnable`` with another object to create a
650
+ ``RunnableSequence``.
651
+
652
+ Args:
653
+ other: Another ``Runnable`` or a ``Runnable``-like object.
654
+
655
+ Returns:
656
+ A new ``Runnable``.
657
+ """
588
658
  return RunnableSequence(coerce_to_runnable(other), self)
589
659
 
590
660
  def pipe(
@@ -592,21 +662,28 @@ class Runnable(ABC, Generic[Input, Output]):
592
662
  *others: Union[Runnable[Any, Other], Callable[[Any], Other]],
593
663
  name: Optional[str] = None,
594
664
  ) -> RunnableSerializable[Input, Other]:
595
- """Compose this Runnable with Runnable-like objects to make a RunnableSequence.
665
+ """Pipe runnables.
666
+
667
+ Compose this ``Runnable`` with ``Runnable``-like objects to make a
668
+ ``RunnableSequence``.
596
669
 
597
- Equivalent to `RunnableSequence(self, *others)` or `self | others[0] | ...`
670
+ Equivalent to ``RunnableSequence(self, *others)`` or ``self | others[0] | ...``
598
671
 
599
672
  Example:
673
+
600
674
  .. code-block:: python
601
675
 
602
676
  from langchain_core.runnables import RunnableLambda
603
677
 
678
+
604
679
  def add_one(x: int) -> int:
605
680
  return x + 1
606
681
 
682
+
607
683
  def mul_two(x: int) -> int:
608
684
  return x * 2
609
685
 
686
+
610
687
  runnable_1 = RunnableLambda(add_one)
611
688
  runnable_2 = RunnableLambda(mul_two)
612
689
  sequence = runnable_1.pipe(runnable_2)
@@ -621,13 +698,20 @@ class Runnable(ABC, Generic[Input, Output]):
621
698
  await sequence.abatch([1, 2, 3])
622
699
  # -> [4, 6, 8]
623
700
 
701
+ Args:
702
+ *others: Other ``Runnable`` or ``Runnable``-like objects to compose
703
+ name: An optional name for the resulting ``RunnableSequence``.
704
+
705
+ Returns:
706
+ A new ``Runnable``.
624
707
  """
625
708
  return RunnableSequence(self, *others, name=name)
626
709
 
627
710
  def pick(self, keys: Union[str, list[str]]) -> RunnableSerializable[Any, Any]:
628
- """Pick keys from the output dict of this Runnable.
711
+ """Pick keys from the output dict of this ``Runnable``.
629
712
 
630
713
  Pick single key:
714
+
631
715
  .. code-block:: python
632
716
 
633
717
  import json
@@ -646,6 +730,7 @@ class Runnable(ABC, Generic[Input, Output]):
646
730
  # -> [1, 2, 3]
647
731
 
648
732
  Pick list of keys:
733
+
649
734
  .. code-block:: python
650
735
 
651
736
  from typing import Any
@@ -656,13 +741,14 @@ class Runnable(ABC, Generic[Input, Output]):
656
741
 
657
742
  as_str = RunnableLambda(str)
658
743
  as_json = RunnableLambda(json.loads)
744
+
745
+
659
746
  def as_bytes(x: Any) -> bytes:
660
747
  return bytes(x, "utf-8")
661
748
 
749
+
662
750
  chain = RunnableMap(
663
- str=as_str,
664
- json=as_json,
665
- bytes=RunnableLambda(as_bytes)
751
+ str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)
666
752
  )
667
753
 
668
754
  chain.invoke("[1, 2, 3]")
@@ -672,8 +758,15 @@ class Runnable(ABC, Generic[Input, Output]):
672
758
  json_and_bytes_chain.invoke("[1, 2, 3]")
673
759
  # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
674
760
 
761
+ Args:
762
+ keys: A key or list of keys to pick from the output dict.
763
+
764
+ Returns:
765
+ a new ``Runnable``.
766
+
675
767
  """
676
- from langchain_core.runnables.passthrough import RunnablePick
768
+ # Import locally to prevent circular import
769
+ from langchain_core.runnables.passthrough import RunnablePick # noqa: PLC0415
677
770
 
678
771
  return self | RunnablePick(keys)
679
772
 
@@ -688,9 +781,7 @@ class Runnable(ABC, Generic[Input, Output]):
688
781
  ],
689
782
  ],
690
783
  ) -> RunnableSerializable[Any, Any]:
691
- """Assigns new fields to the dict output of this Runnable.
692
-
693
- Returns a new Runnable.
784
+ """Assigns new fields to the dict output of this ``Runnable``.
694
785
 
695
786
  .. code-block:: python
696
787
 
@@ -718,8 +809,16 @@ class Runnable(ABC, Generic[Input, Output]):
718
809
  {'str': {'title': 'Str',
719
810
  'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
720
811
 
812
+ Args:
813
+ **kwargs: A mapping of keys to ``Runnable`` or ``Runnable``-like objects
814
+ that will be invoked with the entire output dict of this ``Runnable``.
815
+
816
+ Returns:
817
+ A new ``Runnable``.
818
+
721
819
  """
722
- from langchain_core.runnables.passthrough import RunnableAssign
820
+ # Import locally to prevent circular import
821
+ from langchain_core.runnables.passthrough import RunnableAssign # noqa: PLC0415
723
822
 
724
823
  return self | RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
725
824
 
@@ -728,36 +827,44 @@ class Runnable(ABC, Generic[Input, Output]):
728
827
  @abstractmethod
729
828
  def invoke(
730
829
  self,
731
- input: Input, # noqa: A002
830
+ input: Input,
732
831
  config: Optional[RunnableConfig] = None,
733
832
  **kwargs: Any,
734
833
  ) -> Output:
735
834
  """Transform a single input into an output.
736
835
 
737
836
  Args:
738
- input: The input to the Runnable.
739
- config: A config to use when invoking the Runnable.
837
+ input: The input to the ``Runnable``.
838
+ config: A config to use when invoking the ``Runnable``.
740
839
  The config supports standard keys like ``'tags'``, ``'metadata'`` for
741
840
  tracing purposes, ``'max_concurrency'`` for controlling how much work to
742
- do in parallel, and other keys. Please refer to the RunnableConfig
841
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
743
842
  for more details. Defaults to None.
744
843
 
745
844
  Returns:
746
- The output of the Runnable.
845
+ The output of the ``Runnable``.
846
+
747
847
  """
748
848
 
749
849
  async def ainvoke(
750
850
  self,
751
- input: Input, # noqa: A002
851
+ input: Input,
752
852
  config: Optional[RunnableConfig] = None,
753
853
  **kwargs: Any,
754
854
  ) -> Output:
755
- """Default implementation of ainvoke, calls invoke from a thread.
855
+ """Transform a single input into an output.
856
+
857
+ Args:
858
+ input: The input to the ``Runnable``.
859
+ config: A config to use when invoking the ``Runnable``.
860
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
861
+ tracing purposes, ``'max_concurrency'`` for controlling how much work to
862
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
863
+ for more details. Defaults to None.
756
864
 
757
- The default implementation allows usage of async code even if
758
- the Runnable did not implement a native async version of invoke.
865
+ Returns:
866
+ The output of the ``Runnable``.
759
867
 
760
- Subclasses should override this method if they can run asynchronously.
761
868
  """
762
869
  return await run_in_executor(config, self.invoke, input, config, **kwargs)
763
870
 
@@ -774,7 +881,22 @@ class Runnable(ABC, Generic[Input, Output]):
774
881
  The default implementation of batch works well for IO bound runnables.
775
882
 
776
883
  Subclasses should override this method if they can batch more efficiently;
777
- e.g., if the underlying Runnable uses an API which supports a batch mode.
884
+ e.g., if the underlying ``Runnable`` uses an API which supports a batch mode.
885
+
886
+ Args:
887
+ inputs: A list of inputs to the ``Runnable``.
888
+ config: A config to use when invoking the ``Runnable``.
889
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
890
+ tracing purposes, ``'max_concurrency'`` for controlling how much work
891
+ to do in parallel, and other keys. Please refer to the
892
+ ``RunnableConfig`` for more details. Defaults to None.
893
+ return_exceptions: Whether to return exceptions instead of raising them.
894
+ Defaults to False.
895
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
896
+
897
+ Returns:
898
+ A list of outputs from the ``Runnable``.
899
+
778
900
  """
779
901
  if not inputs:
780
902
  return []
@@ -825,9 +947,24 @@ class Runnable(ABC, Generic[Input, Output]):
825
947
  return_exceptions: bool = False,
826
948
  **kwargs: Optional[Any],
827
949
  ) -> Iterator[tuple[int, Union[Output, Exception]]]:
828
- """Run invoke in parallel on a list of inputs.
950
+ """Run ``invoke`` in parallel on a list of inputs.
829
951
 
830
952
  Yields results as they complete.
953
+
954
+ Args:
955
+ inputs: A list of inputs to the ``Runnable``.
956
+ config: A config to use when invoking the ``Runnable``.
957
+ The config supports standard keys like ``'tags'``, ``'metadata'`` for
958
+ tracing purposes, ``'max_concurrency'`` for controlling how much work to
959
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
960
+ for more details. Defaults to None.
961
+ return_exceptions: Whether to return exceptions instead of raising them.
962
+ Defaults to False.
963
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
964
+
965
+ Yields:
966
+ Tuples of the index of the input and the output from the ``Runnable``.
967
+
831
968
  """
832
969
  if not inputs:
833
970
  return
@@ -876,26 +1013,27 @@ class Runnable(ABC, Generic[Input, Output]):
876
1013
  return_exceptions: bool = False,
877
1014
  **kwargs: Optional[Any],
878
1015
  ) -> list[Output]:
879
- """Default implementation runs ainvoke in parallel using asyncio.gather.
1016
+ """Default implementation runs ``ainvoke`` in parallel using ``asyncio.gather``.
880
1017
 
881
- The default implementation of batch works well for IO bound runnables.
1018
+ The default implementation of ``batch`` works well for IO bound runnables.
882
1019
 
883
1020
  Subclasses should override this method if they can batch more efficiently;
884
- e.g., if the underlying Runnable uses an API which supports a batch mode.
1021
+ e.g., if the underlying ``Runnable`` uses an API which supports a batch mode.
885
1022
 
886
1023
  Args:
887
- inputs: A list of inputs to the Runnable.
888
- config: A config to use when invoking the Runnable.
1024
+ inputs: A list of inputs to the ``Runnable``.
1025
+ config: A config to use when invoking the ``Runnable``.
889
1026
  The config supports standard keys like ``'tags'``, ``'metadata'`` for
890
1027
  tracing purposes, ``'max_concurrency'`` for controlling how much work to
891
- do in parallel, and other keys. Please refer to the RunnableConfig
1028
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
892
1029
  for more details. Defaults to None.
893
1030
  return_exceptions: Whether to return exceptions instead of raising them.
894
1031
  Defaults to False.
895
- kwargs: Additional keyword arguments to pass to the Runnable.
1032
+ **kwargs: Additional keyword arguments to pass to the ``Runnable``.
896
1033
 
897
1034
  Returns:
898
- A list of outputs from the Runnable.
1035
+ A list of outputs from the ``Runnable``.
1036
+
899
1037
  """
900
1038
  if not inputs:
901
1039
  return []
@@ -944,23 +1082,24 @@ class Runnable(ABC, Generic[Input, Output]):
944
1082
  return_exceptions: bool = False,
945
1083
  **kwargs: Optional[Any],
946
1084
  ) -> AsyncIterator[tuple[int, Union[Output, Exception]]]:
947
- """Run ainvoke in parallel on a list of inputs.
1085
+ """Run ``ainvoke`` in parallel on a list of inputs.
948
1086
 
949
1087
  Yields results as they complete.
950
1088
 
951
1089
  Args:
952
- inputs: A list of inputs to the Runnable.
953
- config: A config to use when invoking the Runnable.
1090
+ inputs: A list of inputs to the ``Runnable``.
1091
+ config: A config to use when invoking the ``Runnable``.
954
1092
  The config supports standard keys like ``'tags'``, ``'metadata'`` for
955
1093
  tracing purposes, ``'max_concurrency'`` for controlling how much work to
956
- do in parallel, and other keys. Please refer to the RunnableConfig
1094
+ do in parallel, and other keys. Please refer to the ``RunnableConfig``
957
1095
  for more details. Defaults to None.
958
1096
  return_exceptions: Whether to return exceptions instead of raising them.
959
1097
  Defaults to False.
960
- kwargs: Additional keyword arguments to pass to the Runnable.
1098
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
961
1099
 
962
1100
  Yields:
963
- A tuple of the index of the input and the output from the Runnable.
1101
+ A tuple of the index of the input and the output from the ``Runnable``.
1102
+
964
1103
  """
965
1104
  if not inputs:
966
1105
  return
@@ -996,41 +1135,43 @@ class Runnable(ABC, Generic[Input, Output]):
996
1135
 
997
1136
  def stream(
998
1137
  self,
999
- input: Input, # noqa: A002
1138
+ input: Input,
1000
1139
  config: Optional[RunnableConfig] = None,
1001
1140
  **kwargs: Optional[Any],
1002
1141
  ) -> Iterator[Output]:
1003
- """Default implementation of stream, which calls invoke.
1142
+ """Default implementation of ``stream``, which calls ``invoke``.
1004
1143
 
1005
1144
  Subclasses should override this method if they support streaming output.
1006
1145
 
1007
1146
  Args:
1008
- input: The input to the Runnable.
1009
- config: The config to use for the Runnable. Defaults to None.
1010
- kwargs: Additional keyword arguments to pass to the Runnable.
1147
+ input: The input to the ``Runnable``.
1148
+ config: The config to use for the ``Runnable``. Defaults to None.
1149
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1011
1150
 
1012
1151
  Yields:
1013
- The output of the Runnable.
1152
+ The output of the ``Runnable``.
1153
+
1014
1154
  """
1015
1155
  yield self.invoke(input, config, **kwargs)
1016
1156
 
1017
1157
  async def astream(
1018
1158
  self,
1019
- input: Input, # noqa: A002
1159
+ input: Input,
1020
1160
  config: Optional[RunnableConfig] = None,
1021
1161
  **kwargs: Optional[Any],
1022
1162
  ) -> AsyncIterator[Output]:
1023
- """Default implementation of astream, which calls ainvoke.
1163
+ """Default implementation of ``astream``, which calls ``ainvoke``.
1024
1164
 
1025
1165
  Subclasses should override this method if they support streaming output.
1026
1166
 
1027
1167
  Args:
1028
- input: The input to the Runnable.
1029
- config: The config to use for the Runnable. Defaults to None.
1030
- kwargs: Additional keyword arguments to pass to the Runnable.
1168
+ input: The input to the ``Runnable``.
1169
+ config: The config to use for the ``Runnable``. Defaults to None.
1170
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1031
1171
 
1032
1172
  Yields:
1033
- The output of the Runnable.
1173
+ The output of the ``Runnable``.
1174
+
1034
1175
  """
1035
1176
  yield await self.ainvoke(input, config, **kwargs)
1036
1177
 
@@ -1070,7 +1211,7 @@ class Runnable(ABC, Generic[Input, Output]):
1070
1211
 
1071
1212
  async def astream_log(
1072
1213
  self,
1073
- input: Any, # noqa: A002
1214
+ input: Any,
1074
1215
  config: Optional[RunnableConfig] = None,
1075
1216
  *,
1076
1217
  diff: bool = True,
@@ -1083,7 +1224,7 @@ class Runnable(ABC, Generic[Input, Output]):
1083
1224
  exclude_tags: Optional[Sequence[str]] = None,
1084
1225
  **kwargs: Any,
1085
1226
  ) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]:
1086
- """Stream all output from a Runnable, as reported to the callback system.
1227
+ """Stream all output from a ``Runnable``, as reported to the callback system.
1087
1228
 
1088
1229
  This includes all inner runs of LLMs, Retrievers, Tools, etc.
1089
1230
 
@@ -1094,26 +1235,22 @@ class Runnable(ABC, Generic[Input, Output]):
1094
1235
  The Jsonpatch ops can be applied in order to construct state.
1095
1236
 
1096
1237
  Args:
1097
- input: The input to the Runnable.
1098
- config: The config to use for the Runnable.
1238
+ input: The input to the ``Runnable``.
1239
+ config: The config to use for the ``Runnable``.
1099
1240
  diff: Whether to yield diffs between each step or the current state.
1100
- with_streamed_output_list: Whether to yield the streamed_output list.
1241
+ with_streamed_output_list: Whether to yield the ``streamed_output`` list.
1101
1242
  include_names: Only include logs with these names.
1102
1243
  include_types: Only include logs with these types.
1103
1244
  include_tags: Only include logs with these tags.
1104
1245
  exclude_names: Exclude logs with these names.
1105
1246
  exclude_types: Exclude logs with these types.
1106
1247
  exclude_tags: Exclude logs with these tags.
1107
- kwargs: Additional keyword arguments to pass to the Runnable.
1248
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1108
1249
 
1109
1250
  Yields:
1110
- A RunLogPatch or RunLog object.
1111
- """
1112
- from langchain_core.tracers.log_stream import (
1113
- LogStreamCallbackHandler,
1114
- _astream_log_implementation,
1115
- )
1251
+ A ``RunLogPatch`` or ``RunLog`` object.
1116
1252
 
1253
+ """
1117
1254
  stream = LogStreamCallbackHandler(
1118
1255
  auto_close=False,
1119
1256
  include_names=include_names,
@@ -1141,7 +1278,7 @@ class Runnable(ABC, Generic[Input, Output]):
1141
1278
 
1142
1279
  async def astream_events(
1143
1280
  self,
1144
- input: Any, # noqa: A002
1281
+ input: Any,
1145
1282
  config: Optional[RunnableConfig] = None,
1146
1283
  *,
1147
1284
  version: Literal["v1", "v2"] = "v2",
@@ -1155,73 +1292,73 @@ class Runnable(ABC, Generic[Input, Output]):
1155
1292
  ) -> AsyncIterator[StreamEvent]:
1156
1293
  """Generate a stream of events.
1157
1294
 
1158
- Use to create an iterator over StreamEvents that provide real-time information
1159
- about the progress of the Runnable, including StreamEvents from intermediate
1295
+ Use to create an iterator over ``StreamEvents`` that provide real-time information
1296
+ about the progress of the ``Runnable``, including ``StreamEvents`` from intermediate
1160
1297
  results.
1161
1298
 
1162
- A StreamEvent is a dictionary with the following schema:
1299
+ A ``StreamEvent`` is a dictionary with the following schema:
1163
1300
 
1164
1301
  - ``event``: **str** - Event names are of the format:
1165
- on_[runnable_type]_(start|stream|end).
1166
- - ``name``: **str** - The name of the Runnable that generated the event.
1302
+ ``on_[runnable_type]_(start|stream|end)``.
1303
+ - ``name``: **str** - The name of the ``Runnable`` that generated the event.
1167
1304
  - ``run_id``: **str** - randomly generated ID associated with the given
1168
- execution of the Runnable that emitted the event. A child Runnable that gets
1169
- invoked as part of the execution of a parent Runnable is assigned its own
1305
+ execution of the ``Runnable`` that emitted the event. A child ``Runnable`` that gets
1306
+ invoked as part of the execution of a parent ``Runnable`` is assigned its own
1170
1307
  unique ID.
1171
1308
  - ``parent_ids``: **list[str]** - The IDs of the parent runnables that generated
1172
- the event. The root Runnable will have an empty list. The order of the parent
1309
+ the event. The root ``Runnable`` will have an empty list. The order of the parent
1173
1310
  IDs is from the root to the immediate parent. Only available for v2 version of
1174
1311
  the API. The v1 version of the API will return an empty list.
1175
- - ``tags``: **Optional[list[str]]** - The tags of the Runnable that generated
1312
+ - ``tags``: **Optional[list[str]]** - The tags of the ``Runnable`` that generated
1176
1313
  the event.
1177
- - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the Runnable that
1314
+ - ``metadata``: **Optional[dict[str, Any]]** - The metadata of the ``Runnable`` that
1178
1315
  generated the event.
1179
1316
  - ``data``: **dict[str, Any]**
1180
1317
 
1181
-
1182
1318
  Below is a table that illustrates some events that might be emitted by various
1183
1319
  chains. Metadata fields have been omitted from the table for brevity.
1184
1320
  Chain definitions have been included after the table.
1185
1321
 
1186
- .. NOTE:: This reference table is for the V2 version of the schema.
1187
-
1188
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1189
- | event | name | chunk | input | output |
1190
- +======================+==================+=================================+===============================================+=================================================+
1191
- | on_chat_model_start | [model name] | | {"messages": [[SystemMessage, HumanMessage]]} | |
1192
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1193
- | on_chat_model_stream | [model name] | AIMessageChunk(content="hello") | | |
1194
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1195
- | on_chat_model_end | [model name] | | {"messages": [[SystemMessage, HumanMessage]]} | AIMessageChunk(content="hello world") |
1196
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1197
- | on_llm_start | [model name] | | {'input': 'hello'} | |
1198
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1199
- | on_llm_stream | [model name] | 'Hello' | | |
1200
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1201
- | on_llm_end | [model name] | | 'Hello human!' | |
1202
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1203
- | on_chain_start | format_docs | | | |
1204
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1205
- | on_chain_stream | format_docs | "hello world!, goodbye world!" | | |
1206
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1207
- | on_chain_end | format_docs | | [Document(...)] | "hello world!, goodbye world!" |
1208
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1209
- | on_tool_start | some_tool | | {"x": 1, "y": "2"} | |
1210
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1211
- | on_tool_end | some_tool | | | {"x": 1, "y": "2"} |
1212
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1213
- | on_retriever_start | [retriever name] | | {"query": "hello"} | |
1214
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1215
- | on_retriever_end | [retriever name] | | {"query": "hello"} | [Document(...), ..] |
1216
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1217
- | on_prompt_start | [template_name] | | {"question": "hello"} | |
1218
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1219
- | on_prompt_end | [template_name] | | {"question": "hello"} | ChatPromptValue(messages: [SystemMessage, ...]) |
1220
- +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
1322
+ .. note::
1323
+ This reference table is for the v2 version of the schema.
1324
+
1325
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1326
+ | event | name | chunk | input | output |
1327
+ +==========================+==================+=====================================+===================================================+=====================================================+
1328
+ | ``on_chat_model_start`` | [model name] | | ``{"messages": [[SystemMessage, HumanMessage]]}`` | |
1329
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1330
+ | ``on_chat_model_stream`` | [model name] | ``AIMessageChunk(content="hello")`` | | |
1331
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1332
+ | ``on_chat_model_end`` | [model name] | | ``{"messages": [[SystemMessage, HumanMessage]]}`` | ``AIMessageChunk(content="hello world")`` |
1333
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1334
+ | ``on_llm_start`` | [model name] | | ``{'input': 'hello'}`` | |
1335
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1336
+ | ``on_llm_stream`` | [model name] | ``'Hello' `` | | |
1337
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1338
+ | ``on_llm_end`` | [model name] | | ``'Hello human!'`` | |
1339
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1340
+ | ``on_chain_start`` | format_docs | | | |
1341
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1342
+ | ``on_chain_stream`` | format_docs | ``'hello world!, goodbye world!'`` | | |
1343
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1344
+ | ``on_chain_end`` | format_docs | | ``[Document(...)]`` | ``'hello world!, goodbye world!'`` |
1345
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1346
+ | ``on_tool_start`` | some_tool | | ``{"x": 1, "y": "2"}`` | |
1347
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1348
+ | ``on_tool_end`` | some_tool | | | ``{"x": 1, "y": "2"}`` |
1349
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1350
+ | ``on_retriever_start`` | [retriever name] | | ``{"query": "hello"}`` | |
1351
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1352
+ | ``on_retriever_end`` | [retriever name] | | ``{"query": "hello"}`` | ``[Document(...), ..]`` |
1353
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1354
+ | ``on_prompt_start`` | [template_name] | | ``{"question": "hello"}`` | |
1355
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1356
+ | ``on_prompt_end`` | [template_name] | | ``{"question": "hello"}`` | ``ChatPromptValue(messages: [SystemMessage, ...])`` |
1357
+ +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
1221
1358
 
1222
1359
  In addition to the standard events, users can also dispatch custom events (see example below).
1223
1360
 
1224
- Custom events will be only be surfaced with in the `v2` version of the API!
1361
+ Custom events will be only be surfaced with in the v2 version of the API!
1225
1362
 
1226
1363
  A custom event has following format:
1227
1364
 
@@ -1235,7 +1372,7 @@ class Runnable(ABC, Generic[Input, Output]):
1235
1372
 
1236
1373
  Here are declarations associated with the standard events shown above:
1237
1374
 
1238
- `format_docs`:
1375
+ ``format_docs``:
1239
1376
 
1240
1377
  .. code-block:: python
1241
1378
 
@@ -1243,9 +1380,10 @@ class Runnable(ABC, Generic[Input, Output]):
1243
1380
  '''Format the docs.'''
1244
1381
  return ", ".join([doc.page_content for doc in docs])
1245
1382
 
1383
+
1246
1384
  format_docs = RunnableLambda(format_docs)
1247
1385
 
1248
- `some_tool`:
1386
+ ``some_tool``:
1249
1387
 
1250
1388
  .. code-block:: python
1251
1389
 
@@ -1254,7 +1392,7 @@ class Runnable(ABC, Generic[Input, Output]):
1254
1392
  '''Some_tool.'''
1255
1393
  return {"x": x, "y": y}
1256
1394
 
1257
- `prompt`:
1395
+ ``prompt``:
1258
1396
 
1259
1397
  .. code-block:: python
1260
1398
 
@@ -1269,9 +1407,11 @@ class Runnable(ABC, Generic[Input, Output]):
1269
1407
 
1270
1408
  from langchain_core.runnables import RunnableLambda
1271
1409
 
1410
+
1272
1411
  async def reverse(s: str) -> str:
1273
1412
  return s[::-1]
1274
1413
 
1414
+
1275
1415
  chain = RunnableLambda(func=reverse)
1276
1416
 
1277
1417
  events = [
@@ -1339,36 +1479,31 @@ class Runnable(ABC, Generic[Input, Output]):
1339
1479
  print(event)
1340
1480
 
1341
1481
  Args:
1342
- input: The input to the Runnable.
1343
- config: The config to use for the Runnable.
1344
- version: The version of the schema to use either `v2` or `v1`.
1345
- Users should use `v2`.
1346
- `v1` is for backwards compatibility and will be deprecated
1482
+ input: The input to the ``Runnable``.
1483
+ config: The config to use for the ``Runnable``.
1484
+ version: The version of the schema to use either ``'v2'`` or ``'v1'``.
1485
+ Users should use ``'v2'``.
1486
+ ``'v1'`` is for backwards compatibility and will be deprecated
1347
1487
  in 0.4.0.
1348
1488
  No default will be assigned until the API is stabilized.
1349
- custom events will only be surfaced in `v2`.
1350
- include_names: Only include events from runnables with matching names.
1351
- include_types: Only include events from runnables with matching types.
1352
- include_tags: Only include events from runnables with matching tags.
1353
- exclude_names: Exclude events from runnables with matching names.
1354
- exclude_types: Exclude events from runnables with matching types.
1355
- exclude_tags: Exclude events from runnables with matching tags.
1356
- kwargs: Additional keyword arguments to pass to the Runnable.
1357
- These will be passed to astream_log as this implementation
1358
- of astream_events is built on top of astream_log.
1489
+ custom events will only be surfaced in ``'v2'``.
1490
+ include_names: Only include events from ``Runnables`` with matching names.
1491
+ include_types: Only include events from ``Runnables`` with matching types.
1492
+ include_tags: Only include events from ``Runnables`` with matching tags.
1493
+ exclude_names: Exclude events from ``Runnables`` with matching names.
1494
+ exclude_types: Exclude events from ``Runnables`` with matching types.
1495
+ exclude_tags: Exclude events from ``Runnables`` with matching tags.
1496
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1497
+ These will be passed to ``astream_log`` as this implementation
1498
+ of ``astream_events`` is built on top of ``astream_log``.
1359
1499
 
1360
1500
  Yields:
1361
- An async stream of StreamEvents.
1501
+ An async stream of ``StreamEvents``.
1362
1502
 
1363
1503
  Raises:
1364
- NotImplementedError: If the version is not `v1` or `v2`.
1504
+ NotImplementedError: If the version is not ``'v1'`` or ``'v2'``.
1365
1505
 
1366
1506
  """ # noqa: E501
1367
- from langchain_core.tracers.event_stream import (
1368
- _astream_events_implementation_v1,
1369
- _astream_events_implementation_v2,
1370
- )
1371
-
1372
1507
  if version == "v2":
1373
1508
  event_stream = _astream_events_implementation_v2(
1374
1509
  self,
@@ -1407,22 +1542,25 @@ class Runnable(ABC, Generic[Input, Output]):
1407
1542
 
1408
1543
  def transform(
1409
1544
  self,
1410
- input: Iterator[Input], # noqa: A002
1545
+ input: Iterator[Input],
1411
1546
  config: Optional[RunnableConfig] = None,
1412
1547
  **kwargs: Optional[Any],
1413
1548
  ) -> Iterator[Output]:
1414
- """Default implementation of transform, which buffers input and calls astream.
1549
+ """Transform inputs to outputs.
1550
+
1551
+ Default implementation of transform, which buffers input and calls ``astream``.
1415
1552
 
1416
1553
  Subclasses should override this method if they can start producing output while
1417
1554
  input is still being generated.
1418
1555
 
1419
1556
  Args:
1420
- input: An iterator of inputs to the Runnable.
1421
- config: The config to use for the Runnable. Defaults to None.
1422
- kwargs: Additional keyword arguments to pass to the Runnable.
1557
+ input: An iterator of inputs to the ``Runnable``.
1558
+ config: The config to use for the ``Runnable``. Defaults to None.
1559
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1423
1560
 
1424
1561
  Yields:
1425
- The output of the Runnable.
1562
+ The output of the ``Runnable``.
1563
+
1426
1564
  """
1427
1565
  final: Input
1428
1566
  got_first_val = False
@@ -1449,22 +1587,25 @@ class Runnable(ABC, Generic[Input, Output]):
1449
1587
 
1450
1588
  async def atransform(
1451
1589
  self,
1452
- input: AsyncIterator[Input], # noqa: A002
1590
+ input: AsyncIterator[Input],
1453
1591
  config: Optional[RunnableConfig] = None,
1454
1592
  **kwargs: Optional[Any],
1455
1593
  ) -> AsyncIterator[Output]:
1456
- """Default implementation of atransform, which buffers input and calls astream.
1594
+ """Transform inputs to outputs.
1595
+
1596
+ Default implementation of atransform, which buffers input and calls ``astream``.
1457
1597
 
1458
1598
  Subclasses should override this method if they can start producing output while
1459
1599
  input is still being generated.
1460
1600
 
1461
1601
  Args:
1462
- input: An async iterator of inputs to the Runnable.
1463
- config: The config to use for the Runnable. Defaults to None.
1464
- kwargs: Additional keyword arguments to pass to the Runnable.
1602
+ input: An async iterator of inputs to the ``Runnable``.
1603
+ config: The config to use for the ``Runnable``. Defaults to None.
1604
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1465
1605
 
1466
1606
  Yields:
1467
- The output of the Runnable.
1607
+ The output of the ``Runnable``.
1608
+
1468
1609
  """
1469
1610
  final: Input
1470
1611
  got_first_val = False
@@ -1491,16 +1632,16 @@ class Runnable(ABC, Generic[Input, Output]):
1491
1632
  yield output
1492
1633
 
1493
1634
  def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
1494
- """Bind arguments to a Runnable, returning a new Runnable.
1635
+ """Bind arguments to a ``Runnable``, returning a new ``Runnable``.
1495
1636
 
1496
- Useful when a Runnable in a chain requires an argument that is not
1497
- in the output of the previous Runnable or included in the user input.
1637
+ Useful when a ``Runnable`` in a chain requires an argument that is not
1638
+ in the output of the previous ``Runnable`` or included in the user input.
1498
1639
 
1499
1640
  Args:
1500
- kwargs: The arguments to bind to the Runnable.
1641
+ kwargs: The arguments to bind to the ``Runnable``.
1501
1642
 
1502
1643
  Returns:
1503
- A new Runnable with the arguments bound.
1644
+ A new ``Runnable`` with the arguments bound.
1504
1645
 
1505
1646
  Example:
1506
1647
 
@@ -1509,22 +1650,16 @@ class Runnable(ABC, Generic[Input, Output]):
1509
1650
  from langchain_ollama import ChatOllama
1510
1651
  from langchain_core.output_parsers import StrOutputParser
1511
1652
 
1512
- llm = ChatOllama(model='llama2')
1653
+ llm = ChatOllama(model="llama2")
1513
1654
 
1514
1655
  # Without bind.
1515
- chain = (
1516
- llm
1517
- | StrOutputParser()
1518
- )
1656
+ chain = llm | StrOutputParser()
1519
1657
 
1520
1658
  chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
1521
1659
  # Output is 'One two three four five.'
1522
1660
 
1523
1661
  # With bind.
1524
- chain = (
1525
- llm.bind(stop=["three"])
1526
- | StrOutputParser()
1527
- )
1662
+ chain = llm.bind(stop=["three"]) | StrOutputParser()
1528
1663
 
1529
1664
  chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
1530
1665
  # Output is 'One two'
@@ -1538,14 +1673,15 @@ class Runnable(ABC, Generic[Input, Output]):
1538
1673
  # Sadly Unpack is not well-supported by mypy so this will have to be untyped
1539
1674
  **kwargs: Any,
1540
1675
  ) -> Runnable[Input, Output]:
1541
- """Bind config to a Runnable, returning a new Runnable.
1676
+ """Bind config to a ``Runnable``, returning a new ``Runnable``.
1542
1677
 
1543
1678
  Args:
1544
- config: The config to bind to the Runnable.
1545
- kwargs: Additional keyword arguments to pass to the Runnable.
1679
+ config: The config to bind to the ``Runnable``.
1680
+ kwargs: Additional keyword arguments to pass to the ``Runnable``.
1546
1681
 
1547
1682
  Returns:
1548
- A new Runnable with the config bound.
1683
+ A new ``Runnable`` with the config bound.
1684
+
1549
1685
  """
1550
1686
  return RunnableBinding(
1551
1687
  bound=self,
@@ -1569,22 +1705,22 @@ class Runnable(ABC, Generic[Input, Output]):
1569
1705
  Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]
1570
1706
  ] = None,
1571
1707
  ) -> Runnable[Input, Output]:
1572
- """Bind lifecycle listeners to a Runnable, returning a new Runnable.
1708
+ """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``.
1573
1709
 
1574
- The Run object contains information about the run, including its id,
1575
- type, input, output, error, start_time, end_time, and any tags or metadata
1576
- added to the run.
1710
+ The Run object contains information about the run, including its ``id``,
1711
+ ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
1712
+ any tags or metadata added to the run.
1577
1713
 
1578
1714
  Args:
1579
- on_start: Called before the Runnable starts running, with the Run object.
1580
- Defaults to None.
1581
- on_end: Called after the Runnable finishes running, with the Run object.
1582
- Defaults to None.
1583
- on_error: Called if the Runnable throws an error, with the Run object.
1584
- Defaults to None.
1715
+ on_start: Called before the ``Runnable`` starts running, with the ``Run``
1716
+ object. Defaults to None.
1717
+ on_end: Called after the ``Runnable`` finishes running, with the ``Run``
1718
+ object. Defaults to None.
1719
+ on_error: Called if the ``Runnable`` throws an error, with the ``Run``
1720
+ object. Defaults to None.
1585
1721
 
1586
1722
  Returns:
1587
- A new Runnable with the listeners bound.
1723
+ A new ``Runnable`` with the listeners bound.
1588
1724
 
1589
1725
  Example:
1590
1726
 
@@ -1595,24 +1731,25 @@ class Runnable(ABC, Generic[Input, Output]):
1595
1731
 
1596
1732
  import time
1597
1733
 
1598
- def test_runnable(time_to_sleep : int):
1734
+
1735
+ def test_runnable(time_to_sleep: int):
1599
1736
  time.sleep(time_to_sleep)
1600
1737
 
1738
+
1601
1739
  def fn_start(run_obj: Run):
1602
1740
  print("start_time:", run_obj.start_time)
1603
1741
 
1742
+
1604
1743
  def fn_end(run_obj: Run):
1605
1744
  print("end_time:", run_obj.end_time)
1606
1745
 
1746
+
1607
1747
  chain = RunnableLambda(test_runnable).with_listeners(
1608
- on_start=fn_start,
1609
- on_end=fn_end
1748
+ on_start=fn_start, on_end=fn_end
1610
1749
  )
1611
1750
  chain.invoke(2)
1612
1751
 
1613
1752
  """
1614
- from langchain_core.tracers.root_listeners import RootListenersTracer
1615
-
1616
1753
  return RunnableBinding(
1617
1754
  bound=self,
1618
1755
  config_factories=[
@@ -1636,22 +1773,24 @@ class Runnable(ABC, Generic[Input, Output]):
1636
1773
  on_end: Optional[AsyncListener] = None,
1637
1774
  on_error: Optional[AsyncListener] = None,
1638
1775
  ) -> Runnable[Input, Output]:
1639
- """Bind async lifecycle listeners to a Runnable, returning a new Runnable.
1776
+ """Bind async lifecycle listeners to a ``Runnable``.
1640
1777
 
1641
- The Run object contains information about the run, including its id,
1642
- type, input, output, error, start_time, end_time, and any tags or metadata
1643
- added to the run.
1778
+ Returns a new ``Runnable``.
1779
+
1780
+ The Run object contains information about the run, including its ``id``,
1781
+ ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
1782
+ any tags or metadata added to the run.
1644
1783
 
1645
1784
  Args:
1646
- on_start: Called asynchronously before the Runnable starts running,
1647
- with the Run object. Defaults to None.
1648
- on_end: Called asynchronously after the Runnable finishes running,
1649
- with the Run object. Defaults to None.
1650
- on_error: Called asynchronously if the Runnable throws an error,
1651
- with the Run object. Defaults to None.
1785
+ on_start: Called asynchronously before the ``Runnable`` starts running,
1786
+ with the ``Run`` object. Defaults to None.
1787
+ on_end: Called asynchronously after the ``Runnable`` finishes running,
1788
+ with the ``Run`` object. Defaults to None.
1789
+ on_error: Called asynchronously if the ``Runnable`` throws an error,
1790
+ with the ``Run`` object. Defaults to None.
1652
1791
 
1653
1792
  Returns:
1654
- A new Runnable with the listeners bound.
1793
+ A new ``Runnable`` with the listeners bound.
1655
1794
 
1656
1795
  Example:
1657
1796
 
@@ -1703,8 +1842,6 @@ class Runnable(ABC, Generic[Input, Output]):
1703
1842
  on end callback ends at 2025-03-01T07:05:30.884831+00:00
1704
1843
 
1705
1844
  """
1706
- from langchain_core.tracers.root_listeners import AsyncRootListenersTracer
1707
-
1708
1845
  return RunnableBinding(
1709
1846
  bound=self,
1710
1847
  config_factories=[
@@ -1727,11 +1864,11 @@ class Runnable(ABC, Generic[Input, Output]):
1727
1864
  input_type: Optional[type[Input]] = None,
1728
1865
  output_type: Optional[type[Output]] = None,
1729
1866
  ) -> Runnable[Input, Output]:
1730
- """Bind input and output types to a Runnable, returning a new Runnable.
1867
+ """Bind input and output types to a ``Runnable``, returning a new ``Runnable``.
1731
1868
 
1732
1869
  Args:
1733
- input_type: The input type to bind to the Runnable. Defaults to None.
1734
- output_type: The output type to bind to the Runnable. Defaults to None.
1870
+ input_type: The input type to bind to the ``Runnable``. Defaults to None.
1871
+ output_type: The output type to bind to the ``Runnable``. Defaults to None.
1735
1872
 
1736
1873
  Returns:
1737
1874
  A new Runnable with the types bound.
@@ -1782,7 +1919,7 @@ class Runnable(ABC, Generic[Input, Output]):
1782
1919
  if x == 1:
1783
1920
  raise ValueError("x is 1")
1784
1921
  else:
1785
- pass
1922
+ pass
1786
1923
 
1787
1924
 
1788
1925
  runnable = RunnableLambda(_lambda)
@@ -1794,10 +1931,11 @@ class Runnable(ABC, Generic[Input, Output]):
1794
1931
  except ValueError:
1795
1932
  pass
1796
1933
 
1797
- assert (count == 2)
1934
+ assert count == 2
1798
1935
 
1799
1936
  """
1800
- from langchain_core.runnables.retry import RunnableRetry
1937
+ # Import locally to prevent circular import
1938
+ from langchain_core.runnables.retry import RunnableRetry # noqa: PLC0415
1801
1939
 
1802
1940
  return RunnableRetry(
1803
1941
  bound=self,
@@ -1810,12 +1948,12 @@ class Runnable(ABC, Generic[Input, Output]):
1810
1948
  )
1811
1949
 
1812
1950
  def map(self) -> Runnable[list[Input], list[Output]]:
1813
- """Return a new Runnable that maps a list of inputs to a list of outputs.
1951
+ """Return a new ``Runnable`` that maps a list of inputs to a list of outputs.
1814
1952
 
1815
- Calls invoke() with each input.
1953
+ Calls ``invoke`` with each input.
1816
1954
 
1817
1955
  Returns:
1818
- A new Runnable that maps a list of inputs to a list of outputs.
1956
+ A new ``Runnable`` that maps a list of inputs to a list of outputs.
1819
1957
 
1820
1958
  Example:
1821
1959
 
@@ -1823,11 +1961,13 @@ class Runnable(ABC, Generic[Input, Output]):
1823
1961
 
1824
1962
  from langchain_core.runnables import RunnableLambda
1825
1963
 
1964
+
1826
1965
  def _lambda(x: int) -> int:
1827
1966
  return x + 1
1828
1967
 
1968
+
1829
1969
  runnable = RunnableLambda(_lambda)
1830
- print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
1970
+ print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
1831
1971
 
1832
1972
  """
1833
1973
  return RunnableEach(bound=self)
@@ -1839,22 +1979,24 @@ class Runnable(ABC, Generic[Input, Output]):
1839
1979
  exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,),
1840
1980
  exception_key: Optional[str] = None,
1841
1981
  ) -> RunnableWithFallbacksT[Input, Output]:
1842
- """Add fallbacks to a Runnable, returning a new Runnable.
1982
+ """Add fallbacks to a ``Runnable``, returning a new ``Runnable``.
1843
1983
 
1844
- The new Runnable will try the original Runnable, and then each fallback
1984
+ The new ``Runnable`` will try the original ``Runnable``, and then each fallback
1845
1985
  in order, upon failures.
1846
1986
 
1847
1987
  Args:
1848
- fallbacks: A sequence of runnables to try if the original Runnable fails.
1988
+ fallbacks: A sequence of runnables to try if the original ``Runnable``
1989
+ fails.
1849
1990
  exceptions_to_handle: A tuple of exception types to handle.
1850
- Defaults to (Exception,).
1991
+ Defaults to ``(Exception,)``.
1851
1992
  exception_key: If string is specified then handled exceptions will be passed
1852
- to fallbacks as part of the input under the specified key. If None,
1853
- exceptions will not be passed to fallbacks. If used, the base Runnable
1854
- and its fallbacks must accept a dictionary as input. Defaults to None.
1993
+ to fallbacks as part of the input under the specified key.
1994
+ If None, exceptions will not be passed to fallbacks.
1995
+ If used, the base ``Runnable`` and its fallbacks must accept a
1996
+ dictionary as input. Defaults to None.
1855
1997
 
1856
1998
  Returns:
1857
- A new Runnable that will try the original Runnable, and then each
1999
+ A new ``Runnable`` that will try the original ``Runnable``, and then each
1858
2000
  fallback in order, upon failures.
1859
2001
 
1860
2002
  Example:
@@ -1877,23 +2019,28 @@ class Runnable(ABC, Generic[Input, Output]):
1877
2019
 
1878
2020
  runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
1879
2021
  [RunnableGenerator(_generate)]
1880
- )
1881
- print(''.join(runnable.stream({}))) #foo bar
2022
+ )
2023
+ print("".join(runnable.stream({}))) # foo bar
1882
2024
 
1883
2025
  Args:
1884
- fallbacks: A sequence of runnables to try if the original Runnable fails.
2026
+ fallbacks: A sequence of runnables to try if the original ``Runnable``
2027
+ fails.
1885
2028
  exceptions_to_handle: A tuple of exception types to handle.
1886
2029
  exception_key: If string is specified then handled exceptions will be passed
1887
- to fallbacks as part of the input under the specified key. If None,
1888
- exceptions will not be passed to fallbacks. If used, the base Runnable
1889
- and its fallbacks must accept a dictionary as input.
2030
+ to fallbacks as part of the input under the specified key.
2031
+ If None, exceptions will not be passed to fallbacks.
2032
+ If used, the base ``Runnable`` and its fallbacks must accept a
2033
+ dictionary as input.
1890
2034
 
1891
2035
  Returns:
1892
- A new Runnable that will try the original Runnable, and then each
2036
+ A new ``Runnable`` that will try the original ``Runnable``, and then each
1893
2037
  fallback in order, upon failures.
1894
2038
 
1895
2039
  """
1896
- from langchain_core.runnables.fallbacks import RunnableWithFallbacks
2040
+ # Import locally to prevent circular import
2041
+ from langchain_core.runnables.fallbacks import ( # noqa: PLC0415
2042
+ RunnableWithFallbacks,
2043
+ )
1897
2044
 
1898
2045
  return RunnableWithFallbacks(
1899
2046
  runnable=self,
@@ -1917,9 +2064,13 @@ class Runnable(ABC, Generic[Input, Output]):
1917
2064
  serialized: Optional[dict[str, Any]] = None,
1918
2065
  **kwargs: Optional[Any],
1919
2066
  ) -> Output:
1920
- """Helper method to transform an Input value to an Output value, with callbacks.
2067
+ """Call with config.
2068
+
2069
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2070
+ with callbacks.
2071
+
2072
+ Use this method to implement ``invoke`` in subclasses.
1921
2073
 
1922
- Use this method to implement invoke() in subclasses.
1923
2074
  """
1924
2075
  config = ensure_config(config)
1925
2076
  callback_manager = get_callback_manager_for_config(config)
@@ -1967,9 +2118,12 @@ class Runnable(ABC, Generic[Input, Output]):
1967
2118
  serialized: Optional[dict[str, Any]] = None,
1968
2119
  **kwargs: Optional[Any],
1969
2120
  ) -> Output:
1970
- """Helper method to transform an Input value to an Output value, with callbacks.
2121
+ """Async call with config.
1971
2122
 
1972
- Use this method to implement ainvoke() in subclasses.
2123
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2124
+ with callbacks.
2125
+
2126
+ Use this method to implement ``ainvoke`` in subclasses.
1973
2127
  """
1974
2128
  config = ensure_config(config)
1975
2129
  callback_manager = get_async_callback_manager_for_config(config)
@@ -2016,8 +2170,9 @@ class Runnable(ABC, Generic[Input, Output]):
2016
2170
  ) -> list[Output]:
2017
2171
  """Transform a list of inputs to a list of outputs, with callbacks.
2018
2172
 
2019
- Helper method to transform an Input value to an Output value,
2020
- with callbacks. Use this method to implement invoke() in subclasses.
2173
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2174
+ with callbacks. Use this method to implement ``invoke`` in subclasses.
2175
+
2021
2176
  """
2022
2177
  if not inputs:
2023
2178
  return []
@@ -2089,9 +2244,11 @@ class Runnable(ABC, Generic[Input, Output]):
2089
2244
  ) -> list[Output]:
2090
2245
  """Transform a list of inputs to a list of outputs, with callbacks.
2091
2246
 
2092
- Helper method to transform an Input value to an Output value,
2247
+ Helper method to transform an ``Input`` value to an ``Output`` value,
2093
2248
  with callbacks.
2094
- Use this method to implement invoke() in subclasses.
2249
+
2250
+ Use this method to implement ``invoke`` in subclasses.
2251
+
2095
2252
  """
2096
2253
  if not inputs:
2097
2254
  return []
@@ -2163,13 +2320,12 @@ class Runnable(ABC, Generic[Input, Output]):
2163
2320
  ) -> Iterator[Output]:
2164
2321
  """Transform a stream with config.
2165
2322
 
2166
- Helper method to transform an Iterator of Input values into an Iterator of
2167
- Output values, with callbacks.
2168
- Use this to implement `stream()` or `transform()` in Runnable subclasses.
2169
- """
2170
- # Mixin that is used by both astream log and astream events implementation
2171
- from langchain_core.tracers._streaming import _StreamingCallbackHandler
2323
+ Helper method to transform an ``Iterator`` of ``Input`` values into an
2324
+ ``Iterator`` of ``Output`` values, with callbacks.
2172
2325
 
2326
+ Use this to implement ``stream`` or ``transform`` in ``Runnable`` subclasses.
2327
+
2328
+ """
2173
2329
  # tee the input so we can iterate over it twice
2174
2330
  input_for_tracing, input_for_transform = tee(inputs, 2)
2175
2331
  # Start the input iterator to ensure the input Runnable starts before this one
@@ -2267,13 +2423,12 @@ class Runnable(ABC, Generic[Input, Output]):
2267
2423
  ) -> AsyncIterator[Output]:
2268
2424
  """Transform a stream with config.
2269
2425
 
2270
- Helper method to transform an Async Iterator of Input values into an Async
2271
- Iterator of Output values, with callbacks.
2272
- Use this to implement `astream()` or `atransform()` in Runnable subclasses.
2273
- """
2274
- # Mixin that is used by both astream log and astream events implementation
2275
- from langchain_core.tracers._streaming import _StreamingCallbackHandler
2426
+ Helper method to transform an Async ``Iterator`` of ``Input`` values into an
2427
+ Async ``Iterator`` of ``Output`` values, with callbacks.
2428
+
2429
+ Use this to implement ``astream`` or ``atransform`` in ``Runnable`` subclasses.
2276
2430
 
2431
+ """
2277
2432
  # tee the input so we can iterate over it twice
2278
2433
  input_for_tracing, input_for_transform = atee(inputs, 2)
2279
2434
  # Start the input iterator to ensure the input Runnable starts before this one
@@ -2362,12 +2517,12 @@ class Runnable(ABC, Generic[Input, Output]):
2362
2517
  description: Optional[str] = None,
2363
2518
  arg_types: Optional[dict[str, type]] = None,
2364
2519
  ) -> BaseTool:
2365
- """Create a BaseTool from a Runnable.
2520
+ """Create a ``BaseTool`` from a ``Runnable``.
2366
2521
 
2367
- ``as_tool`` will instantiate a BaseTool with a name, description, and
2368
- ``args_schema`` from a Runnable. Where possible, schemas are inferred
2522
+ ``as_tool`` will instantiate a ``BaseTool`` with a name, description, and
2523
+ ``args_schema`` from a ``Runnable``. Where possible, schemas are inferred
2369
2524
  from ``runnable.get_input_schema``. Alternatively (e.g., if the
2370
- Runnable takes a dict as input and the specific dict keys are not typed),
2525
+ ``Runnable`` takes a dict as input and the specific dict keys are not typed),
2371
2526
  the schema can be specified directly with ``args_schema``. You can also
2372
2527
  pass ``arg_types`` to just specify the required arguments and their types.
2373
2528
 
@@ -2376,9 +2531,11 @@ class Runnable(ABC, Generic[Input, Output]):
2376
2531
  name: The name of the tool. Defaults to None.
2377
2532
  description: The description of the tool. Defaults to None.
2378
2533
  arg_types: A dictionary of argument names to types. Defaults to None.
2534
+ message_version: Version of ``ToolMessage`` to return given
2535
+ :class:`~langchain_core.messages.content_blocks.ToolCall` input.
2379
2536
 
2380
2537
  Returns:
2381
- A BaseTool instance.
2538
+ A ``BaseTool`` instance.
2382
2539
 
2383
2540
  Typed dict input:
2384
2541
 
@@ -2387,13 +2544,16 @@ class Runnable(ABC, Generic[Input, Output]):
2387
2544
  from typing_extensions import TypedDict
2388
2545
  from langchain_core.runnables import RunnableLambda
2389
2546
 
2547
+
2390
2548
  class Args(TypedDict):
2391
2549
  a: int
2392
2550
  b: list[int]
2393
2551
 
2552
+
2394
2553
  def f(x: Args) -> str:
2395
2554
  return str(x["a"] * max(x["b"]))
2396
2555
 
2556
+
2397
2557
  runnable = RunnableLambda(f)
2398
2558
  as_tool = runnable.as_tool()
2399
2559
  as_tool.invoke({"a": 3, "b": [1, 2]})
@@ -2426,9 +2586,11 @@ class Runnable(ABC, Generic[Input, Output]):
2426
2586
  from typing import Any
2427
2587
  from langchain_core.runnables import RunnableLambda
2428
2588
 
2589
+
2429
2590
  def f(x: dict[str, Any]) -> str:
2430
2591
  return str(x["a"] * max(x["b"]))
2431
2592
 
2593
+
2432
2594
  runnable = RunnableLambda(f)
2433
2595
  as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]})
2434
2596
  as_tool.invoke({"a": 3, "b": [1, 2]})
@@ -2439,12 +2601,15 @@ class Runnable(ABC, Generic[Input, Output]):
2439
2601
 
2440
2602
  from langchain_core.runnables import RunnableLambda
2441
2603
 
2604
+
2442
2605
  def f(x: str) -> str:
2443
2606
  return x + "a"
2444
2607
 
2608
+
2445
2609
  def g(x: str) -> str:
2446
2610
  return x + "z"
2447
2611
 
2612
+
2448
2613
  runnable = RunnableLambda(f) | g
2449
2614
  as_tool = runnable.as_tool()
2450
2615
  as_tool.invoke("b")
@@ -2453,7 +2618,7 @@ class Runnable(ABC, Generic[Input, Output]):
2453
2618
 
2454
2619
  """
2455
2620
  # Avoid circular import
2456
- from langchain_core.tools import convert_runnable_to_tool
2621
+ from langchain_core.tools import convert_runnable_to_tool # noqa: PLC0415
2457
2622
 
2458
2623
  return convert_runnable_to_tool(
2459
2624
  self,
@@ -2477,10 +2642,11 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2477
2642
 
2478
2643
  @override
2479
2644
  def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:
2480
- """Serialize the Runnable to JSON.
2645
+ """Serialize the ``Runnable`` to JSON.
2481
2646
 
2482
2647
  Returns:
2483
- A JSON-serializable representation of the Runnable.
2648
+ A JSON-serializable representation of the ``Runnable``.
2649
+
2484
2650
  """
2485
2651
  dumped = super().to_json()
2486
2652
  with contextlib.suppress(Exception):
@@ -2490,13 +2656,16 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2490
2656
  def configurable_fields(
2491
2657
  self, **kwargs: AnyConfigurableField
2492
2658
  ) -> RunnableSerializable[Input, Output]:
2493
- """Configure particular Runnable fields at runtime.
2659
+ """Configure particular ``Runnable`` fields at runtime.
2494
2660
 
2495
2661
  Args:
2496
- **kwargs: A dictionary of ConfigurableField instances to configure.
2662
+ **kwargs: A dictionary of ``ConfigurableField`` instances to configure.
2663
+
2664
+ Raises:
2665
+ ValueError: If a configuration key is not found in the ``Runnable``.
2497
2666
 
2498
2667
  Returns:
2499
- A new Runnable with the fields configured.
2668
+ A new ``Runnable`` with the fields configured.
2500
2669
 
2501
2670
  .. code-block:: python
2502
2671
 
@@ -2513,18 +2682,22 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2513
2682
 
2514
2683
  # max_tokens = 20
2515
2684
  print(
2516
- "max_tokens_20: ",
2517
- model.invoke("tell me something about chess").content
2685
+ "max_tokens_20: ", model.invoke("tell me something about chess").content
2518
2686
  )
2519
2687
 
2520
2688
  # max_tokens = 200
2521
- print("max_tokens_200: ", model.with_config(
2522
- configurable={"output_token_number": 200}
2523
- ).invoke("tell me something about chess").content
2689
+ print(
2690
+ "max_tokens_200: ",
2691
+ model.with_config(configurable={"output_token_number": 200})
2692
+ .invoke("tell me something about chess")
2693
+ .content,
2524
2694
  )
2525
2695
 
2526
2696
  """
2527
- from langchain_core.runnables.configurable import RunnableConfigurableFields
2697
+ # Import locally to prevent circular import
2698
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
2699
+ RunnableConfigurableFields,
2700
+ )
2528
2701
 
2529
2702
  model_fields = type(self).model_fields
2530
2703
  for key in kwargs:
@@ -2545,20 +2718,20 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2545
2718
  prefix_keys: bool = False,
2546
2719
  **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]],
2547
2720
  ) -> RunnableSerializable[Input, Output]:
2548
- """Configure alternatives for Runnables that can be set at runtime.
2721
+ """Configure alternatives for ``Runnables`` that can be set at runtime.
2549
2722
 
2550
2723
  Args:
2551
- which: The ConfigurableField instance that will be used to select the
2724
+ which: The ``ConfigurableField`` instance that will be used to select the
2552
2725
  alternative.
2553
2726
  default_key: The default key to use if no alternative is selected.
2554
2727
  Defaults to ``'default'``.
2555
- prefix_keys: Whether to prefix the keys with the ConfigurableField id.
2728
+ prefix_keys: Whether to prefix the keys with the ``ConfigurableField`` id.
2556
2729
  Defaults to False.
2557
- **kwargs: A dictionary of keys to Runnable instances or callables that
2558
- return Runnable instances.
2730
+ **kwargs: A dictionary of keys to ``Runnable`` instances or callables that
2731
+ return ``Runnable`` instances.
2559
2732
 
2560
2733
  Returns:
2561
- A new Runnable with the alternatives configured.
2734
+ A new ``Runnable`` with the alternatives configured.
2562
2735
 
2563
2736
  .. code-block:: python
2564
2737
 
@@ -2571,7 +2744,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2571
2744
  ).configurable_alternatives(
2572
2745
  ConfigurableField(id="llm"),
2573
2746
  default_key="anthropic",
2574
- openai=ChatOpenAI()
2747
+ openai=ChatOpenAI(),
2575
2748
  )
2576
2749
 
2577
2750
  # uses the default model ChatAnthropic
@@ -2579,13 +2752,14 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2579
2752
 
2580
2753
  # uses ChatOpenAI
2581
2754
  print(
2582
- model.with_config(
2583
- configurable={"llm": "openai"}
2584
- ).invoke("which organization created you?").content
2755
+ model.with_config(configurable={"llm": "openai"})
2756
+ .invoke("which organization created you?")
2757
+ .content
2585
2758
  )
2586
2759
 
2587
2760
  """
2588
- from langchain_core.runnables.configurable import (
2761
+ # Import locally to prevent circular import
2762
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
2589
2763
  RunnableConfigurableAlternatives,
2590
2764
  )
2591
2765
 
@@ -2601,7 +2775,11 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
2601
2775
  def _seq_input_schema(
2602
2776
  steps: list[Runnable[Any, Any]], config: Optional[RunnableConfig]
2603
2777
  ) -> type[BaseModel]:
2604
- from langchain_core.runnables.passthrough import RunnableAssign, RunnablePick
2778
+ # Import locally to prevent circular import
2779
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
2780
+ RunnableAssign,
2781
+ RunnablePick,
2782
+ )
2605
2783
 
2606
2784
  first = steps[0]
2607
2785
  if len(steps) == 1:
@@ -2627,7 +2805,11 @@ def _seq_input_schema(
2627
2805
  def _seq_output_schema(
2628
2806
  steps: list[Runnable[Any, Any]], config: Optional[RunnableConfig]
2629
2807
  ) -> type[BaseModel]:
2630
- from langchain_core.runnables.passthrough import RunnableAssign, RunnablePick
2808
+ # Import locally to prevent circular import
2809
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
2810
+ RunnableAssign,
2811
+ RunnablePick,
2812
+ )
2631
2813
 
2632
2814
  last = steps[-1]
2633
2815
  if len(steps) == 1:
@@ -2672,25 +2854,26 @@ def _seq_output_schema(
2672
2854
 
2673
2855
 
2674
2856
  class RunnableSequence(RunnableSerializable[Input, Output]):
2675
- """Sequence of Runnables, where the output of each is the input of the next.
2857
+ """Sequence of ``Runnables``, where the output of each is the input of the next.
2676
2858
 
2677
- **RunnableSequence** is the most important composition operator in LangChain
2859
+ **``RunnableSequence``** is the most important composition operator in LangChain
2678
2860
  as it is used in virtually every chain.
2679
2861
 
2680
- A RunnableSequence can be instantiated directly or more commonly by using the `|`
2681
- operator where either the left or right operands (or both) must be a Runnable.
2862
+ A ``RunnableSequence`` can be instantiated directly or more commonly by using the
2863
+ ``|`` operator where either the left or right operands (or both) must be a
2864
+ ``Runnable``.
2682
2865
 
2683
- Any RunnableSequence automatically supports sync, async, batch.
2866
+ Any ``RunnableSequence`` automatically supports sync, async, batch.
2684
2867
 
2685
- The default implementations of `batch` and `abatch` utilize threadpools and
2686
- asyncio gather and will be faster than naive invocation of invoke or ainvoke
2687
- for IO bound Runnables.
2868
+ The default implementations of ``batch`` and ``abatch`` utilize threadpools and
2869
+ asyncio gather and will be faster than naive invocation of ``invoke`` or ``ainvoke``
2870
+ for IO bound ``Runnable``s.
2688
2871
 
2689
2872
  Batching is implemented by invoking the batch method on each component of the
2690
- RunnableSequence in order.
2873
+ ``RunnableSequence`` in order.
2691
2874
 
2692
- A RunnableSequence preserves the streaming properties of its components, so if all
2693
- components of the sequence implement a `transform` method -- which
2875
+ A ``RunnableSequence`` preserves the streaming properties of its components, so if
2876
+ all components of the sequence implement a ``transform`` method -- which
2694
2877
  is the method that implements the logic to map a streaming input to a streaming
2695
2878
  output -- then the sequence will be able to stream input to output!
2696
2879
 
@@ -2698,26 +2881,30 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2698
2881
  streaming will only begin after this component is run. If there are
2699
2882
  multiple blocking components, streaming begins after the last one.
2700
2883
 
2701
- Please note: RunnableLambdas do not support `transform` by default! So if
2702
- you need to use a RunnableLambdas be careful about where you place them in a
2703
- RunnableSequence (if you need to use the .stream()/.astream() methods).
2884
+ .. note::
2885
+ ``RunnableLambdas`` do not support ``transform`` by default! So if you need to
2886
+ use a ``RunnableLambdas`` be careful about where you place them in a
2887
+ ``RunnableSequence`` (if you need to use the ``stream``/``astream`` methods).
2704
2888
 
2705
2889
  If you need arbitrary logic and need streaming, you can subclass
2706
- Runnable, and implement `transform` for whatever logic you need.
2890
+ Runnable, and implement ``transform`` for whatever logic you need.
2707
2891
 
2708
2892
  Here is a simple example that uses simple functions to illustrate the use of
2709
- RunnableSequence:
2893
+ ``RunnableSequence``:
2710
2894
 
2711
2895
  .. code-block:: python
2712
2896
 
2713
2897
  from langchain_core.runnables import RunnableLambda
2714
2898
 
2899
+
2715
2900
  def add_one(x: int) -> int:
2716
2901
  return x + 1
2717
2902
 
2903
+
2718
2904
  def mul_two(x: int) -> int:
2719
2905
  return x * 2
2720
2906
 
2907
+
2721
2908
  runnable_1 = RunnableLambda(add_one)
2722
2909
  runnable_2 = RunnableLambda(mul_two)
2723
2910
  sequence = runnable_1 | runnable_2
@@ -2737,17 +2924,17 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2737
2924
  from langchain_openai import ChatOpenAI
2738
2925
 
2739
2926
  prompt = PromptTemplate.from_template(
2740
- 'In JSON format, give me a list of {topic} and their '
2741
- 'corresponding names in French, Spanish and in a '
2742
- 'Cat Language.'
2927
+ "In JSON format, give me a list of {topic} and their "
2928
+ "corresponding names in French, Spanish and in a "
2929
+ "Cat Language."
2743
2930
  )
2744
2931
 
2745
2932
  model = ChatOpenAI()
2746
2933
  chain = prompt | model | SimpleJsonOutputParser()
2747
2934
 
2748
- async for chunk in chain.astream({'topic': 'colors'}):
2749
- print('-') # noqa: T201
2750
- print(chunk, sep='', flush=True) # noqa: T201
2935
+ async for chunk in chain.astream({"topic": "colors"}):
2936
+ print("-") # noqa: T201
2937
+ print(chunk, sep="", flush=True) # noqa: T201
2751
2938
 
2752
2939
  """
2753
2940
 
@@ -2755,11 +2942,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2755
2942
  # purposes. It allows specifying the `Input` on the first type, the `Output` of
2756
2943
  # the last type.
2757
2944
  first: Runnable[Input, Any]
2758
- """The first Runnable in the sequence."""
2945
+ """The first ``Runnable`` in the sequence."""
2759
2946
  middle: list[Runnable[Any, Any]] = Field(default_factory=list)
2760
- """The middle Runnables in the sequence."""
2947
+ """The middle ``Runnable`` in the sequence."""
2761
2948
  last: Runnable[Any, Output]
2762
- """The last Runnable in the sequence."""
2949
+ """The last ``Runnable`` in the sequence."""
2763
2950
 
2764
2951
  def __init__(
2765
2952
  self,
@@ -2769,13 +2956,13 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2769
2956
  middle: Optional[list[Runnable[Any, Any]]] = None,
2770
2957
  last: Optional[Runnable[Any, Any]] = None,
2771
2958
  ) -> None:
2772
- """Create a new RunnableSequence.
2959
+ """Create a new ``RunnableSequence``.
2773
2960
 
2774
2961
  Args:
2775
2962
  steps: The steps to include in the sequence.
2776
- name: The name of the Runnable. Defaults to None.
2777
- first: The first Runnable in the sequence. Defaults to None.
2778
- middle: The middle Runnables in the sequence. Defaults to None.
2963
+ name: The name of the ``Runnable``. Defaults to None.
2964
+ first: The first ``Runnable`` in the sequence. Defaults to None.
2965
+ middle: The middle ``Runnables`` in the sequence. Defaults to None.
2779
2966
  last: The last Runnable in the sequence. Defaults to None.
2780
2967
 
2781
2968
  Raises:
@@ -2792,7 +2979,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2792
2979
  if len(steps_flat) < 2:
2793
2980
  msg = f"RunnableSequence must have at least 2 steps, got {len(steps_flat)}"
2794
2981
  raise ValueError(msg)
2795
- super().__init__( # type: ignore[call-arg]
2982
+ super().__init__(
2796
2983
  first=steps_flat[0],
2797
2984
  middle=list(steps_flat[1:-1]),
2798
2985
  last=steps_flat[-1],
@@ -2802,26 +2989,26 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2802
2989
  @classmethod
2803
2990
  @override
2804
2991
  def get_lc_namespace(cls) -> list[str]:
2992
+ """Get the namespace of the langchain object.
2993
+
2994
+ Returns:
2995
+ ``["langchain", "schema", "runnable"]``
2996
+ """
2805
2997
  return ["langchain", "schema", "runnable"]
2806
2998
 
2807
2999
  @property
2808
3000
  def steps(self) -> list[Runnable[Any, Any]]:
2809
- """All the Runnables that make up the sequence in order.
3001
+ """All the ``Runnable``s that make up the sequence in order.
2810
3002
 
2811
3003
  Returns:
2812
- A list of Runnables.
3004
+ A list of ``Runnable``s.
2813
3005
  """
2814
3006
  return [self.first, *self.middle, self.last]
2815
3007
 
2816
3008
  @classmethod
2817
3009
  @override
2818
3010
  def is_lc_serializable(cls) -> bool:
2819
- """Check if the object is serializable.
2820
-
2821
- Returns:
2822
- True if the object is serializable, False otherwise.
2823
- Defaults to True.
2824
- """
3011
+ """Return True as this class is serializable."""
2825
3012
  return True
2826
3013
 
2827
3014
  model_config = ConfigDict(
@@ -2831,26 +3018,27 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2831
3018
  @property
2832
3019
  @override
2833
3020
  def InputType(self) -> type[Input]:
2834
- """The type of the input to the Runnable."""
3021
+ """The type of the input to the ``Runnable``."""
2835
3022
  return self.first.InputType
2836
3023
 
2837
3024
  @property
2838
3025
  @override
2839
3026
  def OutputType(self) -> type[Output]:
2840
- """The type of the output of the Runnable."""
3027
+ """The type of the output of the ``Runnable``."""
2841
3028
  return self.last.OutputType
2842
3029
 
2843
3030
  @override
2844
3031
  def get_input_schema(
2845
3032
  self, config: Optional[RunnableConfig] = None
2846
3033
  ) -> type[BaseModel]:
2847
- """Get the input schema of the Runnable.
3034
+ """Get the input schema of the ``Runnable``.
2848
3035
 
2849
3036
  Args:
2850
3037
  config: The config to use. Defaults to None.
2851
3038
 
2852
3039
  Returns:
2853
- The input schema of the Runnable.
3040
+ The input schema of the ``Runnable``.
3041
+
2854
3042
  """
2855
3043
  return _seq_input_schema(self.steps, config)
2856
3044
 
@@ -2858,25 +3046,28 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2858
3046
  def get_output_schema(
2859
3047
  self, config: Optional[RunnableConfig] = None
2860
3048
  ) -> type[BaseModel]:
2861
- """Get the output schema of the Runnable.
3049
+ """Get the output schema of the ``Runnable``.
2862
3050
 
2863
3051
  Args:
2864
3052
  config: The config to use. Defaults to None.
2865
3053
 
2866
3054
  Returns:
2867
- The output schema of the Runnable.
3055
+ The output schema of the ``Runnable``.
3056
+
2868
3057
  """
2869
3058
  return _seq_output_schema(self.steps, config)
2870
3059
 
2871
3060
  @property
2872
3061
  @override
2873
3062
  def config_specs(self) -> list[ConfigurableFieldSpec]:
2874
- """Get the config specs of the Runnable.
3063
+ """Get the config specs of the ``Runnable``.
2875
3064
 
2876
3065
  Returns:
2877
- The config specs of the Runnable.
3066
+ The config specs of the ``Runnable``.
3067
+
2878
3068
  """
2879
- from langchain_core.beta.runnables.context import (
3069
+ # Import locally to prevent circular import
3070
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
2880
3071
  CONTEXT_CONFIG_PREFIX,
2881
3072
  _key_from_id,
2882
3073
  )
@@ -2922,18 +3113,20 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
2922
3113
 
2923
3114
  @override
2924
3115
  def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
2925
- """Get the graph representation of the Runnable.
3116
+ """Get the graph representation of the ``Runnable``.
2926
3117
 
2927
3118
  Args:
2928
3119
  config: The config to use. Defaults to None.
2929
3120
 
2930
3121
  Returns:
2931
- The graph representation of the Runnable.
3122
+ The graph representation of the ``Runnable``.
2932
3123
 
2933
3124
  Raises:
2934
- ValueError: If a Runnable has no first or last node.
3125
+ ValueError: If a ``Runnable`` has no first or last node.
3126
+
2935
3127
  """
2936
- from langchain_core.runnables.graph import Graph
3128
+ # Import locally to prevent circular import
3129
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
2937
3130
 
2938
3131
  graph = Graph()
2939
3132
  for step in self.steps:
@@ -3021,7 +3214,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3021
3214
  def invoke(
3022
3215
  self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
3023
3216
  ) -> Output:
3024
- from langchain_core.beta.runnables.context import config_with_context
3217
+ # Import locally to prevent circular import
3218
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3219
+ config_with_context,
3220
+ )
3025
3221
 
3026
3222
  # setup callbacks and context
3027
3223
  config = config_with_context(ensure_config(config), self.steps)
@@ -3062,7 +3258,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3062
3258
  config: Optional[RunnableConfig] = None,
3063
3259
  **kwargs: Optional[Any],
3064
3260
  ) -> Output:
3065
- from langchain_core.beta.runnables.context import aconfig_with_context
3261
+ # Import locally to prevent circular import
3262
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3263
+ aconfig_with_context,
3264
+ )
3066
3265
 
3067
3266
  # setup callbacks and context
3068
3267
  config = aconfig_with_context(ensure_config(config), self.steps)
@@ -3106,8 +3305,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3106
3305
  return_exceptions: bool = False,
3107
3306
  **kwargs: Optional[Any],
3108
3307
  ) -> list[Output]:
3109
- from langchain_core.beta.runnables.context import config_with_context
3110
- from langchain_core.callbacks.manager import CallbackManager
3308
+ # Import locally to prevent circular import
3309
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3310
+ config_with_context,
3311
+ )
3111
3312
 
3112
3313
  if not inputs:
3113
3314
  return []
@@ -3236,8 +3437,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3236
3437
  return_exceptions: bool = False,
3237
3438
  **kwargs: Optional[Any],
3238
3439
  ) -> list[Output]:
3239
- from langchain_core.beta.runnables.context import aconfig_with_context
3240
- from langchain_core.callbacks.manager import AsyncCallbackManager
3440
+ # Import locally to prevent circular import
3441
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3442
+ aconfig_with_context,
3443
+ )
3241
3444
 
3242
3445
  if not inputs:
3243
3446
  return []
@@ -3367,7 +3570,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3367
3570
  config: RunnableConfig,
3368
3571
  **kwargs: Any,
3369
3572
  ) -> Iterator[Output]:
3370
- from langchain_core.beta.runnables.context import config_with_context
3573
+ # Import locally to prevent circular import
3574
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3575
+ config_with_context,
3576
+ )
3371
3577
 
3372
3578
  steps = [self.first, *self.middle, self.last]
3373
3579
  config = config_with_context(config, self.steps)
@@ -3394,7 +3600,10 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3394
3600
  config: RunnableConfig,
3395
3601
  **kwargs: Any,
3396
3602
  ) -> AsyncIterator[Output]:
3397
- from langchain_core.beta.runnables.context import aconfig_with_context
3603
+ # Import locally to prevent circular import
3604
+ from langchain_core.beta.runnables.context import ( # noqa: PLC0415
3605
+ aconfig_with_context,
3606
+ )
3398
3607
 
3399
3608
  steps = [self.first, *self.middle, self.last]
3400
3609
  config = aconfig_with_context(config, self.steps)
@@ -3469,33 +3678,37 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
3469
3678
 
3470
3679
 
3471
3680
  class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3472
- """Runnable that runs a mapping of Runnables in parallel.
3681
+ """Runnable that runs a mapping of ``Runnable``s in parallel.
3473
3682
 
3474
3683
  Returns a mapping of their outputs.
3475
3684
 
3476
- RunnableParallel is one of the two main composition primitives for the LCEL,
3477
- alongside RunnableSequence. It invokes Runnables concurrently, providing the same
3478
- input to each.
3685
+ ``RunnableParallel`` is one of the two main composition primitives for the LCEL,
3686
+ alongside ``RunnableSequence``. It invokes ``Runnable``s concurrently, providing the
3687
+ same input to each.
3479
3688
 
3480
- A RunnableParallel can be instantiated directly or by using a dict literal within a
3481
- sequence.
3689
+ A ``RunnableParallel`` can be instantiated directly or by using a dict literal
3690
+ within a sequence.
3482
3691
 
3483
3692
  Here is a simple example that uses functions to illustrate the use of
3484
- RunnableParallel:
3693
+ ``RunnableParallel``:
3485
3694
 
3486
3695
  .. code-block:: python
3487
3696
 
3488
3697
  from langchain_core.runnables import RunnableLambda
3489
3698
 
3699
+
3490
3700
  def add_one(x: int) -> int:
3491
3701
  return x + 1
3492
3702
 
3703
+
3493
3704
  def mul_two(x: int) -> int:
3494
3705
  return x * 2
3495
3706
 
3707
+
3496
3708
  def mul_three(x: int) -> int:
3497
3709
  return x * 3
3498
3710
 
3711
+
3499
3712
  runnable_1 = RunnableLambda(add_one)
3500
3713
  runnable_2 = RunnableLambda(mul_two)
3501
3714
  runnable_3 = RunnableLambda(mul_three)
@@ -3520,8 +3733,8 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3520
3733
  sequence.batch([1, 2, 3])
3521
3734
  await sequence.abatch([1, 2, 3])
3522
3735
 
3523
- RunnableParallel makes it easy to run Runnables in parallel. In the below example,
3524
- we simultaneously stream output from two different Runnables:
3736
+ ``RunnableParallel`` makes it easy to run ``Runnable``s in parallel. In the below
3737
+ example, we simultaneously stream output from two different ``Runnables``:
3525
3738
 
3526
3739
  .. code-block:: python
3527
3740
 
@@ -3531,8 +3744,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3531
3744
 
3532
3745
  model = ChatOpenAI()
3533
3746
  joke_chain = (
3534
- ChatPromptTemplate.from_template("tell me a joke about {topic}")
3535
- | model
3747
+ ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
3536
3748
  )
3537
3749
  poem_chain = (
3538
3750
  ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
@@ -3570,26 +3782,33 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3570
3782
  Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]],
3571
3783
  ],
3572
3784
  ) -> None:
3573
- """Create a RunnableParallel.
3785
+ """Create a ``RunnableParallel``.
3574
3786
 
3575
3787
  Args:
3576
3788
  steps__: The steps to include. Defaults to None.
3577
3789
  **kwargs: Additional steps to include.
3790
+
3578
3791
  """
3579
3792
  merged = {**steps__} if steps__ is not None else {}
3580
3793
  merged.update(kwargs)
3581
- super().__init__( # type: ignore[call-arg]
3794
+ super().__init__(
3582
3795
  steps__={key: coerce_to_runnable(r) for key, r in merged.items()}
3583
3796
  )
3584
3797
 
3585
3798
  @classmethod
3586
3799
  @override
3587
3800
  def is_lc_serializable(cls) -> bool:
3801
+ """Return True as this class is serializable."""
3588
3802
  return True
3589
3803
 
3590
3804
  @classmethod
3591
3805
  @override
3592
3806
  def get_lc_namespace(cls) -> list[str]:
3807
+ """Get the namespace of the langchain object.
3808
+
3809
+ Returns:
3810
+ ``["langchain", "schema", "runnable"]``
3811
+ """
3593
3812
  return ["langchain", "schema", "runnable"]
3594
3813
 
3595
3814
  model_config = ConfigDict(
@@ -3600,14 +3819,15 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3600
3819
  def get_name(
3601
3820
  self, suffix: Optional[str] = None, *, name: Optional[str] = None
3602
3821
  ) -> str:
3603
- """Get the name of the Runnable.
3822
+ """Get the name of the ``Runnable``.
3604
3823
 
3605
3824
  Args:
3606
3825
  suffix: The suffix to use. Defaults to None.
3607
3826
  name: The name to use. Defaults to None.
3608
3827
 
3609
3828
  Returns:
3610
- The name of the Runnable.
3829
+ The name of the ``Runnable``.
3830
+
3611
3831
  """
3612
3832
  name = name or self.name or f"RunnableParallel<{','.join(self.steps__.keys())}>"
3613
3833
  return super().get_name(suffix, name=name)
@@ -3615,7 +3835,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3615
3835
  @property
3616
3836
  @override
3617
3837
  def InputType(self) -> Any:
3618
- """The type of the input to the Runnable."""
3838
+ """The type of the input to the ``Runnable``."""
3619
3839
  for step in self.steps__.values():
3620
3840
  if step.InputType:
3621
3841
  return step.InputType
@@ -3626,13 +3846,14 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3626
3846
  def get_input_schema(
3627
3847
  self, config: Optional[RunnableConfig] = None
3628
3848
  ) -> type[BaseModel]:
3629
- """Get the input schema of the Runnable.
3849
+ """Get the input schema of the ``Runnable``.
3630
3850
 
3631
3851
  Args:
3632
3852
  config: The config to use. Defaults to None.
3633
3853
 
3634
3854
  Returns:
3635
- The input schema of the Runnable.
3855
+ The input schema of the ``Runnable``.
3856
+
3636
3857
  """
3637
3858
  if all(
3638
3859
  s.get_input_schema(config).model_json_schema().get("type", "object")
@@ -3656,13 +3877,14 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3656
3877
  def get_output_schema(
3657
3878
  self, config: Optional[RunnableConfig] = None
3658
3879
  ) -> type[BaseModel]:
3659
- """Get the output schema of the Runnable.
3880
+ """Get the output schema of the ``Runnable``.
3660
3881
 
3661
3882
  Args:
3662
3883
  config: The config to use. Defaults to None.
3663
3884
 
3664
3885
  Returns:
3665
- The output schema of the Runnable.
3886
+ The output schema of the ``Runnable``.
3887
+
3666
3888
  """
3667
3889
  fields = {k: (v.OutputType, ...) for k, v in self.steps__.items()}
3668
3890
  return create_model_v2(self.get_name("Output"), field_definitions=fields)
@@ -3670,10 +3892,11 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3670
3892
  @property
3671
3893
  @override
3672
3894
  def config_specs(self) -> list[ConfigurableFieldSpec]:
3673
- """Get the config specs of the Runnable.
3895
+ """Get the config specs of the ``Runnable``.
3674
3896
 
3675
3897
  Returns:
3676
- The config specs of the Runnable.
3898
+ The config specs of the ``Runnable``.
3899
+
3677
3900
  """
3678
3901
  return get_unique_config_specs(
3679
3902
  spec for step in self.steps__.values() for spec in step.config_specs
@@ -3681,18 +3904,20 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3681
3904
 
3682
3905
  @override
3683
3906
  def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
3684
- """Get the graph representation of the Runnable.
3907
+ """Get the graph representation of the ``Runnable``.
3685
3908
 
3686
3909
  Args:
3687
3910
  config: The config to use. Defaults to None.
3688
3911
 
3689
3912
  Returns:
3690
- The graph representation of the Runnable.
3913
+ The graph representation of the ``Runnable``.
3691
3914
 
3692
3915
  Raises:
3693
- ValueError: If a Runnable has no first or last node.
3916
+ ValueError: If a ``Runnable`` has no first or last node.
3917
+
3694
3918
  """
3695
- from langchain_core.runnables.graph import Graph
3919
+ # Import locally to prevent circular import
3920
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
3696
3921
 
3697
3922
  graph = Graph()
3698
3923
  input_node = graph.add_node(self.get_input_schema(config))
@@ -3728,8 +3953,6 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
3728
3953
  def invoke(
3729
3954
  self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
3730
3955
  ) -> dict[str, Any]:
3731
- from langchain_core.callbacks.manager import CallbackManager
3732
-
3733
3956
  # setup callbacks
3734
3957
  config = ensure_config(config)
3735
3958
  callback_manager = CallbackManager.configure(
@@ -3987,22 +4210,24 @@ RunnableMap = RunnableParallel
3987
4210
 
3988
4211
 
3989
4212
  class RunnableGenerator(Runnable[Input, Output]):
3990
- """Runnable that runs a generator function.
4213
+ """``Runnable`` that runs a generator function.
3991
4214
 
3992
- RunnableGenerators can be instantiated directly or by using a generator within
4215
+ ``RunnableGenerator``s can be instantiated directly or by using a generator within
3993
4216
  a sequence.
3994
4217
 
3995
- RunnableGenerators can be used to implement custom behavior, such as custom output
3996
- parsers, while preserving streaming capabilities. Given a generator function with
3997
- a signature Iterator[A] -> Iterator[B], wrapping it in a RunnableGenerator allows
3998
- it to emit output chunks as soon as they are streamed in from the previous step.
4218
+ ``RunnableGenerator``s can be used to implement custom behavior, such as custom
4219
+ output parsers, while preserving streaming capabilities. Given a generator function
4220
+ with a signature ``Iterator[A] -> Iterator[B]``, wrapping it in a
4221
+ ``RunnableGenerator`` allows it to emit output chunks as soon as they are streamed
4222
+ in from the previous step.
3999
4223
 
4000
- Note that if a generator function has a signature A -> Iterator[B], such that it
4001
- requires its input from the previous step to be completed before emitting chunks
4002
- (e.g., most LLMs need the entire prompt available to start generating), it can
4003
- instead be wrapped in a RunnableLambda.
4224
+ .. note::
4225
+ If a generator function has a ``signature A -> Iterator[B]``, such that it
4226
+ requires its input from the previous step to be completed before emitting chunks
4227
+ (e.g., most LLMs need the entire prompt available to start generating), it can
4228
+ instead be wrapped in a ``RunnableLambda``.
4004
4229
 
4005
- Here is an example to show the basic mechanics of a RunnableGenerator:
4230
+ Here is an example to show the basic mechanics of a ``RunnableGenerator``:
4006
4231
 
4007
4232
  .. code-block:: python
4008
4233
 
@@ -4027,11 +4252,12 @@ class RunnableGenerator(Runnable[Input, Output]):
4027
4252
  for token in ["Have", " a", " nice", " day"]:
4028
4253
  yield token
4029
4254
 
4255
+
4030
4256
  runnable = RunnableGenerator(agen)
4031
4257
  await runnable.ainvoke(None) # "Have a nice day"
4032
- [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
4258
+ [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
4033
4259
 
4034
- RunnableGenerator makes it easy to implement custom behavior within a streaming
4260
+ ``RunnableGenerator`` makes it easy to implement custom behavior within a streaming
4035
4261
  context. Below we show an example:
4036
4262
 
4037
4263
  .. code-block:: python
@@ -4049,6 +4275,7 @@ class RunnableGenerator(Runnable[Input, Output]):
4049
4275
  | StrOutputParser()
4050
4276
  )
4051
4277
 
4278
+
4052
4279
  def character_generator(input: Iterator[str]) -> Iterator[str]:
4053
4280
  for token in input:
4054
4281
  if "," in token or "." in token:
@@ -4059,7 +4286,10 @@ class RunnableGenerator(Runnable[Input, Output]):
4059
4286
 
4060
4287
  runnable = chant_chain | character_generator
4061
4288
  assert type(runnable.last) is RunnableGenerator
4062
- "".join(runnable.stream({"topic": "waste"})) # Reduce👏, Reuse👏, Recycle👏.
4289
+ "".join(
4290
+ runnable.stream({"topic": "waste"})
4291
+ ) # Reduce👏, Reuse👏, Recycle👏.
4292
+
4063
4293
 
4064
4294
  # Note that RunnableLambda can be used to delay streaming of one step in a
4065
4295
  # sequence until the previous step is finished:
@@ -4068,6 +4298,7 @@ class RunnableGenerator(Runnable[Input, Output]):
4068
4298
  for character in input[::-1]:
4069
4299
  yield character
4070
4300
 
4301
+
4071
4302
  runnable = chant_chain | RunnableLambda(reverse_generator)
4072
4303
  "".join(runnable.stream({"topic": "waste"})) # ".elcycer ,esuer ,ecudeR"
4073
4304
 
@@ -4085,15 +4316,16 @@ class RunnableGenerator(Runnable[Input, Output]):
4085
4316
  *,
4086
4317
  name: Optional[str] = None,
4087
4318
  ) -> None:
4088
- """Initialize a RunnableGenerator.
4319
+ """Initialize a ``RunnableGenerator``.
4089
4320
 
4090
4321
  Args:
4091
4322
  transform: The transform function.
4092
4323
  atransform: The async transform function. Defaults to None.
4093
- name: The name of the Runnable. Defaults to None.
4324
+ name: The name of the ``Runnable``. Defaults to None.
4094
4325
 
4095
4326
  Raises:
4096
4327
  TypeError: If the transform is not a generator function.
4328
+
4097
4329
  """
4098
4330
  if atransform is not None:
4099
4331
  self._atransform = atransform
@@ -4288,12 +4520,12 @@ class RunnableGenerator(Runnable[Input, Output]):
4288
4520
 
4289
4521
 
4290
4522
  class RunnableLambda(Runnable[Input, Output]):
4291
- """RunnableLambda converts a python callable into a Runnable.
4523
+ """``RunnableLambda`` converts a python callable into a ``Runnable``.
4292
4524
 
4293
- Wrapping a callable in a RunnableLambda makes the callable usable
4525
+ Wrapping a callable in a ``RunnableLambda`` makes the callable usable
4294
4526
  within either a sync or async context.
4295
4527
 
4296
- RunnableLambda can be composed as any other Runnable and provides
4528
+ ``RunnableLambda`` can be composed as any other ``Runnable`` and provides
4297
4529
  seamless integration with LangChain tracing.
4298
4530
 
4299
4531
  ``RunnableLambda`` is best suited for code that does not need to support
@@ -4311,26 +4543,29 @@ class RunnableLambda(Runnable[Input, Output]):
4311
4543
  # This is a RunnableLambda
4312
4544
  from langchain_core.runnables import RunnableLambda
4313
4545
 
4546
+
4314
4547
  def add_one(x: int) -> int:
4315
4548
  return x + 1
4316
4549
 
4550
+
4317
4551
  runnable = RunnableLambda(add_one)
4318
4552
 
4319
- runnable.invoke(1) # returns 2
4320
- runnable.batch([1, 2, 3]) # returns [2, 3, 4]
4553
+ runnable.invoke(1) # returns 2
4554
+ runnable.batch([1, 2, 3]) # returns [2, 3, 4]
4321
4555
 
4322
4556
  # Async is supported by default by delegating to the sync implementation
4323
- await runnable.ainvoke(1) # returns 2
4324
- await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
4557
+ await runnable.ainvoke(1) # returns 2
4558
+ await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
4325
4559
 
4326
4560
 
4327
4561
  # Alternatively, can provide both synd and sync implementations
4328
4562
  async def add_one_async(x: int) -> int:
4329
4563
  return x + 1
4330
4564
 
4565
+
4331
4566
  runnable = RunnableLambda(add_one, afunc=add_one_async)
4332
- runnable.invoke(1) # Uses add_one
4333
- await runnable.ainvoke(1) # Uses add_one_async
4567
+ runnable.invoke(1) # Uses add_one
4568
+ await runnable.ainvoke(1) # Uses add_one_async
4334
4569
 
4335
4570
  """
4336
4571
 
@@ -4370,7 +4605,7 @@ class RunnableLambda(Runnable[Input, Output]):
4370
4605
  ] = None,
4371
4606
  name: Optional[str] = None,
4372
4607
  ) -> None:
4373
- """Create a RunnableLambda from a callable, and async callable or both.
4608
+ """Create a ``RunnableLambda`` from a callable, and async callable or both.
4374
4609
 
4375
4610
  Accepts both sync and async variants to allow providing efficient
4376
4611
  implementations for sync and async execution.
@@ -4379,11 +4614,12 @@ class RunnableLambda(Runnable[Input, Output]):
4379
4614
  func: Either sync or async callable
4380
4615
  afunc: An async callable that takes an input and returns an output.
4381
4616
  Defaults to None.
4382
- name: The name of the Runnable. Defaults to None.
4617
+ name: The name of the ``Runnable``. Defaults to None.
4383
4618
 
4384
4619
  Raises:
4385
- TypeError: If the func is not a callable type.
4386
- TypeError: If both func and afunc are provided.
4620
+ TypeError: If the ``func`` is not a callable type.
4621
+ TypeError: If both ``func`` and ``afunc`` are provided.
4622
+
4387
4623
  """
4388
4624
  if afunc is not None:
4389
4625
  self.afunc = afunc
@@ -4422,7 +4658,7 @@ class RunnableLambda(Runnable[Input, Output]):
4422
4658
  @property
4423
4659
  @override
4424
4660
  def InputType(self) -> Any:
4425
- """The type of the input to this Runnable."""
4661
+ """The type of the input to this ``Runnable``."""
4426
4662
  func = getattr(self, "func", None) or self.afunc
4427
4663
  try:
4428
4664
  params = inspect.signature(func).parameters
@@ -4437,13 +4673,14 @@ class RunnableLambda(Runnable[Input, Output]):
4437
4673
  def get_input_schema(
4438
4674
  self, config: Optional[RunnableConfig] = None
4439
4675
  ) -> type[BaseModel]:
4440
- """The pydantic schema for the input to this Runnable.
4676
+ """The pydantic schema for the input to this ``Runnable``.
4441
4677
 
4442
4678
  Args:
4443
4679
  config: The config to use. Defaults to None.
4444
4680
 
4445
4681
  Returns:
4446
- The input schema for this Runnable.
4682
+ The input schema for this ``Runnable``.
4683
+
4447
4684
  """
4448
4685
  func = getattr(self, "func", None) or self.afunc
4449
4686
 
@@ -4481,10 +4718,11 @@ class RunnableLambda(Runnable[Input, Output]):
4481
4718
  @property
4482
4719
  @override
4483
4720
  def OutputType(self) -> Any:
4484
- """The type of the output of this Runnable as a type annotation.
4721
+ """The type of the output of this ``Runnable`` as a type annotation.
4485
4722
 
4486
4723
  Returns:
4487
- The type of the output of this Runnable.
4724
+ The type of the output of this ``Runnable``.
4725
+
4488
4726
  """
4489
4727
  func = getattr(self, "func", None) or self.afunc
4490
4728
  try:
@@ -4530,11 +4768,12 @@ class RunnableLambda(Runnable[Input, Output]):
4530
4768
 
4531
4769
  @functools.cached_property
4532
4770
  def deps(self) -> list[Runnable]:
4533
- """The dependencies of this Runnable.
4771
+ """The dependencies of this ``Runnable``.
4534
4772
 
4535
4773
  Returns:
4536
- The dependencies of this Runnable. If the function has nonlocal
4537
- variables that are Runnables, they are considered dependencies.
4774
+ The dependencies of this ``Runnable``. If the function has nonlocal
4775
+ variables that are ``Runnable``s, they are considered dependencies.
4776
+
4538
4777
  """
4539
4778
  if hasattr(self, "func"):
4540
4779
  objects = get_function_nonlocals(self.func)
@@ -4561,6 +4800,9 @@ class RunnableLambda(Runnable[Input, Output]):
4561
4800
  @override
4562
4801
  def get_graph(self, config: RunnableConfig | None = None) -> Graph:
4563
4802
  if deps := self.deps:
4803
+ # Import locally to prevent circular import
4804
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
4805
+
4564
4806
  graph = Graph()
4565
4807
  input_node = graph.add_node(self.get_input_schema(config))
4566
4808
  output_node = graph.add_node(self.get_output_schema(config))
@@ -4598,7 +4840,7 @@ class RunnableLambda(Runnable[Input, Output]):
4598
4840
  __hash__ = None # type: ignore[assignment]
4599
4841
 
4600
4842
  def __repr__(self) -> str:
4601
- """A string representation of this Runnable."""
4843
+ """Return a string representation of this ``Runnable``."""
4602
4844
  if self._repr is None:
4603
4845
  if hasattr(self, "func") and isinstance(self.func, itemgetter):
4604
4846
  self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})"
@@ -4764,18 +5006,19 @@ class RunnableLambda(Runnable[Input, Output]):
4764
5006
  config: Optional[RunnableConfig] = None,
4765
5007
  **kwargs: Optional[Any],
4766
5008
  ) -> Output:
4767
- """Invoke this Runnable synchronously.
5009
+ """Invoke this ``Runnable`` synchronously.
4768
5010
 
4769
5011
  Args:
4770
- input: The input to this Runnable.
5012
+ input: The input to this ``Runnable``.
4771
5013
  config: The config to use. Defaults to None.
4772
5014
  kwargs: Additional keyword arguments.
4773
5015
 
4774
5016
  Returns:
4775
- The output of this Runnable.
5017
+ The output of this ``Runnable``.
4776
5018
 
4777
5019
  Raises:
4778
- TypeError: If the Runnable is a coroutine function.
5020
+ TypeError: If the ``Runnable`` is a coroutine function.
5021
+
4779
5022
  """
4780
5023
  if hasattr(self, "func"):
4781
5024
  return self._call_with_config(
@@ -4794,15 +5037,16 @@ class RunnableLambda(Runnable[Input, Output]):
4794
5037
  config: Optional[RunnableConfig] = None,
4795
5038
  **kwargs: Optional[Any],
4796
5039
  ) -> Output:
4797
- """Invoke this Runnable asynchronously.
5040
+ """Invoke this ``Runnable`` asynchronously.
4798
5041
 
4799
5042
  Args:
4800
- input: The input to this Runnable.
5043
+ input: The input to this ``Runnable``.
4801
5044
  config: The config to use. Defaults to None.
4802
5045
  kwargs: Additional keyword arguments.
4803
5046
 
4804
5047
  Returns:
4805
- The output of this Runnable.
5048
+ The output of this ``Runnable``.
5049
+
4806
5050
  """
4807
5051
  return await self._acall_with_config(
4808
5052
  self._ainvoke,
@@ -5032,11 +5276,15 @@ class RunnableLambda(Runnable[Input, Output]):
5032
5276
 
5033
5277
 
5034
5278
  class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5035
- """Runnable that calls another Runnable for each element of the input sequence.
5279
+ """RunnableEachBase class.
5280
+
5281
+ ``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5036
5282
 
5037
- Use only if creating a new RunnableEach subclass with different __init__ args.
5283
+ Use only if creating a new ``RunnableEach`` subclass with different ``__init__``
5284
+ args.
5285
+
5286
+ See documentation for ``RunnableEach`` for more details.
5038
5287
 
5039
- See documentation for RunnableEach for more details.
5040
5288
  """
5041
5289
 
5042
5290
  bound: Runnable[Input, Output]
@@ -5105,11 +5353,17 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5105
5353
  @classmethod
5106
5354
  @override
5107
5355
  def is_lc_serializable(cls) -> bool:
5356
+ """Return True as this class is serializable."""
5108
5357
  return True
5109
5358
 
5110
5359
  @classmethod
5111
5360
  @override
5112
5361
  def get_lc_namespace(cls) -> list[str]:
5362
+ """Get the namespace of the langchain object.
5363
+
5364
+ Returns:
5365
+ ``["langchain", "schema", "runnable"]``
5366
+ """
5113
5367
  return ["langchain", "schema", "runnable"]
5114
5368
 
5115
5369
  def _invoke(
@@ -5155,20 +5409,25 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
5155
5409
  config: Optional[RunnableConfig] = None,
5156
5410
  **kwargs: Optional[Any],
5157
5411
  ) -> AsyncIterator[StreamEvent]:
5412
+ def _error_stream_event(message: str) -> StreamEvent:
5413
+ raise NotImplementedError(message)
5414
+
5158
5415
  for _ in range(1):
5159
- msg = "RunnableEach does not support astream_events yet."
5160
- raise NotImplementedError(msg)
5161
- yield
5416
+ yield _error_stream_event(
5417
+ "RunnableEach does not support astream_events yet."
5418
+ )
5162
5419
 
5163
5420
 
5164
5421
  class RunnableEach(RunnableEachBase[Input, Output]):
5165
- """Runnable that calls another Runnable for each element of the input sequence.
5422
+ """RunnableEach class.
5166
5423
 
5167
- It allows you to call multiple inputs with the bounded Runnable.
5424
+ ``Runnable`` that calls another ``Runnable`` for each element of the input sequence.
5168
5425
 
5169
- RunnableEach makes it easy to run multiple inputs for the Runnable.
5426
+ It allows you to call multiple inputs with the bounded ``Runnable``.
5427
+
5428
+ ``RunnableEach`` makes it easy to run multiple inputs for the ``Runnable``.
5170
5429
  In the below example, we associate and run three inputs
5171
- with a Runnable:
5430
+ with a ``Runnable``:
5172
5431
 
5173
5432
  .. code-block:: python
5174
5433
 
@@ -5220,22 +5479,23 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5220
5479
  Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]
5221
5480
  ] = None,
5222
5481
  ) -> RunnableEach[Input, Output]:
5223
- """Bind lifecycle listeners to a Runnable, returning a new Runnable.
5482
+ """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``.
5224
5483
 
5225
- The Run object contains information about the run, including its id,
5226
- type, input, output, error, start_time, end_time, and any tags or metadata
5227
- added to the run.
5484
+ The ``Run`` object contains information about the run, including its ``id``,
5485
+ ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
5486
+ any tags or metadata added to the run.
5228
5487
 
5229
5488
  Args:
5230
- on_start: Called before the Runnable starts running, with the Run object.
5231
- Defaults to None.
5232
- on_end: Called after the Runnable finishes running, with the Run object.
5233
- Defaults to None.
5234
- on_error: Called if the Runnable throws an error, with the Run object.
5235
- Defaults to None.
5489
+ on_start: Called before the ``Runnable`` starts running, with the ``Run``
5490
+ object. Defaults to None.
5491
+ on_end: Called after the ``Runnable`` finishes running, with the ``Run``
5492
+ object. Defaults to None.
5493
+ on_error: Called if the ``Runnable`` throws an error, with the ``Run``
5494
+ object. Defaults to None.
5236
5495
 
5237
5496
  Returns:
5238
- A new Runnable with the listeners bound.
5497
+ A new ``Runnable`` with the listeners bound.
5498
+
5239
5499
  """
5240
5500
  return RunnableEach(
5241
5501
  bound=self.bound.with_listeners(
@@ -5250,22 +5510,25 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5250
5510
  on_end: Optional[AsyncListener] = None,
5251
5511
  on_error: Optional[AsyncListener] = None,
5252
5512
  ) -> RunnableEach[Input, Output]:
5253
- """Bind async lifecycle listeners to a Runnable, returning a new Runnable.
5513
+ """Bind async lifecycle listeners to a ``Runnable``.
5254
5514
 
5255
- The Run object contains information about the run, including its id,
5256
- type, input, output, error, start_time, end_time, and any tags or metadata
5257
- added to the run.
5515
+ Returns a new ``Runnable``.
5516
+
5517
+ The ``Run`` object contains information about the run, including its ``id``,
5518
+ ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
5519
+ any tags or metadata added to the run.
5258
5520
 
5259
5521
  Args:
5260
- on_start: Called asynchronously before the Runnable starts running,
5261
- with the Run object. Defaults to None.
5262
- on_end: Called asynchronously after the Runnable finishes running,
5263
- with the Run object. Defaults to None.
5264
- on_error: Called asynchronously if the Runnable throws an error,
5265
- with the Run object. Defaults to None.
5522
+ on_start: Called asynchronously before the ``Runnable`` starts running,
5523
+ with the ``Run`` object. Defaults to None.
5524
+ on_end: Called asynchronously after the ``Runnable`` finishes running,
5525
+ with the ``Run`` object. Defaults to None.
5526
+ on_error: Called asynchronously if the ``Runnable`` throws an error,
5527
+ with the ``Run`` object. Defaults to None.
5266
5528
 
5267
5529
  Returns:
5268
- A new Runnable with the listeners bound.
5530
+ A new ``Runnable`` with the listeners bound.
5531
+
5269
5532
  """
5270
5533
  return RunnableEach(
5271
5534
  bound=self.bound.with_alisteners(
@@ -5274,44 +5537,47 @@ class RunnableEach(RunnableEachBase[Input, Output]):
5274
5537
  )
5275
5538
 
5276
5539
 
5277
- class RunnableBindingBase(RunnableSerializable[Input, Output]):
5278
- """Runnable that delegates calls to another Runnable with a set of kwargs.
5540
+ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[no-redef]
5541
+ """``Runnable`` that delegates calls to another ``Runnable`` with a set of kwargs.
5279
5542
 
5280
- Use only if creating a new RunnableBinding subclass with different __init__ args.
5543
+ Use only if creating a new ``RunnableBinding`` subclass with different ``__init__``
5544
+ args.
5545
+
5546
+ See documentation for ``RunnableBinding`` for more details.
5281
5547
 
5282
- See documentation for RunnableBinding for more details.
5283
5548
  """
5284
5549
 
5285
5550
  bound: Runnable[Input, Output]
5286
- """The underlying Runnable that this Runnable delegates to."""
5551
+ """The underlying ``Runnable`` that this ``Runnable`` delegates to."""
5287
5552
 
5288
5553
  kwargs: Mapping[str, Any] = Field(default_factory=dict)
5289
- """kwargs to pass to the underlying Runnable when running.
5554
+ """kwargs to pass to the underlying ``Runnable`` when running.
5290
5555
 
5291
- For example, when the Runnable binding is invoked the underlying
5292
- Runnable will be invoked with the same input but with these additional
5556
+ For example, when the ``Runnable`` binding is invoked the underlying
5557
+ ``Runnable`` will be invoked with the same input but with these additional
5293
5558
  kwargs.
5559
+
5294
5560
  """
5295
5561
 
5296
- config: RunnableConfig = Field(default_factory=RunnableConfig) # type: ignore[arg-type]
5297
- """The config to bind to the underlying Runnable."""
5562
+ config: RunnableConfig = Field(default_factory=RunnableConfig)
5563
+ """The config to bind to the underlying ``Runnable``."""
5298
5564
 
5299
5565
  config_factories: list[Callable[[RunnableConfig], RunnableConfig]] = Field(
5300
5566
  default_factory=list
5301
5567
  )
5302
- """The config factories to bind to the underlying Runnable."""
5568
+ """The config factories to bind to the underlying ``Runnable``."""
5303
5569
 
5304
5570
  # Union[Type[Input], BaseModel] + things like list[str]
5305
5571
  custom_input_type: Optional[Any] = None
5306
- """Override the input type of the underlying Runnable with a custom type.
5572
+ """Override the input type of the underlying ``Runnable`` with a custom type.
5307
5573
 
5308
- The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
5574
+ The type can be a pydantic model, or a type annotation (e.g., ``list[str]``).
5309
5575
  """
5310
5576
  # Union[Type[Output], BaseModel] + things like list[str]
5311
5577
  custom_output_type: Optional[Any] = None
5312
- """Override the output type of the underlying Runnable with a custom type.
5578
+ """Override the output type of the underlying ``Runnable`` with a custom type.
5313
5579
 
5314
- The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
5580
+ The type can be a pydantic model, or a type annotation (e.g., ``list[str]``).
5315
5581
  """
5316
5582
 
5317
5583
  model_config = ConfigDict(
@@ -5331,26 +5597,27 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
5331
5597
  custom_output_type: Optional[Union[type[Output], BaseModel]] = None,
5332
5598
  **other_kwargs: Any,
5333
5599
  ) -> None:
5334
- """Create a RunnableBinding from a Runnable and kwargs.
5600
+ """Create a ``RunnableBinding`` from a ``Runnable`` and kwargs.
5335
5601
 
5336
5602
  Args:
5337
- bound: The underlying Runnable that this Runnable delegates calls to.
5338
- kwargs: optional kwargs to pass to the underlying Runnable, when running
5339
- the underlying Runnable (e.g., via `invoke`, `batch`,
5340
- `transform`, or `stream` or async variants)
5341
- Defaults to None.
5342
- config: optional config to bind to the underlying Runnable.
5343
- Defaults to None.
5603
+ bound: The underlying ``Runnable`` that this ``Runnable`` delegates calls
5604
+ to.
5605
+ kwargs: optional kwargs to pass to the underlying ``Runnable``, when running
5606
+ the underlying ``Runnable`` (e.g., via ``invoke``, ``batch``,
5607
+ ``transform``, or ``stream`` or async variants)
5608
+ Defaults to None.
5609
+ config: optional config to bind to the underlying ``Runnable``.
5610
+ Defaults to None.
5344
5611
  config_factories: optional list of config factories to apply to the
5345
- config before binding to the underlying Runnable.
5346
- Defaults to None.
5612
+ config before binding to the underlying ``Runnable``.
5613
+ Defaults to None.
5347
5614
  custom_input_type: Specify to override the input type of the underlying
5348
- Runnable with a custom type. Defaults to None.
5615
+ ``Runnable`` with a custom type. Defaults to None.
5349
5616
  custom_output_type: Specify to override the output type of the underlying
5350
- Runnable with a custom type. Defaults to None.
5617
+ ``Runnable`` with a custom type. Defaults to None.
5351
5618
  **other_kwargs: Unpacked into the base class.
5352
5619
  """
5353
- super().__init__( # type: ignore[call-arg]
5620
+ super().__init__(
5354
5621
  bound=bound,
5355
5622
  kwargs=kwargs or {},
5356
5623
  config=config or {},
@@ -5416,6 +5683,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
5416
5683
  @classmethod
5417
5684
  @override
5418
5685
  def is_lc_serializable(cls) -> bool:
5686
+ """Return True as this class is serializable."""
5419
5687
  return True
5420
5688
 
5421
5689
  @classmethod
@@ -5423,7 +5691,8 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
5423
5691
  def get_lc_namespace(cls) -> list[str]:
5424
5692
  """Get the namespace of the langchain object.
5425
5693
 
5426
- Defaults to ["langchain", "schema", "runnable"].
5694
+ Returns:
5695
+ ``["langchain", "schema", "runnable"]``
5427
5696
  """
5428
5697
  return ["langchain", "schema", "runnable"]
5429
5698
 
@@ -5675,65 +5944,71 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
5675
5944
  yield item
5676
5945
 
5677
5946
 
5678
- class RunnableBinding(RunnableBindingBase[Input, Output]):
5679
- """Wrap a Runnable with additional functionality.
5947
+ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
5948
+ """Wrap a ``Runnable`` with additional functionality.
5680
5949
 
5681
- A RunnableBinding can be thought of as a "runnable decorator" that
5682
- preserves the essential features of Runnable; i.e., batching, streaming,
5950
+ A ``RunnableBinding`` can be thought of as a "runnable decorator" that
5951
+ preserves the essential features of ``Runnable``; i.e., batching, streaming,
5683
5952
  and async support, while adding additional functionality.
5684
5953
 
5685
- Any class that inherits from Runnable can be bound to a `RunnableBinding`.
5686
- Runnables expose a standard set of methods for creating `RunnableBindings`
5687
- or sub-classes of `RunnableBindings` (e.g., `RunnableRetry`,
5688
- `RunnableWithFallbacks`) that add additional functionality.
5954
+ Any class that inherits from ``Runnable`` can be bound to a ``RunnableBinding``.
5955
+ Runnables expose a standard set of methods for creating ``RunnableBindings``
5956
+ or sub-classes of ``RunnableBindings`` (e.g., ``RunnableRetry``,
5957
+ ``RunnableWithFallbacks``) that add additional functionality.
5689
5958
 
5690
5959
  These methods include:
5691
5960
 
5692
- - ``bind``: Bind kwargs to pass to the underlying Runnable when running it.
5693
- - ``with_config``: Bind config to pass to the underlying Runnable when running it.
5694
- - ``with_listeners``: Bind lifecycle listeners to the underlying Runnable.
5695
- - ``with_types``: Override the input and output types of the underlying Runnable.
5696
- - ``with_retry``: Bind a retry policy to the underlying Runnable.
5697
- - ``with_fallbacks``: Bind a fallback policy to the underlying Runnable.
5961
+ - ``bind``: Bind kwargs to pass to the underlying ``Runnable`` when running it.
5962
+ - ``with_config``: Bind config to pass to the underlying ``Runnable`` when running
5963
+ it.
5964
+ - ``with_listeners``: Bind lifecycle listeners to the underlying ``Runnable``.
5965
+ - ``with_types``: Override the input and output types of the underlying
5966
+ ``Runnable``.
5967
+ - ``with_retry``: Bind a retry policy to the underlying ``Runnable``.
5968
+ - ``with_fallbacks``: Bind a fallback policy to the underlying ``Runnable``.
5698
5969
 
5699
5970
  Example:
5700
- `bind`: Bind kwargs to pass to the underlying Runnable when running it.
5971
+ `bind`: Bind kwargs to pass to the underlying ``Runnable`` when running it.
5701
5972
 
5702
5973
  .. code-block:: python
5703
5974
 
5704
5975
  # Create a Runnable binding that invokes the ChatModel with the
5705
5976
  # additional kwarg `stop=['-']` when running it.
5706
5977
  from langchain_community.chat_models import ChatOpenAI
5978
+
5707
5979
  model = ChatOpenAI()
5708
- model.invoke('Say "Parrot-MAGIC"', stop=['-']) # Should return `Parrot`
5980
+ model.invoke('Say "Parrot-MAGIC"', stop=["-"]) # Should return `Parrot`
5709
5981
  # Using it the easy way via `bind` method which returns a new
5710
5982
  # RunnableBinding
5711
- runnable_binding = model.bind(stop=['-'])
5712
- runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5983
+ runnable_binding = model.bind(stop=["-"])
5984
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5713
5985
 
5714
- Can also be done by instantiating a RunnableBinding directly (not recommended):
5986
+ Can also be done by instantiating a ``RunnableBinding`` directly (not
5987
+ recommended):
5715
5988
 
5716
5989
  .. code-block:: python
5717
5990
 
5718
5991
  from langchain_core.runnables import RunnableBinding
5992
+
5719
5993
  runnable_binding = RunnableBinding(
5720
5994
  bound=model,
5721
- kwargs={'stop': ['-']} # <-- Note the additional kwargs
5995
+ kwargs={"stop": ["-"]}, # <-- Note the additional kwargs
5722
5996
  )
5723
- runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5997
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
5724
5998
 
5725
5999
  """
5726
6000
 
5727
6001
  @override
5728
6002
  def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
5729
- """Bind additional kwargs to a Runnable, returning a new Runnable.
6003
+ """Bind additional kwargs to a ``Runnable``, returning a new ``Runnable``.
5730
6004
 
5731
6005
  Args:
5732
- **kwargs: The kwargs to bind to the Runnable.
6006
+ **kwargs: The kwargs to bind to the ``Runnable``.
5733
6007
 
5734
6008
  Returns:
5735
- A new Runnable with the same type and config as the original,
6009
+ A new ``Runnable`` with the same type and config as the original,
5736
6010
  but with the additional kwargs bound.
6011
+
5737
6012
  """
5738
6013
  return self.__class__(
5739
6014
  bound=self.bound,
@@ -5774,24 +6049,23 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
5774
6049
  Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]
5775
6050
  ] = None,
5776
6051
  ) -> Runnable[Input, Output]:
5777
- """Bind lifecycle listeners to a Runnable, returning a new Runnable.
6052
+ """Bind lifecycle listeners to a ``Runnable``, returning a new ``Runnable``.
5778
6053
 
5779
- The Run object contains information about the run, including its id,
5780
- type, input, output, error, start_time, end_time, and any tags or metadata
5781
- added to the run.
6054
+ The ``Run`` object contains information about the run, including its ``id``,
6055
+ ``type``, ``input``, ``output``, ``error``, ``start_time``, ``end_time``, and
6056
+ any tags or metadata added to the run.
5782
6057
 
5783
6058
  Args:
5784
- on_start: Called before the Runnable starts running, with the Run object.
5785
- Defaults to None.
5786
- on_end: Called after the Runnable finishes running, with the Run object.
5787
- Defaults to None.
5788
- on_error: Called if the Runnable throws an error, with the Run object.
5789
- Defaults to None.
6059
+ on_start: Called before the ``Runnable`` starts running, with the ``Run``
6060
+ object. Defaults to None.
6061
+ on_end: Called after the ``Runnable`` finishes running, with the ``Run``
6062
+ object. Defaults to None.
6063
+ on_error: Called if the ``Runnable`` throws an error, with the ``Run``
6064
+ object. Defaults to None.
5790
6065
 
5791
6066
  Returns:
5792
- A new Runnable with the listeners bound.
6067
+ A new ``Runnable`` with the listeners bound.
5793
6068
  """
5794
- from langchain_core.tracers.root_listeners import RootListenersTracer
5795
6069
 
5796
6070
  def listener_config_factory(config: RunnableConfig) -> RunnableConfig:
5797
6071
  return {
@@ -5917,16 +6191,16 @@ RunnableLike = Union[
5917
6191
 
5918
6192
 
5919
6193
  def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]:
5920
- """Coerce a Runnable-like object into a Runnable.
6194
+ """Coerce a ``Runnable``-like object into a ``Runnable``.
5921
6195
 
5922
6196
  Args:
5923
- thing: A Runnable-like object.
6197
+ thing: A ``Runnable``-like object.
5924
6198
 
5925
6199
  Returns:
5926
- A Runnable.
6200
+ A ``Runnable``.
5927
6201
 
5928
6202
  Raises:
5929
- TypeError: If the object is not Runnable-like.
6203
+ TypeError: If the object is not ``Runnable``-like.
5930
6204
  """
5931
6205
  if isinstance(thing, Runnable):
5932
6206
  return thing
@@ -5975,16 +6249,16 @@ def chain(
5975
6249
  Callable[[Input], AsyncIterator[Output]],
5976
6250
  ],
5977
6251
  ) -> Runnable[Input, Output]:
5978
- """Decorate a function to make it a Runnable.
6252
+ """Decorate a function to make it a ``Runnable``.
5979
6253
 
5980
- Sets the name of the Runnable to the name of the function.
6254
+ Sets the name of the ``Runnable`` to the name of the function.
5981
6255
  Any runnables called by the function will be traced as dependencies.
5982
6256
 
5983
6257
  Args:
5984
- func: A callable.
6258
+ func: A ``Callable``.
5985
6259
 
5986
6260
  Returns:
5987
- A Runnable.
6261
+ A ``Runnable``.
5988
6262
 
5989
6263
  Example:
5990
6264
 
@@ -5994,6 +6268,7 @@ def chain(
5994
6268
  from langchain_core.prompts import PromptTemplate
5995
6269
  from langchain_openai import OpenAI
5996
6270
 
6271
+
5997
6272
  @chain
5998
6273
  def my_func(fields):
5999
6274
  prompt = PromptTemplate("Hello, {name}!")