langchain-core 0.4.0.dev0__py3-none-any.whl → 1.0.0__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 (172) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +45 -70
  4. langchain_core/_api/deprecation.py +80 -80
  5. langchain_core/_api/path.py +22 -8
  6. langchain_core/_import_utils.py +10 -4
  7. langchain_core/agents.py +25 -21
  8. langchain_core/caches.py +53 -63
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +341 -348
  11. langchain_core/callbacks/file.py +55 -44
  12. langchain_core/callbacks/manager.py +546 -683
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +35 -36
  15. langchain_core/callbacks/usage.py +65 -70
  16. langchain_core/chat_history.py +48 -55
  17. langchain_core/document_loaders/base.py +46 -21
  18. langchain_core/document_loaders/langsmith.py +39 -36
  19. langchain_core/documents/__init__.py +0 -1
  20. langchain_core/documents/base.py +96 -74
  21. langchain_core/documents/compressor.py +12 -9
  22. langchain_core/documents/transformers.py +29 -28
  23. langchain_core/embeddings/fake.py +56 -57
  24. langchain_core/env.py +2 -3
  25. langchain_core/example_selectors/base.py +12 -0
  26. langchain_core/example_selectors/length_based.py +1 -1
  27. langchain_core/example_selectors/semantic_similarity.py +21 -25
  28. langchain_core/exceptions.py +15 -9
  29. langchain_core/globals.py +4 -163
  30. langchain_core/indexing/api.py +132 -125
  31. langchain_core/indexing/base.py +64 -67
  32. langchain_core/indexing/in_memory.py +26 -6
  33. langchain_core/language_models/__init__.py +15 -27
  34. langchain_core/language_models/_utils.py +267 -117
  35. langchain_core/language_models/base.py +92 -177
  36. langchain_core/language_models/chat_models.py +547 -407
  37. langchain_core/language_models/fake.py +11 -11
  38. langchain_core/language_models/fake_chat_models.py +72 -118
  39. langchain_core/language_models/llms.py +168 -242
  40. langchain_core/load/dump.py +8 -11
  41. langchain_core/load/load.py +32 -28
  42. langchain_core/load/mapping.py +2 -4
  43. langchain_core/load/serializable.py +50 -56
  44. langchain_core/messages/__init__.py +36 -51
  45. langchain_core/messages/ai.py +377 -150
  46. langchain_core/messages/base.py +239 -47
  47. langchain_core/messages/block_translators/__init__.py +111 -0
  48. langchain_core/messages/block_translators/anthropic.py +470 -0
  49. langchain_core/messages/block_translators/bedrock.py +94 -0
  50. langchain_core/messages/block_translators/bedrock_converse.py +297 -0
  51. langchain_core/messages/block_translators/google_genai.py +530 -0
  52. langchain_core/messages/block_translators/google_vertexai.py +21 -0
  53. langchain_core/messages/block_translators/groq.py +143 -0
  54. langchain_core/messages/block_translators/langchain_v0.py +301 -0
  55. langchain_core/messages/block_translators/openai.py +1010 -0
  56. langchain_core/messages/chat.py +2 -3
  57. langchain_core/messages/content.py +1423 -0
  58. langchain_core/messages/function.py +7 -7
  59. langchain_core/messages/human.py +44 -38
  60. langchain_core/messages/modifier.py +3 -2
  61. langchain_core/messages/system.py +40 -27
  62. langchain_core/messages/tool.py +160 -58
  63. langchain_core/messages/utils.py +527 -638
  64. langchain_core/output_parsers/__init__.py +1 -14
  65. langchain_core/output_parsers/base.py +68 -104
  66. langchain_core/output_parsers/json.py +13 -17
  67. langchain_core/output_parsers/list.py +11 -33
  68. langchain_core/output_parsers/openai_functions.py +56 -74
  69. langchain_core/output_parsers/openai_tools.py +68 -109
  70. langchain_core/output_parsers/pydantic.py +15 -13
  71. langchain_core/output_parsers/string.py +6 -2
  72. langchain_core/output_parsers/transform.py +17 -60
  73. langchain_core/output_parsers/xml.py +34 -44
  74. langchain_core/outputs/__init__.py +1 -1
  75. langchain_core/outputs/chat_generation.py +26 -11
  76. langchain_core/outputs/chat_result.py +1 -3
  77. langchain_core/outputs/generation.py +17 -6
  78. langchain_core/outputs/llm_result.py +15 -8
  79. langchain_core/prompt_values.py +29 -123
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +48 -63
  82. langchain_core/prompts/chat.py +259 -288
  83. langchain_core/prompts/dict.py +19 -11
  84. langchain_core/prompts/few_shot.py +84 -90
  85. langchain_core/prompts/few_shot_with_templates.py +14 -12
  86. langchain_core/prompts/image.py +19 -14
  87. langchain_core/prompts/loading.py +6 -8
  88. langchain_core/prompts/message.py +7 -8
  89. langchain_core/prompts/prompt.py +42 -43
  90. langchain_core/prompts/string.py +37 -16
  91. langchain_core/prompts/structured.py +43 -46
  92. langchain_core/rate_limiters.py +51 -60
  93. langchain_core/retrievers.py +52 -192
  94. langchain_core/runnables/base.py +1727 -1683
  95. langchain_core/runnables/branch.py +52 -73
  96. langchain_core/runnables/config.py +89 -103
  97. langchain_core/runnables/configurable.py +128 -130
  98. langchain_core/runnables/fallbacks.py +93 -82
  99. langchain_core/runnables/graph.py +127 -127
  100. langchain_core/runnables/graph_ascii.py +63 -41
  101. langchain_core/runnables/graph_mermaid.py +87 -70
  102. langchain_core/runnables/graph_png.py +31 -36
  103. langchain_core/runnables/history.py +145 -161
  104. langchain_core/runnables/passthrough.py +141 -144
  105. langchain_core/runnables/retry.py +84 -68
  106. langchain_core/runnables/router.py +33 -37
  107. langchain_core/runnables/schema.py +79 -72
  108. langchain_core/runnables/utils.py +95 -139
  109. langchain_core/stores.py +85 -131
  110. langchain_core/structured_query.py +11 -15
  111. langchain_core/sys_info.py +31 -32
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +221 -247
  114. langchain_core/tools/convert.py +144 -161
  115. langchain_core/tools/render.py +10 -10
  116. langchain_core/tools/retriever.py +12 -19
  117. langchain_core/tools/simple.py +52 -29
  118. langchain_core/tools/structured.py +56 -60
  119. langchain_core/tracers/__init__.py +1 -9
  120. langchain_core/tracers/_streaming.py +6 -7
  121. langchain_core/tracers/base.py +103 -112
  122. langchain_core/tracers/context.py +29 -48
  123. langchain_core/tracers/core.py +142 -105
  124. langchain_core/tracers/evaluation.py +30 -34
  125. langchain_core/tracers/event_stream.py +162 -117
  126. langchain_core/tracers/langchain.py +34 -36
  127. langchain_core/tracers/log_stream.py +87 -49
  128. langchain_core/tracers/memory_stream.py +3 -3
  129. langchain_core/tracers/root_listeners.py +18 -34
  130. langchain_core/tracers/run_collector.py +8 -20
  131. langchain_core/tracers/schemas.py +0 -125
  132. langchain_core/tracers/stdout.py +3 -3
  133. langchain_core/utils/__init__.py +1 -4
  134. langchain_core/utils/_merge.py +47 -9
  135. langchain_core/utils/aiter.py +70 -66
  136. langchain_core/utils/env.py +12 -9
  137. langchain_core/utils/function_calling.py +139 -206
  138. langchain_core/utils/html.py +7 -8
  139. langchain_core/utils/input.py +6 -6
  140. langchain_core/utils/interactive_env.py +6 -2
  141. langchain_core/utils/iter.py +48 -45
  142. langchain_core/utils/json.py +14 -4
  143. langchain_core/utils/json_schema.py +159 -43
  144. langchain_core/utils/mustache.py +32 -25
  145. langchain_core/utils/pydantic.py +67 -40
  146. langchain_core/utils/strings.py +5 -5
  147. langchain_core/utils/usage.py +1 -1
  148. langchain_core/utils/utils.py +104 -62
  149. langchain_core/vectorstores/base.py +131 -179
  150. langchain_core/vectorstores/in_memory.py +113 -182
  151. langchain_core/vectorstores/utils.py +23 -17
  152. langchain_core/version.py +1 -1
  153. langchain_core-1.0.0.dist-info/METADATA +68 -0
  154. langchain_core-1.0.0.dist-info/RECORD +172 -0
  155. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0.dist-info}/WHEEL +1 -1
  156. langchain_core/beta/__init__.py +0 -1
  157. langchain_core/beta/runnables/__init__.py +0 -1
  158. langchain_core/beta/runnables/context.py +0 -448
  159. langchain_core/memory.py +0 -116
  160. langchain_core/messages/content_blocks.py +0 -1435
  161. langchain_core/prompts/pipeline.py +0 -133
  162. langchain_core/pydantic_v1/__init__.py +0 -30
  163. langchain_core/pydantic_v1/dataclasses.py +0 -23
  164. langchain_core/pydantic_v1/main.py +0 -23
  165. langchain_core/tracers/langchain_v1.py +0 -23
  166. langchain_core/utils/loading.py +0 -31
  167. langchain_core/v1/__init__.py +0 -1
  168. langchain_core/v1/chat_models.py +0 -1047
  169. langchain_core/v1/messages.py +0 -755
  170. langchain_core-0.4.0.dev0.dist-info/METADATA +0 -108
  171. langchain_core-0.4.0.dev0.dist-info/RECORD +0 -177
  172. langchain_core-0.4.0.dev0.dist-info/entry_points.txt +0 -4
@@ -1,11 +1,15 @@
1
1
  """Runnable that selects which branch to run based on a condition."""
2
2
 
3
- from collections.abc import AsyncIterator, Awaitable, Iterator, Mapping, Sequence
3
+ from collections.abc import (
4
+ AsyncIterator,
5
+ Awaitable,
6
+ Callable,
7
+ Iterator,
8
+ Mapping,
9
+ Sequence,
10
+ )
4
11
  from typing import (
5
12
  Any,
6
- Callable,
7
- Optional,
8
- Union,
9
13
  cast,
10
14
  )
11
15
 
@@ -44,44 +48,36 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
44
48
 
45
49
  If no condition evaluates to True, the default branch is run on the input.
46
50
 
47
- Parameters:
48
- branches: A list of (condition, Runnable) pairs.
49
- default: A Runnable to run if no condition is met.
50
-
51
51
  Examples:
52
+ ```python
53
+ from langchain_core.runnables import RunnableBranch
54
+
55
+ branch = RunnableBranch(
56
+ (lambda x: isinstance(x, str), lambda x: x.upper()),
57
+ (lambda x: isinstance(x, int), lambda x: x + 1),
58
+ (lambda x: isinstance(x, float), lambda x: x * 2),
59
+ lambda x: "goodbye",
60
+ )
52
61
 
53
- .. code-block:: python
54
-
55
- from langchain_core.runnables import RunnableBranch
56
-
57
- branch = RunnableBranch(
58
- (lambda x: isinstance(x, str), lambda x: x.upper()),
59
- (lambda x: isinstance(x, int), lambda x: x + 1),
60
- (lambda x: isinstance(x, float), lambda x: x * 2),
61
- lambda x: "goodbye",
62
- )
63
-
64
- branch.invoke("hello") # "HELLO"
65
- branch.invoke(None) # "goodbye"
66
-
62
+ branch.invoke("hello") # "HELLO"
63
+ branch.invoke(None) # "goodbye"
64
+ ```
67
65
  """
68
66
 
69
67
  branches: Sequence[tuple[Runnable[Input, bool], Runnable[Input, Output]]]
68
+ """A list of (condition, Runnable) pairs."""
70
69
  default: Runnable[Input, Output]
70
+ """A Runnable to run if no condition is met."""
71
71
 
72
72
  def __init__(
73
73
  self,
74
- *branches: Union[
75
- tuple[
76
- Union[
77
- Runnable[Input, bool],
78
- Callable[[Input], bool],
79
- Callable[[Input], Awaitable[bool]],
80
- ],
81
- RunnableLike,
82
- ],
83
- RunnableLike, # To accommodate the default branch
84
- ],
74
+ *branches: tuple[
75
+ Runnable[Input, bool]
76
+ | Callable[[Input], bool]
77
+ | Callable[[Input], Awaitable[bool]],
78
+ RunnableLike,
79
+ ]
80
+ | RunnableLike,
85
81
  ) -> None:
86
82
  """A Runnable that runs one of two branches based on a condition.
87
83
 
@@ -136,7 +132,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
136
132
  super().__init__(
137
133
  branches=branches_,
138
134
  default=default_,
139
- ) # type: ignore[call-arg]
135
+ )
140
136
 
141
137
  model_config = ConfigDict(
142
138
  arbitrary_types_allowed=True,
@@ -144,18 +140,21 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
144
140
 
145
141
  @classmethod
146
142
  def is_lc_serializable(cls) -> bool:
147
- """RunnableBranch is serializable if all its branches are serializable."""
143
+ """Return True as this class is serializable."""
148
144
  return True
149
145
 
150
146
  @classmethod
151
147
  @override
152
148
  def get_lc_namespace(cls) -> list[str]:
149
+ """Get the namespace of the LangChain object.
150
+
151
+ Returns:
152
+ `["langchain", "schema", "runnable"]`
153
+ """
153
154
  return ["langchain", "schema", "runnable"]
154
155
 
155
156
  @override
156
- def get_input_schema(
157
- self, config: Optional[RunnableConfig] = None
158
- ) -> type[BaseModel]:
157
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
159
158
  runnables = (
160
159
  [self.default]
161
160
  + [r for _, r in self.branches]
@@ -174,12 +173,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
174
173
  @property
175
174
  @override
176
175
  def config_specs(self) -> list[ConfigurableFieldSpec]:
177
- from langchain_core.beta.runnables.context import (
178
- CONTEXT_CONFIG_PREFIX,
179
- CONTEXT_CONFIG_SUFFIX_SET,
180
- )
181
-
182
- specs = get_unique_config_specs(
176
+ return get_unique_config_specs(
183
177
  spec
184
178
  for step in (
185
179
  [self.default]
@@ -188,25 +182,17 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
188
182
  )
189
183
  for spec in step.config_specs
190
184
  )
191
- if any(
192
- s.id.startswith(CONTEXT_CONFIG_PREFIX)
193
- and s.id.endswith(CONTEXT_CONFIG_SUFFIX_SET)
194
- for s in specs
195
- ):
196
- msg = "RunnableBranch cannot contain context setters."
197
- raise ValueError(msg)
198
- return specs
199
185
 
200
186
  @override
201
187
  def invoke(
202
- self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
188
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
203
189
  ) -> Output:
204
190
  """First evaluates the condition, then delegate to true or false branch.
205
191
 
206
192
  Args:
207
193
  input: The input to the Runnable.
208
- config: The configuration for the Runnable. Defaults to None.
209
- kwargs: Additional keyword arguments to pass to the Runnable.
194
+ config: The configuration for the Runnable.
195
+ **kwargs: Additional keyword arguments to pass to the Runnable.
210
196
 
211
197
  Returns:
212
198
  The output of the branch that was run.
@@ -258,9 +244,8 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
258
244
 
259
245
  @override
260
246
  async def ainvoke(
261
- self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
247
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
262
248
  ) -> Output:
263
- """Async version of invoke."""
264
249
  config = ensure_config(config)
265
250
  callback_manager = get_async_callback_manager_for_config(config)
266
251
  run_manager = await callback_manager.on_chain_start(
@@ -309,21 +294,18 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
309
294
  def stream(
310
295
  self,
311
296
  input: Input,
312
- config: Optional[RunnableConfig] = None,
313
- **kwargs: Optional[Any],
297
+ config: RunnableConfig | None = None,
298
+ **kwargs: Any | None,
314
299
  ) -> Iterator[Output]:
315
300
  """First evaluates the condition, then delegate to true or false branch.
316
301
 
317
302
  Args:
318
303
  input: The input to the Runnable.
319
- config: The configuration for the Runnable. Defaults to None.
320
- kwargs: Additional keyword arguments to pass to the Runnable.
304
+ config: The configuration for the Runnable.
305
+ **kwargs: Additional keyword arguments to pass to the Runnable.
321
306
 
322
307
  Yields:
323
308
  The output of the branch that was run.
324
-
325
- Raises:
326
- BaseException: If an error occurs during the execution of the Runnable.
327
309
  """
328
310
  config = ensure_config(config)
329
311
  callback_manager = get_callback_manager_for_config(config)
@@ -333,7 +315,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
333
315
  name=config.get("run_name") or self.get_name(),
334
316
  run_id=config.pop("run_id", None),
335
317
  )
336
- final_output: Optional[Output] = None
318
+ final_output: Output | None = None
337
319
  final_output_supported = True
338
320
 
339
321
  try:
@@ -396,21 +378,18 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
396
378
  async def astream(
397
379
  self,
398
380
  input: Input,
399
- config: Optional[RunnableConfig] = None,
400
- **kwargs: Optional[Any],
381
+ config: RunnableConfig | None = None,
382
+ **kwargs: Any | None,
401
383
  ) -> AsyncIterator[Output]:
402
384
  """First evaluates the condition, then delegate to true or false branch.
403
385
 
404
386
  Args:
405
387
  input: The input to the Runnable.
406
- config: The configuration for the Runnable. Defaults to None.
407
- kwargs: Additional keyword arguments to pass to the Runnable.
388
+ config: The configuration for the Runnable.
389
+ **kwargs: Additional keyword arguments to pass to the Runnable.
408
390
 
409
391
  Yields:
410
392
  The output of the branch that was run.
411
-
412
- Raises:
413
- BaseException: If an error occurs during the execution of the Runnable.
414
393
  """
415
394
  config = ensure_config(config)
416
395
  callback_manager = get_async_callback_manager_for_config(config)
@@ -420,7 +399,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
420
399
  name=config.get("run_name") or self.get_name(),
421
400
  run_id=config.pop("run_id", None),
422
401
  )
423
- final_output: Optional[Output] = None
402
+ final_output: Output | None = None
424
403
  final_output_supported = True
425
404
 
426
405
  try:
@@ -5,34 +5,41 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import uuid
7
7
  import warnings
8
- from collections.abc import Awaitable, Generator, Iterable, Iterator, Sequence
8
+ from collections.abc import Awaitable, Callable, Generator, Iterable, Iterator, Sequence
9
9
  from concurrent.futures import Executor, Future, ThreadPoolExecutor
10
10
  from contextlib import contextmanager
11
11
  from contextvars import Context, ContextVar, Token, copy_context
12
12
  from functools import partial
13
- from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, cast
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ ParamSpec,
17
+ TypeVar,
18
+ cast,
19
+ )
14
20
 
15
- from typing_extensions import ParamSpec, TypedDict
21
+ from langsmith.run_helpers import _set_tracing_context, get_tracing_context
22
+ from typing_extensions import TypedDict
16
23
 
24
+ from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
17
25
  from langchain_core.runnables.utils import (
18
26
  Input,
19
27
  Output,
20
28
  accepts_config,
21
29
  accepts_run_manager,
22
30
  )
31
+ from langchain_core.tracers.langchain import LangChainTracer
23
32
 
24
33
  if TYPE_CHECKING:
25
34
  from langchain_core.callbacks.base import BaseCallbackManager, Callbacks
26
35
  from langchain_core.callbacks.manager import (
27
- AsyncCallbackManager,
28
36
  AsyncCallbackManagerForChainRun,
29
- CallbackManager,
30
37
  CallbackManagerForChainRun,
31
38
  )
32
39
  else:
33
40
  # Pydantic validates through typed dicts, but
34
41
  # the callbacks need forward refs updated
35
- Callbacks = Optional[Union[list, Any]]
42
+ Callbacks = list | Any | None
36
43
 
37
44
 
38
45
  class EmptyDict(TypedDict, total=False):
@@ -65,29 +72,29 @@ class RunnableConfig(TypedDict, total=False):
65
72
  Name for the tracer run for this call. Defaults to the name of the class.
66
73
  """
67
74
 
68
- max_concurrency: Optional[int]
75
+ max_concurrency: int | None
69
76
  """
70
77
  Maximum number of parallel calls to make. If not provided, defaults to
71
- ThreadPoolExecutor's default.
78
+ `ThreadPoolExecutor`'s default.
72
79
  """
73
80
 
74
81
  recursion_limit: int
75
82
  """
76
- Maximum number of times a call can recurse. If not provided, defaults to 25.
83
+ Maximum number of times a call can recurse. If not provided, defaults to `25`.
77
84
  """
78
85
 
79
86
  configurable: dict[str, Any]
80
87
  """
81
- Runtime values for attributes previously made configurable on this Runnable,
82
- or sub-Runnables, through .configurable_fields() or .configurable_alternatives().
83
- Check .output_schema() for a description of the attributes that have been made
88
+ Runtime values for attributes previously made configurable on this `Runnable`,
89
+ or sub-Runnables, through `configurable_fields` or `configurable_alternatives`.
90
+ Check `output_schema` for a description of the attributes that have been made
84
91
  configurable.
85
92
  """
86
93
 
87
- run_id: Optional[uuid.UUID]
94
+ run_id: uuid.UUID | None
88
95
  """
89
96
  Unique identifier for the tracer run for this call. If not provided, a new UUID
90
- will be generated.
97
+ will be generated.
91
98
  """
92
99
 
93
100
 
@@ -120,14 +127,15 @@ var_child_runnable_config: ContextVar[RunnableConfig | None] = ContextVar(
120
127
  # This is imported and used in langgraph, so don't break.
121
128
  def _set_config_context(
122
129
  config: RunnableConfig,
123
- ) -> tuple[Token[Optional[RunnableConfig]], Optional[dict[str, Any]]]:
130
+ ) -> tuple[Token[RunnableConfig | None], dict[str, Any] | None]:
124
131
  """Set the child Runnable config + tracing context.
125
132
 
126
133
  Args:
127
- config (RunnableConfig): The config to set.
128
- """
129
- from langchain_core.tracers.langchain import LangChainTracer
134
+ config: The config to set.
130
135
 
136
+ Returns:
137
+ The token to reset the config and the previous tracing context.
138
+ """
131
139
  config_token = var_child_runnable_config.set(config)
132
140
  current_context = None
133
141
  if (
@@ -147,8 +155,6 @@ def _set_config_context(
147
155
  )
148
156
  and (run := tracer.run_map.get(str(parent_run_id)))
149
157
  ):
150
- from langsmith.run_helpers import _set_tracing_context, get_tracing_context
151
-
152
158
  current_context = get_tracing_context()
153
159
  _set_tracing_context({"parent": run})
154
160
  return config_token, current_context
@@ -159,10 +165,11 @@ def set_config_context(config: RunnableConfig) -> Generator[Context, None, None]
159
165
  """Set the child Runnable config + tracing context.
160
166
 
161
167
  Args:
162
- config (RunnableConfig): The config to set.
163
- """
164
- from langsmith.run_helpers import _set_tracing_context
168
+ config: The config to set.
165
169
 
170
+ Yields:
171
+ The config context.
172
+ """
166
173
  ctx = copy_context()
167
174
  config_token, _ = ctx.run(_set_config_context, config)
168
175
  try:
@@ -182,15 +189,14 @@ def set_config_context(config: RunnableConfig) -> Generator[Context, None, None]
182
189
  )
183
190
 
184
191
 
185
- def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:
192
+ def ensure_config(config: RunnableConfig | None = None) -> RunnableConfig:
186
193
  """Ensure that a config is a dict with all keys present.
187
194
 
188
195
  Args:
189
- config (Optional[RunnableConfig], optional): The config to ensure.
190
- Defaults to None.
196
+ config: The config to ensure.
191
197
 
192
198
  Returns:
193
- RunnableConfig: The ensured config.
199
+ The ensured config.
194
200
  """
195
201
  empty = RunnableConfig(
196
202
  tags=[],
@@ -237,19 +243,18 @@ def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:
237
243
 
238
244
 
239
245
  def get_config_list(
240
- config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]], length: int
246
+ config: RunnableConfig | Sequence[RunnableConfig] | None, length: int
241
247
  ) -> list[RunnableConfig]:
242
248
  """Get a list of configs from a single config or a list of configs.
243
249
 
244
250
  It is useful for subclasses overriding batch() or abatch().
245
251
 
246
252
  Args:
247
- config (Optional[Union[RunnableConfig, list[RunnableConfig]]]):
248
- The config or list of configs.
249
- length (int): The length of the list.
253
+ config: The config or list of configs.
254
+ length: The length of the list.
250
255
 
251
256
  Returns:
252
- list[RunnableConfig]: The list of configs.
257
+ The list of configs.
253
258
 
254
259
  Raises:
255
260
  ValueError: If the length of the list is not equal to the length of the inputs.
@@ -284,30 +289,26 @@ def get_config_list(
284
289
 
285
290
 
286
291
  def patch_config(
287
- config: Optional[RunnableConfig],
292
+ config: RunnableConfig | None,
288
293
  *,
289
- callbacks: Optional[BaseCallbackManager] = None,
290
- recursion_limit: Optional[int] = None,
291
- max_concurrency: Optional[int] = None,
292
- run_name: Optional[str] = None,
293
- configurable: Optional[dict[str, Any]] = None,
294
+ callbacks: BaseCallbackManager | None = None,
295
+ recursion_limit: int | None = None,
296
+ max_concurrency: int | None = None,
297
+ run_name: str | None = None,
298
+ configurable: dict[str, Any] | None = None,
294
299
  ) -> RunnableConfig:
295
300
  """Patch a config with new values.
296
301
 
297
302
  Args:
298
- config (Optional[RunnableConfig]): The config to patch.
299
- callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.
300
- Defaults to None.
301
- recursion_limit (Optional[int], optional): The recursion limit to set.
302
- Defaults to None.
303
- max_concurrency (Optional[int], optional): The max concurrency to set.
304
- Defaults to None.
305
- run_name (Optional[str], optional): The run name to set. Defaults to None.
306
- configurable (Optional[dict[str, Any]], optional): The configurable to set.
307
- Defaults to None.
303
+ config: The config to patch.
304
+ callbacks: The callbacks to set.
305
+ recursion_limit: The recursion limit to set.
306
+ max_concurrency: The max concurrency to set.
307
+ run_name: The run name to set.
308
+ configurable: The configurable to set.
308
309
 
309
310
  Returns:
310
- RunnableConfig: The patched config.
311
+ The patched config.
311
312
  """
312
313
  config = ensure_config(config)
313
314
  if callbacks is not None:
@@ -329,14 +330,14 @@ def patch_config(
329
330
  return config
330
331
 
331
332
 
332
- def merge_configs(*configs: Optional[RunnableConfig]) -> RunnableConfig:
333
+ def merge_configs(*configs: RunnableConfig | None) -> RunnableConfig:
333
334
  """Merge multiple configs into one.
334
335
 
335
336
  Args:
336
- *configs (Optional[RunnableConfig]): The configs to merge.
337
+ *configs: The configs to merge.
337
338
 
338
339
  Returns:
339
- RunnableConfig: The merged config.
340
+ The merged config.
340
341
  """
341
342
  base: RunnableConfig = {}
342
343
  # Even though the keys aren't literals, this is correct
@@ -396,15 +397,13 @@ def merge_configs(*configs: Optional[RunnableConfig]) -> RunnableConfig:
396
397
 
397
398
 
398
399
  def call_func_with_variable_args(
399
- func: Union[
400
- Callable[[Input], Output],
401
- Callable[[Input, RunnableConfig], Output],
402
- Callable[[Input, CallbackManagerForChainRun], Output],
403
- Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
404
- ],
400
+ func: Callable[[Input], Output]
401
+ | Callable[[Input, RunnableConfig], Output]
402
+ | Callable[[Input, CallbackManagerForChainRun], Output]
403
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
405
404
  input: Input,
406
405
  config: RunnableConfig,
407
- run_manager: Optional[CallbackManagerForChainRun] = None,
406
+ run_manager: CallbackManagerForChainRun | None = None,
408
407
  **kwargs: Any,
409
408
  ) -> Output:
410
409
  """Call function that may optionally accept a run_manager and/or config.
@@ -413,7 +412,7 @@ def call_func_with_variable_args(
413
412
  func: The function to call.
414
413
  input: The input to the function.
415
414
  config: The config to pass to the function.
416
- run_manager: The run manager to pass to the function. Defaults to None.
415
+ run_manager: The run manager to pass to the function.
417
416
  **kwargs: The keyword arguments to pass to the function.
418
417
 
419
418
  Returns:
@@ -430,18 +429,15 @@ def call_func_with_variable_args(
430
429
 
431
430
 
432
431
  def acall_func_with_variable_args(
433
- func: Union[
434
- Callable[[Input], Awaitable[Output]],
435
- Callable[[Input, RunnableConfig], Awaitable[Output]],
436
- Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],
437
- Callable[
438
- [Input, AsyncCallbackManagerForChainRun, RunnableConfig],
439
- Awaitable[Output],
440
- ],
432
+ func: Callable[[Input], Awaitable[Output]]
433
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
434
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
435
+ | Callable[
436
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
441
437
  ],
442
438
  input: Input,
443
439
  config: RunnableConfig,
444
- run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
440
+ run_manager: AsyncCallbackManagerForChainRun | None = None,
445
441
  **kwargs: Any,
446
442
  ) -> Awaitable[Output]:
447
443
  """Async call function that may optionally accept a run_manager and/or config.
@@ -450,7 +446,7 @@ def acall_func_with_variable_args(
450
446
  func: The function to call.
451
447
  input: The input to the function.
452
448
  config: The config to pass to the function.
453
- run_manager: The run manager to pass to the function. Defaults to None.
449
+ run_manager: The run manager to pass to the function.
454
450
  **kwargs: The keyword arguments to pass to the function.
455
451
 
456
452
  Returns:
@@ -470,13 +466,11 @@ def get_callback_manager_for_config(config: RunnableConfig) -> CallbackManager:
470
466
  """Get a callback manager for a config.
471
467
 
472
468
  Args:
473
- config (RunnableConfig): The config.
469
+ config: The config.
474
470
 
475
471
  Returns:
476
- CallbackManager: The callback manager.
472
+ The callback manager.
477
473
  """
478
- from langchain_core.callbacks.manager import CallbackManager
479
-
480
474
  return CallbackManager.configure(
481
475
  inheritable_callbacks=config.get("callbacks"),
482
476
  inheritable_tags=config.get("tags"),
@@ -490,13 +484,11 @@ def get_async_callback_manager_for_config(
490
484
  """Get an async callback manager for a config.
491
485
 
492
486
  Args:
493
- config (RunnableConfig): The config.
487
+ config: The config.
494
488
 
495
489
  Returns:
496
- AsyncCallbackManager: The async callback manager.
490
+ The async callback manager.
497
491
  """
498
- from langchain_core.callbacks.manager import AsyncCallbackManager
499
-
500
492
  return AsyncCallbackManager.configure(
501
493
  inheritable_callbacks=config.get("callbacks"),
502
494
  inheritable_tags=config.get("tags"),
@@ -520,12 +512,12 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor):
520
512
  """Submit a function to the executor.
521
513
 
522
514
  Args:
523
- func (Callable[..., T]): The function to submit.
524
- *args (Any): The positional arguments to the function.
525
- **kwargs (Any): The keyword arguments to the function.
515
+ func: The function to submit.
516
+ *args: The positional arguments to the function.
517
+ **kwargs: The keyword arguments to the function.
526
518
 
527
519
  Returns:
528
- Future[T]: The future for the function.
520
+ The future for the function.
529
521
  """
530
522
  return super().submit(
531
523
  cast("Callable[..., T]", partial(copy_context().run, func, *args, **kwargs))
@@ -535,20 +527,18 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor):
535
527
  self,
536
528
  fn: Callable[..., T],
537
529
  *iterables: Iterable[Any],
538
- timeout: float | None = None,
539
- chunksize: int = 1,
530
+ **kwargs: Any,
540
531
  ) -> Iterator[T]:
541
532
  """Map a function to multiple iterables.
542
533
 
543
534
  Args:
544
- fn (Callable[..., T]): The function to map.
545
- *iterables (Iterable[Any]): The iterables to map over.
546
- timeout (float | None, optional): The timeout for the map.
547
- Defaults to None.
548
- chunksize (int, optional): The chunksize for the map. Defaults to 1.
535
+ fn: The function to map.
536
+ *iterables: The iterables to map over.
537
+ timeout: The timeout for the map.
538
+ chunksize: The chunksize for the map.
549
539
 
550
540
  Returns:
551
- Iterator[T]: The iterator for the mapped function.
541
+ The iterator for the mapped function.
552
542
  """
553
543
  contexts = [copy_context() for _ in range(len(iterables[0]))] # type: ignore[arg-type]
554
544
 
@@ -558,22 +548,21 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor):
558
548
  return super().map(
559
549
  _wrapped_fn,
560
550
  *iterables,
561
- timeout=timeout,
562
- chunksize=chunksize,
551
+ **kwargs,
563
552
  )
564
553
 
565
554
 
566
555
  @contextmanager
567
556
  def get_executor_for_config(
568
- config: Optional[RunnableConfig],
557
+ config: RunnableConfig | None,
569
558
  ) -> Generator[Executor, None, None]:
570
559
  """Get an executor for a config.
571
560
 
572
561
  Args:
573
- config (RunnableConfig): The config.
562
+ config: The config.
574
563
 
575
564
  Yields:
576
- Generator[Executor, None, None]: The executor.
565
+ The executor.
577
566
  """
578
567
  config = config or {}
579
568
  with ContextThreadPoolExecutor(
@@ -583,7 +572,7 @@ def get_executor_for_config(
583
572
 
584
573
 
585
574
  async def run_in_executor(
586
- executor_or_config: Optional[Union[Executor, RunnableConfig]],
575
+ executor_or_config: Executor | RunnableConfig | None,
587
576
  func: Callable[P, T],
588
577
  *args: P.args,
589
578
  **kwargs: P.kwargs,
@@ -592,15 +581,12 @@ async def run_in_executor(
592
581
 
593
582
  Args:
594
583
  executor_or_config: The executor or config to run in.
595
- func (Callable[P, Output]): The function.
596
- *args (Any): The positional arguments to the function.
597
- **kwargs (Any): The keyword arguments to the function.
584
+ func: The function.
585
+ *args: The positional arguments to the function.
586
+ **kwargs: The keyword arguments to the function.
598
587
 
599
588
  Returns:
600
- Output: The output of the function.
601
-
602
- Raises:
603
- RuntimeError: If the function raises a StopIteration.
589
+ The output of the function.
604
590
  """
605
591
 
606
592
  def wrapper() -> T: