langchain-core 1.0.0a5__py3-none-any.whl → 1.0.0a7__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 (132) hide show
  1. langchain_core/_api/__init__.py +3 -3
  2. langchain_core/_api/beta_decorator.py +6 -6
  3. langchain_core/_api/deprecation.py +21 -29
  4. langchain_core/_api/path.py +3 -6
  5. langchain_core/_import_utils.py +2 -3
  6. langchain_core/agents.py +10 -11
  7. langchain_core/caches.py +7 -7
  8. langchain_core/callbacks/base.py +91 -91
  9. langchain_core/callbacks/file.py +11 -11
  10. langchain_core/callbacks/manager.py +86 -89
  11. langchain_core/callbacks/stdout.py +8 -8
  12. langchain_core/callbacks/usage.py +4 -4
  13. langchain_core/chat_history.py +1 -37
  14. langchain_core/document_loaders/base.py +2 -2
  15. langchain_core/document_loaders/langsmith.py +15 -15
  16. langchain_core/documents/base.py +16 -16
  17. langchain_core/documents/compressor.py +4 -4
  18. langchain_core/example_selectors/length_based.py +1 -1
  19. langchain_core/example_selectors/semantic_similarity.py +17 -19
  20. langchain_core/exceptions.py +3 -3
  21. langchain_core/globals.py +3 -151
  22. langchain_core/indexing/api.py +44 -43
  23. langchain_core/indexing/base.py +30 -30
  24. langchain_core/indexing/in_memory.py +3 -3
  25. langchain_core/language_models/_utils.py +5 -7
  26. langchain_core/language_models/base.py +18 -132
  27. langchain_core/language_models/chat_models.py +118 -227
  28. langchain_core/language_models/fake.py +11 -11
  29. langchain_core/language_models/fake_chat_models.py +35 -29
  30. langchain_core/language_models/llms.py +91 -201
  31. langchain_core/load/dump.py +1 -1
  32. langchain_core/load/load.py +11 -12
  33. langchain_core/load/mapping.py +2 -4
  34. langchain_core/load/serializable.py +2 -4
  35. langchain_core/messages/ai.py +17 -20
  36. langchain_core/messages/base.py +28 -26
  37. langchain_core/messages/block_translators/__init__.py +17 -7
  38. langchain_core/messages/block_translators/anthropic.py +3 -3
  39. langchain_core/messages/block_translators/bedrock_converse.py +2 -2
  40. langchain_core/messages/block_translators/google_genai.py +502 -20
  41. langchain_core/messages/block_translators/langchain_v0.py +2 -2
  42. langchain_core/messages/block_translators/openai.py +6 -6
  43. langchain_core/messages/content.py +120 -124
  44. langchain_core/messages/human.py +7 -7
  45. langchain_core/messages/system.py +7 -7
  46. langchain_core/messages/tool.py +24 -24
  47. langchain_core/messages/utils.py +67 -79
  48. langchain_core/output_parsers/base.py +12 -14
  49. langchain_core/output_parsers/json.py +4 -4
  50. langchain_core/output_parsers/list.py +3 -5
  51. langchain_core/output_parsers/openai_functions.py +3 -3
  52. langchain_core/output_parsers/openai_tools.py +3 -3
  53. langchain_core/output_parsers/pydantic.py +2 -2
  54. langchain_core/output_parsers/transform.py +13 -15
  55. langchain_core/output_parsers/xml.py +7 -9
  56. langchain_core/outputs/chat_generation.py +4 -4
  57. langchain_core/outputs/chat_result.py +1 -3
  58. langchain_core/outputs/generation.py +2 -2
  59. langchain_core/outputs/llm_result.py +5 -5
  60. langchain_core/prompts/__init__.py +1 -5
  61. langchain_core/prompts/base.py +10 -15
  62. langchain_core/prompts/chat.py +31 -82
  63. langchain_core/prompts/dict.py +2 -2
  64. langchain_core/prompts/few_shot.py +5 -5
  65. langchain_core/prompts/few_shot_with_templates.py +4 -4
  66. langchain_core/prompts/loading.py +3 -5
  67. langchain_core/prompts/prompt.py +4 -16
  68. langchain_core/prompts/string.py +2 -1
  69. langchain_core/prompts/structured.py +16 -23
  70. langchain_core/rate_limiters.py +3 -4
  71. langchain_core/retrievers.py +14 -14
  72. langchain_core/runnables/base.py +938 -1054
  73. langchain_core/runnables/branch.py +36 -40
  74. langchain_core/runnables/config.py +27 -35
  75. langchain_core/runnables/configurable.py +108 -124
  76. langchain_core/runnables/fallbacks.py +76 -72
  77. langchain_core/runnables/graph.py +39 -45
  78. langchain_core/runnables/graph_ascii.py +9 -11
  79. langchain_core/runnables/graph_mermaid.py +18 -19
  80. langchain_core/runnables/graph_png.py +8 -9
  81. langchain_core/runnables/history.py +114 -127
  82. langchain_core/runnables/passthrough.py +113 -139
  83. langchain_core/runnables/retry.py +43 -48
  84. langchain_core/runnables/router.py +23 -28
  85. langchain_core/runnables/schema.py +42 -44
  86. langchain_core/runnables/utils.py +28 -31
  87. langchain_core/stores.py +9 -13
  88. langchain_core/structured_query.py +8 -8
  89. langchain_core/tools/base.py +63 -115
  90. langchain_core/tools/convert.py +31 -35
  91. langchain_core/tools/render.py +1 -1
  92. langchain_core/tools/retriever.py +4 -4
  93. langchain_core/tools/simple.py +13 -17
  94. langchain_core/tools/structured.py +12 -15
  95. langchain_core/tracers/base.py +62 -64
  96. langchain_core/tracers/context.py +17 -35
  97. langchain_core/tracers/core.py +49 -53
  98. langchain_core/tracers/evaluation.py +11 -11
  99. langchain_core/tracers/event_stream.py +58 -60
  100. langchain_core/tracers/langchain.py +13 -13
  101. langchain_core/tracers/log_stream.py +22 -24
  102. langchain_core/tracers/root_listeners.py +14 -14
  103. langchain_core/tracers/run_collector.py +2 -4
  104. langchain_core/tracers/schemas.py +8 -8
  105. langchain_core/tracers/stdout.py +2 -1
  106. langchain_core/utils/__init__.py +0 -3
  107. langchain_core/utils/_merge.py +2 -2
  108. langchain_core/utils/aiter.py +24 -28
  109. langchain_core/utils/env.py +4 -4
  110. langchain_core/utils/function_calling.py +31 -41
  111. langchain_core/utils/html.py +3 -4
  112. langchain_core/utils/input.py +3 -3
  113. langchain_core/utils/iter.py +15 -19
  114. langchain_core/utils/json.py +3 -2
  115. langchain_core/utils/json_schema.py +6 -6
  116. langchain_core/utils/mustache.py +3 -5
  117. langchain_core/utils/pydantic.py +16 -18
  118. langchain_core/utils/usage.py +1 -1
  119. langchain_core/utils/utils.py +29 -29
  120. langchain_core/vectorstores/base.py +18 -21
  121. langchain_core/vectorstores/in_memory.py +14 -87
  122. langchain_core/vectorstores/utils.py +2 -2
  123. langchain_core/version.py +1 -1
  124. {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.0a7.dist-info}/METADATA +10 -31
  125. langchain_core-1.0.0a7.dist-info/RECORD +176 -0
  126. {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.0a7.dist-info}/WHEEL +1 -1
  127. langchain_core/messages/block_translators/ollama.py +0 -47
  128. langchain_core/prompts/pipeline.py +0 -138
  129. langchain_core/tracers/langchain_v1.py +0 -31
  130. langchain_core/utils/loading.py +0 -35
  131. langchain_core-1.0.0a5.dist-info/RECORD +0 -181
  132. langchain_core-1.0.0a5.dist-info/entry_points.txt +0 -4
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import logging
6
6
  from concurrent.futures import ThreadPoolExecutor
7
7
  from datetime import datetime, timezone
8
- from typing import TYPE_CHECKING, Any, Optional, Union
8
+ from typing import TYPE_CHECKING, Any
9
9
  from uuid import UUID
10
10
 
11
11
  from langsmith import Client, get_tracing_context
@@ -30,7 +30,7 @@ if TYPE_CHECKING:
30
30
 
31
31
  logger = logging.getLogger(__name__)
32
32
  _LOGGED = set()
33
- _EXECUTOR: Optional[ThreadPoolExecutor] = None
33
+ _EXECUTOR: ThreadPoolExecutor | None = None
34
34
 
35
35
 
36
36
  def log_error_once(method: str, exception: Exception) -> None:
@@ -76,10 +76,10 @@ class LangChainTracer(BaseTracer):
76
76
 
77
77
  def __init__(
78
78
  self,
79
- example_id: Optional[Union[UUID, str]] = None,
80
- project_name: Optional[str] = None,
81
- client: Optional[Client] = None,
82
- tags: Optional[list[str]] = None,
79
+ example_id: UUID | str | None = None,
80
+ project_name: str | None = None,
81
+ client: Client | None = None,
82
+ tags: list[str] | None = None,
83
83
  **kwargs: Any,
84
84
  ) -> None:
85
85
  """Initialize the LangChain tracer.
@@ -98,7 +98,7 @@ class LangChainTracer(BaseTracer):
98
98
  self.project_name = project_name or ls_utils.get_tracer_project()
99
99
  self.client = client or get_client()
100
100
  self.tags = tags or []
101
- self.latest_run: Optional[Run] = None
101
+ self.latest_run: Run | None = None
102
102
  self.run_has_token_event_map: dict[str, bool] = {}
103
103
 
104
104
  def _start_trace(self, run: Run) -> None:
@@ -122,10 +122,10 @@ class LangChainTracer(BaseTracer):
122
122
  messages: list[list[BaseMessage]],
123
123
  *,
124
124
  run_id: UUID,
125
- tags: Optional[list[str]] = None,
126
- parent_run_id: Optional[UUID] = None,
127
- metadata: Optional[dict[str, Any]] = None,
128
- name: Optional[str] = None,
125
+ tags: list[str] | None = None,
126
+ parent_run_id: UUID | None = None,
127
+ metadata: dict[str, Any] | None = None,
128
+ name: str | None = None,
129
129
  **kwargs: Any,
130
130
  ) -> Run:
131
131
  """Start a trace for an LLM run.
@@ -242,8 +242,8 @@ class LangChainTracer(BaseTracer):
242
242
  self,
243
243
  token: str,
244
244
  run_id: UUID,
245
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
246
- parent_run_id: Optional[UUID] = None,
245
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
246
+ parent_run_id: UUID | None = None,
247
247
  ) -> Run:
248
248
  run_id_str = str(run_id)
249
249
  if run_id_str not in self.run_has_token_event_map:
@@ -12,9 +12,7 @@ from typing import (
12
12
  TYPE_CHECKING,
13
13
  Any,
14
14
  Literal,
15
- Optional,
16
15
  TypeVar,
17
- Union,
18
16
  overload,
19
17
  )
20
18
 
@@ -59,13 +57,13 @@ class LogEntry(TypedDict):
59
57
  """List of LLM tokens streamed by this run, if applicable."""
60
58
  streamed_output: list[Any]
61
59
  """List of output chunks streamed by this run, if available."""
62
- inputs: NotRequired[Optional[Any]]
60
+ inputs: NotRequired[Any | None]
63
61
  """Inputs to this run. Not available currently via astream_log."""
64
- final_output: Optional[Any]
62
+ final_output: Any | None
65
63
  """Final output of this run.
66
64
 
67
65
  Only available after the run has finished successfully."""
68
- end_time: Optional[str]
66
+ end_time: str | None
69
67
  """ISO-8601 timestamp of when the run ended.
70
68
  Only available after the run has finished."""
71
69
 
@@ -77,7 +75,7 @@ class RunState(TypedDict):
77
75
  """ID of the run."""
78
76
  streamed_output: list[Any]
79
77
  """List of output chunks streamed by Runnable.stream()"""
80
- final_output: Optional[Any]
78
+ final_output: Any | None
81
79
  """Final output of the run, usually the result of aggregating (`+`) streamed_output.
82
80
  Updated throughout the run when supported by the Runnable."""
83
81
 
@@ -112,7 +110,7 @@ class RunLogPatch:
112
110
  """
113
111
  self.ops = list(ops)
114
112
 
115
- def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:
113
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
116
114
  """Combine two ``RunLogPatch`` instances.
117
115
 
118
116
  Args:
@@ -160,7 +158,7 @@ class RunLog(RunLogPatch):
160
158
  super().__init__(*ops)
161
159
  self.state = state
162
160
 
163
- def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:
161
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
164
162
  """Combine two ``RunLog``s.
165
163
 
166
164
  Args:
@@ -215,12 +213,12 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
215
213
  self,
216
214
  *,
217
215
  auto_close: bool = True,
218
- include_names: Optional[Sequence[str]] = None,
219
- include_types: Optional[Sequence[str]] = None,
220
- include_tags: Optional[Sequence[str]] = None,
221
- exclude_names: Optional[Sequence[str]] = None,
222
- exclude_types: Optional[Sequence[str]] = None,
223
- exclude_tags: Optional[Sequence[str]] = None,
216
+ include_names: Sequence[str] | None = None,
217
+ include_types: Sequence[str] | None = None,
218
+ include_tags: Sequence[str] | None = None,
219
+ exclude_names: Sequence[str] | None = None,
220
+ exclude_types: Sequence[str] | None = None,
221
+ exclude_tags: Sequence[str] | None = None,
224
222
  # Schema format is for internal use only.
225
223
  _schema_format: Literal["original", "streaming_events"] = "streaming_events",
226
224
  ) -> None:
@@ -273,7 +271,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
273
271
  self.receive_stream = memory_stream.get_receive_stream()
274
272
  self._key_map_by_run_id: dict[UUID, str] = {}
275
273
  self._counter_map_by_name: dict[str, int] = defaultdict(int)
276
- self.root_id: Optional[UUID] = None
274
+ self.root_id: UUID | None = None
277
275
 
278
276
  def __aiter__(self) -> AsyncIterator[RunLogPatch]:
279
277
  """Iterate over the stream of run logs.
@@ -515,7 +513,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
515
513
  self,
516
514
  run: Run,
517
515
  token: str,
518
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]],
516
+ chunk: GenerationChunk | ChatGenerationChunk | None,
519
517
  ) -> None:
520
518
  """Process new LLM token."""
521
519
  index = self._key_map_by_run_id.get(run.id)
@@ -541,7 +539,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
541
539
 
542
540
  def _get_standardized_inputs(
543
541
  run: Run, schema_format: Literal["original", "streaming_events"]
544
- ) -> Optional[dict[str, Any]]:
542
+ ) -> dict[str, Any] | None:
545
543
  """Extract standardized inputs from a run.
546
544
 
547
545
  Standardizes the inputs based on the type of the runnable used.
@@ -583,7 +581,7 @@ def _get_standardized_inputs(
583
581
 
584
582
  def _get_standardized_outputs(
585
583
  run: Run, schema_format: Literal["original", "streaming_events", "original+chat"]
586
- ) -> Optional[Any]:
584
+ ) -> Any | None:
587
585
  """Extract standardized output from a run.
588
586
 
589
587
  Standardizes the outputs based on the type of the runnable used.
@@ -617,7 +615,7 @@ def _get_standardized_outputs(
617
615
  def _astream_log_implementation(
618
616
  runnable: Runnable[Input, Output],
619
617
  value: Any,
620
- config: Optional[RunnableConfig] = None,
618
+ config: RunnableConfig | None = None,
621
619
  *,
622
620
  stream: LogStreamCallbackHandler,
623
621
  diff: Literal[True] = True,
@@ -630,7 +628,7 @@ def _astream_log_implementation(
630
628
  def _astream_log_implementation(
631
629
  runnable: Runnable[Input, Output],
632
630
  value: Any,
633
- config: Optional[RunnableConfig] = None,
631
+ config: RunnableConfig | None = None,
634
632
  *,
635
633
  stream: LogStreamCallbackHandler,
636
634
  diff: Literal[False],
@@ -642,13 +640,13 @@ def _astream_log_implementation(
642
640
  async def _astream_log_implementation(
643
641
  runnable: Runnable[Input, Output],
644
642
  value: Any,
645
- config: Optional[RunnableConfig] = None,
643
+ config: RunnableConfig | None = None,
646
644
  *,
647
645
  stream: LogStreamCallbackHandler,
648
646
  diff: bool = True,
649
647
  with_streamed_output_list: bool = True,
650
648
  **kwargs: Any,
651
- ) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]:
649
+ ) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]:
652
650
  """Implementation of astream_log for a given runnable.
653
651
 
654
652
  The implementation has been factored out (at least temporarily) as both
@@ -693,8 +691,8 @@ async def _astream_log_implementation(
693
691
  # add each chunk to the output stream
694
692
  async def consume_astream() -> None:
695
693
  try:
696
- prev_final_output: Optional[Output] = None
697
- final_output: Optional[Output] = None
694
+ prev_final_output: Output | None = None
695
+ final_output: Output | None = None
698
696
 
699
697
  async for chunk in runnable.astream(value, config, **kwargs):
700
698
  prev_final_output = final_output
@@ -1,7 +1,7 @@
1
1
  """Tracers that call listeners."""
2
2
 
3
- from collections.abc import Awaitable
4
- from typing import TYPE_CHECKING, Callable, Optional, Union
3
+ from collections.abc import Awaitable, Callable
4
+ from typing import TYPE_CHECKING
5
5
 
6
6
  from langchain_core.runnables.config import (
7
7
  RunnableConfig,
@@ -14,10 +14,10 @@ from langchain_core.tracers.schemas import Run
14
14
  if TYPE_CHECKING:
15
15
  from uuid import UUID
16
16
 
17
- Listener = Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]
18
- AsyncListener = Union[
19
- Callable[[Run], Awaitable[None]], Callable[[Run, RunnableConfig], Awaitable[None]]
20
- ]
17
+ Listener = Callable[[Run], None] | Callable[[Run, RunnableConfig], None]
18
+ AsyncListener = (
19
+ Callable[[Run], Awaitable[None]] | Callable[[Run, RunnableConfig], Awaitable[None]]
20
+ )
21
21
 
22
22
 
23
23
  class RootListenersTracer(BaseTracer):
@@ -30,9 +30,9 @@ class RootListenersTracer(BaseTracer):
30
30
  self,
31
31
  *,
32
32
  config: RunnableConfig,
33
- on_start: Optional[Listener],
34
- on_end: Optional[Listener],
35
- on_error: Optional[Listener],
33
+ on_start: Listener | None,
34
+ on_end: Listener | None,
35
+ on_error: Listener | None,
36
36
  ) -> None:
37
37
  """Initialize the tracer.
38
38
 
@@ -48,7 +48,7 @@ class RootListenersTracer(BaseTracer):
48
48
  self._arg_on_start = on_start
49
49
  self._arg_on_end = on_end
50
50
  self._arg_on_error = on_error
51
- self.root_id: Optional[UUID] = None
51
+ self.root_id: UUID | None = None
52
52
 
53
53
  def _persist_run(self, run: Run) -> None:
54
54
  # This is a legacy method only called once for an entire run tree
@@ -85,9 +85,9 @@ class AsyncRootListenersTracer(AsyncBaseTracer):
85
85
  self,
86
86
  *,
87
87
  config: RunnableConfig,
88
- on_start: Optional[AsyncListener],
89
- on_end: Optional[AsyncListener],
90
- on_error: Optional[AsyncListener],
88
+ on_start: AsyncListener | None,
89
+ on_end: AsyncListener | None,
90
+ on_error: AsyncListener | None,
91
91
  ) -> None:
92
92
  """Initialize the tracer.
93
93
 
@@ -103,7 +103,7 @@ class AsyncRootListenersTracer(AsyncBaseTracer):
103
103
  self._arg_on_start = on_start
104
104
  self._arg_on_end = on_end
105
105
  self._arg_on_error = on_error
106
- self.root_id: Optional[UUID] = None
106
+ self.root_id: UUID | None = None
107
107
 
108
108
  async def _persist_run(self, run: Run) -> None:
109
109
  # This is a legacy method only called once for an entire run tree
@@ -1,6 +1,6 @@
1
1
  """A tracer that collects all nested runs in a list."""
2
2
 
3
- from typing import Any, Optional, Union
3
+ from typing import Any
4
4
  from uuid import UUID
5
5
 
6
6
  from langchain_core.tracers.base import BaseTracer
@@ -15,9 +15,7 @@ class RunCollectorCallbackHandler(BaseTracer):
15
15
 
16
16
  name: str = "run-collector_callback_handler"
17
17
 
18
- def __init__(
19
- self, example_id: Optional[Union[UUID, str]] = None, **kwargs: Any
20
- ) -> None:
18
+ def __init__(self, example_id: UUID | str | None = None, **kwargs: Any) -> None:
21
19
  """Initialize the RunCollectorCallbackHandler.
22
20
 
23
21
  Args:
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import warnings
6
6
  from datetime import datetime, timezone
7
- from typing import Any, Optional
7
+ from typing import Any
8
8
  from uuid import UUID
9
9
 
10
10
  from langsmith import RunTree
@@ -37,8 +37,8 @@ class TracerSessionV1Base(BaseModelV1):
37
37
  """Base class for TracerSessionV1."""
38
38
 
39
39
  start_time: datetime = FieldV1(default_factory=lambda: datetime.now(timezone.utc))
40
- name: Optional[str] = None
41
- extra: Optional[dict[str, Any]] = None
40
+ name: str | None = None
41
+ extra: dict[str, Any] | None = None
42
42
 
43
43
 
44
44
  @deprecated("0.1.0", removal="1.0")
@@ -72,15 +72,15 @@ class BaseRun(BaseModelV1):
72
72
  """Base class for Run."""
73
73
 
74
74
  uuid: str
75
- parent_uuid: Optional[str] = None
75
+ parent_uuid: str | None = None
76
76
  start_time: datetime = FieldV1(default_factory=lambda: datetime.now(timezone.utc))
77
77
  end_time: datetime = FieldV1(default_factory=lambda: datetime.now(timezone.utc))
78
- extra: Optional[dict[str, Any]] = None
78
+ extra: dict[str, Any] | None = None
79
79
  execution_order: int
80
80
  child_execution_order: int
81
81
  serialized: dict[str, Any]
82
82
  session_id: int
83
- error: Optional[str] = None
83
+ error: str | None = None
84
84
 
85
85
 
86
86
  @deprecated("0.1.0", alternative="Run", removal="1.0")
@@ -97,7 +97,7 @@ class ChainRun(BaseRun):
97
97
  """Class for ChainRun."""
98
98
 
99
99
  inputs: dict[str, Any]
100
- outputs: Optional[dict[str, Any]] = None
100
+ outputs: dict[str, Any] | None = None
101
101
  child_llm_runs: list[LLMRun] = FieldV1(default_factory=list)
102
102
  child_chain_runs: list[ChainRun] = FieldV1(default_factory=list)
103
103
  child_tool_runs: list[ToolRun] = FieldV1(default_factory=list)
@@ -108,7 +108,7 @@ class ToolRun(BaseRun):
108
108
  """Class for ToolRun."""
109
109
 
110
110
  tool_input: str
111
- output: Optional[str] = None
111
+ output: str | None = None
112
112
  action: str
113
113
  child_llm_runs: list[LLMRun] = FieldV1(default_factory=list)
114
114
  child_chain_runs: list[ChainRun] = FieldV1(default_factory=list)
@@ -1,7 +1,8 @@
1
1
  """Tracers that print to the console."""
2
2
 
3
3
  import json
4
- from typing import Any, Callable
4
+ from collections.abc import Callable
5
+ from typing import Any
5
6
 
6
7
  from langchain_core.tracers.base import BaseTracer
7
8
  from langchain_core.tracers.schemas import Run
@@ -21,7 +21,6 @@ if TYPE_CHECKING:
21
21
  print_text,
22
22
  )
23
23
  from langchain_core.utils.iter import batch_iterate
24
- from langchain_core.utils.loading import try_load_from_hub
25
24
  from langchain_core.utils.pydantic import pre_init
26
25
  from langchain_core.utils.strings import (
27
26
  comma_list,
@@ -68,7 +67,6 @@ __all__ = (
68
67
  "secret_from_env",
69
68
  "stringify_dict",
70
69
  "stringify_value",
71
- "try_load_from_hub",
72
70
  "xor_args",
73
71
  )
74
72
 
@@ -84,7 +82,6 @@ _dynamic_imports = {
84
82
  "get_colored_text": "input",
85
83
  "print_text": "input",
86
84
  "batch_iterate": "iter",
87
- "try_load_from_hub": "loading",
88
85
  "pre_init": "pydantic",
89
86
  "comma_list": "strings",
90
87
  "sanitize_for_postgres": "strings",
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import Any, Optional
3
+ from typing import Any
4
4
 
5
5
 
6
6
  def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:
@@ -80,7 +80,7 @@ def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]
80
80
  return merged
81
81
 
82
82
 
83
- def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]:
83
+ def merge_lists(left: list | None, *others: list | None) -> list | None:
84
84
  """Add many lists, handling None.
85
85
 
86
86
  Args:
@@ -11,17 +11,15 @@ from collections.abc import (
11
11
  AsyncIterable,
12
12
  AsyncIterator,
13
13
  Awaitable,
14
+ Callable,
14
15
  Iterator,
15
16
  )
16
17
  from contextlib import AbstractAsyncContextManager
17
18
  from types import TracebackType
18
19
  from typing import (
19
20
  Any,
20
- Callable,
21
21
  Generic,
22
- Optional,
23
22
  TypeVar,
24
- Union,
25
23
  cast,
26
24
  overload,
27
25
  )
@@ -36,8 +34,8 @@ _no_default = object()
36
34
  # https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
37
35
  # before 3.10, the builtin anext() was not available
38
36
  def py_anext(
39
- iterator: AsyncIterator[T], default: Union[T, Any] = _no_default
40
- ) -> Awaitable[Union[T, Any, None]]:
37
+ iterator: AsyncIterator[T], default: T | Any = _no_default
38
+ ) -> Awaitable[T | Any | None]:
41
39
  """Pure-Python implementation of anext() for testing purposes.
42
40
 
43
41
  Closely matches the builtin anext() C implementation.
@@ -68,7 +66,7 @@ def py_anext(
68
66
  if default is _no_default:
69
67
  return __anext__(iterator)
70
68
 
71
- async def anext_impl() -> Union[T, Any]:
69
+ async def anext_impl() -> T | Any:
72
70
  try:
73
71
  # The C code is way more low-level than this, as it implements
74
72
  # all methods of the iterator protocol. In this implementation
@@ -90,9 +88,9 @@ class NoLock:
90
88
 
91
89
  async def __aexit__(
92
90
  self,
93
- exc_type: Optional[type[BaseException]],
94
- exc_val: Optional[BaseException],
95
- exc_tb: Optional[TracebackType],
91
+ exc_type: type[BaseException] | None,
92
+ exc_val: BaseException | None,
93
+ exc_tb: TracebackType | None,
96
94
  ) -> bool:
97
95
  """Return False, exception not suppressed."""
98
96
  return False
@@ -106,7 +104,7 @@ async def tee_peer(
106
104
  peers: list[deque[T]],
107
105
  lock: AbstractAsyncContextManager[Any],
108
106
  ) -> AsyncGenerator[T, None]:
109
- """An individual iterator of a :py:func:`~.tee`.
107
+ """An individual iterator of a `tee`.
110
108
 
111
109
  This function is a generator that yields items from the shared iterator
112
110
  ``iterator``. It buffers items until the least advanced iterator has
@@ -172,22 +170,22 @@ class Tee(Generic[T]):
172
170
  await a.anext(previous) # advance one iterator
173
171
  return a.map(operator.sub, previous, current)
174
172
 
175
- Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead
176
- of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked
177
- to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
173
+ Unlike `itertools.tee`, `.tee` returns a custom type instead
174
+ of a :py`tuple`. Like a tuple, it can be indexed, iterated and unpacked
175
+ to get the child iterators. In addition, its `.tee.aclose` method
178
176
  immediately closes all children, and it can be used in an ``async with`` context
179
177
  for the same effect.
180
178
 
181
179
  If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
182
180
  provide these items. Also, ``tee`` must internally buffer each item until the
183
181
  last iterator has yielded it; if the most and least advanced iterator differ
184
- by most data, using a :py:class:`list` is more efficient (but not lazy).
182
+ by most data, using a :py`list` is more efficient (but not lazy).
185
183
 
186
184
  If the underlying iterable is concurrency safe (``anext`` may be awaited
187
185
  concurrently) the resulting iterators are concurrency safe as well. Otherwise,
188
186
  the iterators are safe if there is only ever one single "most advanced" iterator.
189
187
  To enforce sequential use of ``anext``, provide a ``lock``
190
- - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
188
+ - e.g. an :py`asyncio.Lock` instance in an :py:mod:`asyncio` application -
191
189
  and access is automatically synchronised.
192
190
 
193
191
  """
@@ -197,7 +195,7 @@ class Tee(Generic[T]):
197
195
  iterable: AsyncIterator[T],
198
196
  n: int = 2,
199
197
  *,
200
- lock: Optional[AbstractAsyncContextManager[Any]] = None,
198
+ lock: AbstractAsyncContextManager[Any] | None = None,
201
199
  ):
202
200
  """Create a ``tee``.
203
201
 
@@ -230,8 +228,8 @@ class Tee(Generic[T]):
230
228
  def __getitem__(self, item: slice) -> tuple[AsyncIterator[T], ...]: ...
231
229
 
232
230
  def __getitem__(
233
- self, item: Union[int, slice]
234
- ) -> Union[AsyncIterator[T], tuple[AsyncIterator[T], ...]]:
231
+ self, item: int | slice
232
+ ) -> AsyncIterator[T] | tuple[AsyncIterator[T], ...]:
235
233
  """Return the child iterator(s) for the given index or slice."""
236
234
  return self._children[item]
237
235
 
@@ -249,9 +247,9 @@ class Tee(Generic[T]):
249
247
 
250
248
  async def __aexit__(
251
249
  self,
252
- exc_type: Optional[type[BaseException]],
253
- exc_val: Optional[BaseException],
254
- exc_tb: Optional[TracebackType],
250
+ exc_type: type[BaseException] | None,
251
+ exc_val: BaseException | None,
252
+ exc_tb: TracebackType | None,
255
253
  ) -> bool:
256
254
  """Close all child iterators.
257
255
 
@@ -292,9 +290,7 @@ class aclosing(AbstractAsyncContextManager): # noqa: N801
292
290
 
293
291
  """
294
292
 
295
- def __init__(
296
- self, thing: Union[AsyncGenerator[Any, Any], AsyncIterator[Any]]
297
- ) -> None:
293
+ def __init__(self, thing: AsyncGenerator[Any, Any] | AsyncIterator[Any]) -> None:
298
294
  """Create the context manager.
299
295
 
300
296
  Args:
@@ -303,15 +299,15 @@ class aclosing(AbstractAsyncContextManager): # noqa: N801
303
299
  self.thing = thing
304
300
 
305
301
  @override
306
- async def __aenter__(self) -> Union[AsyncGenerator[Any, Any], AsyncIterator[Any]]:
302
+ async def __aenter__(self) -> AsyncGenerator[Any, Any] | AsyncIterator[Any]:
307
303
  return self.thing
308
304
 
309
305
  @override
310
306
  async def __aexit__(
311
307
  self,
312
- exc_type: Optional[type[BaseException]],
313
- exc_value: Optional[BaseException],
314
- traceback: Optional[TracebackType],
308
+ exc_type: type[BaseException] | None,
309
+ exc_value: BaseException | None,
310
+ traceback: TracebackType | None,
315
311
  ) -> None:
316
312
  if hasattr(self.thing, "aclose"):
317
313
  await self.thing.aclose()
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
- from typing import Any, Optional, Union
6
+ from typing import Any
7
7
 
8
8
 
9
9
  def env_var_is_set(env_var: str) -> bool:
@@ -25,9 +25,9 @@ def env_var_is_set(env_var: str) -> bool:
25
25
 
26
26
  def get_from_dict_or_env(
27
27
  data: dict[str, Any],
28
- key: Union[str, list[str]],
28
+ key: str | list[str],
29
29
  env_key: str,
30
- default: Optional[str] = None,
30
+ default: str | None = None,
31
31
  ) -> str:
32
32
  """Get a value from a dictionary or an environment variable.
33
33
 
@@ -56,7 +56,7 @@ def get_from_dict_or_env(
56
56
  return get_from_env(key_for_err, env_key, default=default)
57
57
 
58
58
 
59
- def get_from_env(key: str, env_key: str, default: Optional[str] = None) -> str:
59
+ def get_from_env(key: str, env_key: str, default: str | None = None) -> str:
60
60
  """Get a value from a dictionary or an environment variable.
61
61
 
62
62
  Args: