langchain-core 1.0.0a6__py3-none-any.whl → 1.0.4__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.
Files changed (165) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +23 -26
  4. langchain_core/_api/deprecation.py +51 -64
  5. langchain_core/_api/path.py +3 -6
  6. langchain_core/_import_utils.py +3 -4
  7. langchain_core/agents.py +55 -48
  8. langchain_core/caches.py +65 -66
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +321 -336
  11. langchain_core/callbacks/file.py +44 -44
  12. langchain_core/callbacks/manager.py +454 -514
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +32 -32
  15. langchain_core/callbacks/usage.py +60 -57
  16. langchain_core/chat_history.py +53 -68
  17. langchain_core/document_loaders/base.py +27 -25
  18. langchain_core/document_loaders/blob_loaders.py +1 -1
  19. langchain_core/document_loaders/langsmith.py +44 -48
  20. langchain_core/documents/__init__.py +23 -3
  21. langchain_core/documents/base.py +102 -94
  22. langchain_core/documents/compressor.py +10 -10
  23. langchain_core/documents/transformers.py +34 -35
  24. langchain_core/embeddings/fake.py +50 -54
  25. langchain_core/example_selectors/length_based.py +2 -2
  26. langchain_core/example_selectors/semantic_similarity.py +28 -32
  27. langchain_core/exceptions.py +21 -20
  28. langchain_core/globals.py +3 -151
  29. langchain_core/indexing/__init__.py +1 -1
  30. langchain_core/indexing/api.py +121 -126
  31. langchain_core/indexing/base.py +73 -75
  32. langchain_core/indexing/in_memory.py +4 -6
  33. langchain_core/language_models/__init__.py +14 -29
  34. langchain_core/language_models/_utils.py +58 -61
  35. langchain_core/language_models/base.py +82 -172
  36. langchain_core/language_models/chat_models.py +329 -402
  37. langchain_core/language_models/fake.py +11 -11
  38. langchain_core/language_models/fake_chat_models.py +42 -36
  39. langchain_core/language_models/llms.py +189 -269
  40. langchain_core/load/dump.py +9 -12
  41. langchain_core/load/load.py +18 -28
  42. langchain_core/load/mapping.py +2 -4
  43. langchain_core/load/serializable.py +42 -40
  44. langchain_core/messages/__init__.py +10 -16
  45. langchain_core/messages/ai.py +148 -148
  46. langchain_core/messages/base.py +53 -51
  47. langchain_core/messages/block_translators/__init__.py +19 -22
  48. langchain_core/messages/block_translators/anthropic.py +6 -6
  49. langchain_core/messages/block_translators/bedrock_converse.py +5 -5
  50. langchain_core/messages/block_translators/google_genai.py +10 -7
  51. langchain_core/messages/block_translators/google_vertexai.py +4 -32
  52. langchain_core/messages/block_translators/groq.py +117 -21
  53. langchain_core/messages/block_translators/langchain_v0.py +5 -5
  54. langchain_core/messages/block_translators/openai.py +11 -11
  55. langchain_core/messages/chat.py +2 -6
  56. langchain_core/messages/content.py +339 -330
  57. langchain_core/messages/function.py +6 -10
  58. langchain_core/messages/human.py +24 -31
  59. langchain_core/messages/modifier.py +2 -2
  60. langchain_core/messages/system.py +19 -29
  61. langchain_core/messages/tool.py +74 -90
  62. langchain_core/messages/utils.py +484 -510
  63. langchain_core/output_parsers/__init__.py +13 -10
  64. langchain_core/output_parsers/base.py +61 -61
  65. langchain_core/output_parsers/format_instructions.py +9 -4
  66. langchain_core/output_parsers/json.py +12 -10
  67. langchain_core/output_parsers/list.py +21 -23
  68. langchain_core/output_parsers/openai_functions.py +49 -47
  69. langchain_core/output_parsers/openai_tools.py +30 -23
  70. langchain_core/output_parsers/pydantic.py +13 -14
  71. langchain_core/output_parsers/string.py +5 -5
  72. langchain_core/output_parsers/transform.py +15 -17
  73. langchain_core/output_parsers/xml.py +35 -34
  74. langchain_core/outputs/__init__.py +1 -1
  75. langchain_core/outputs/chat_generation.py +18 -18
  76. langchain_core/outputs/chat_result.py +1 -3
  77. langchain_core/outputs/generation.py +16 -16
  78. langchain_core/outputs/llm_result.py +10 -10
  79. langchain_core/prompt_values.py +13 -19
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +81 -86
  82. langchain_core/prompts/chat.py +308 -351
  83. langchain_core/prompts/dict.py +6 -6
  84. langchain_core/prompts/few_shot.py +81 -88
  85. langchain_core/prompts/few_shot_with_templates.py +11 -13
  86. langchain_core/prompts/image.py +12 -14
  87. langchain_core/prompts/loading.py +4 -6
  88. langchain_core/prompts/message.py +7 -7
  89. langchain_core/prompts/prompt.py +24 -39
  90. langchain_core/prompts/string.py +26 -10
  91. langchain_core/prompts/structured.py +49 -53
  92. langchain_core/rate_limiters.py +51 -60
  93. langchain_core/retrievers.py +61 -198
  94. langchain_core/runnables/base.py +1551 -1656
  95. langchain_core/runnables/branch.py +68 -70
  96. langchain_core/runnables/config.py +72 -89
  97. langchain_core/runnables/configurable.py +145 -161
  98. langchain_core/runnables/fallbacks.py +102 -96
  99. langchain_core/runnables/graph.py +91 -97
  100. langchain_core/runnables/graph_ascii.py +27 -28
  101. langchain_core/runnables/graph_mermaid.py +42 -51
  102. langchain_core/runnables/graph_png.py +43 -16
  103. langchain_core/runnables/history.py +175 -177
  104. langchain_core/runnables/passthrough.py +151 -167
  105. langchain_core/runnables/retry.py +46 -51
  106. langchain_core/runnables/router.py +30 -35
  107. langchain_core/runnables/schema.py +75 -80
  108. langchain_core/runnables/utils.py +60 -67
  109. langchain_core/stores.py +85 -121
  110. langchain_core/structured_query.py +8 -8
  111. langchain_core/sys_info.py +29 -29
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +306 -245
  114. langchain_core/tools/convert.py +160 -155
  115. langchain_core/tools/render.py +10 -10
  116. langchain_core/tools/retriever.py +12 -11
  117. langchain_core/tools/simple.py +19 -24
  118. langchain_core/tools/structured.py +32 -39
  119. langchain_core/tracers/__init__.py +1 -9
  120. langchain_core/tracers/base.py +97 -99
  121. langchain_core/tracers/context.py +29 -52
  122. langchain_core/tracers/core.py +49 -53
  123. langchain_core/tracers/evaluation.py +11 -11
  124. langchain_core/tracers/event_stream.py +65 -64
  125. langchain_core/tracers/langchain.py +21 -21
  126. langchain_core/tracers/log_stream.py +45 -45
  127. langchain_core/tracers/memory_stream.py +3 -3
  128. langchain_core/tracers/root_listeners.py +16 -16
  129. langchain_core/tracers/run_collector.py +2 -4
  130. langchain_core/tracers/schemas.py +0 -129
  131. langchain_core/tracers/stdout.py +3 -3
  132. langchain_core/utils/__init__.py +1 -4
  133. langchain_core/utils/_merge.py +2 -2
  134. langchain_core/utils/aiter.py +57 -61
  135. langchain_core/utils/env.py +9 -9
  136. langchain_core/utils/function_calling.py +94 -188
  137. langchain_core/utils/html.py +7 -8
  138. langchain_core/utils/input.py +9 -6
  139. langchain_core/utils/interactive_env.py +1 -1
  140. langchain_core/utils/iter.py +36 -40
  141. langchain_core/utils/json.py +4 -3
  142. langchain_core/utils/json_schema.py +9 -9
  143. langchain_core/utils/mustache.py +8 -10
  144. langchain_core/utils/pydantic.py +35 -37
  145. langchain_core/utils/strings.py +6 -9
  146. langchain_core/utils/usage.py +1 -1
  147. langchain_core/utils/utils.py +66 -62
  148. langchain_core/vectorstores/base.py +182 -216
  149. langchain_core/vectorstores/in_memory.py +101 -176
  150. langchain_core/vectorstores/utils.py +5 -5
  151. langchain_core/version.py +1 -1
  152. langchain_core-1.0.4.dist-info/METADATA +69 -0
  153. langchain_core-1.0.4.dist-info/RECORD +172 -0
  154. {langchain_core-1.0.0a6.dist-info → langchain_core-1.0.4.dist-info}/WHEEL +1 -1
  155. langchain_core/memory.py +0 -120
  156. langchain_core/messages/block_translators/ollama.py +0 -47
  157. langchain_core/prompts/pipeline.py +0 -138
  158. langchain_core/pydantic_v1/__init__.py +0 -30
  159. langchain_core/pydantic_v1/dataclasses.py +0 -23
  160. langchain_core/pydantic_v1/main.py +0 -23
  161. langchain_core/tracers/langchain_v1.py +0 -31
  162. langchain_core/utils/loading.py +0 -35
  163. langchain_core-1.0.0a6.dist-info/METADATA +0 -67
  164. langchain_core-1.0.0a6.dist-info/RECORD +0 -181
  165. langchain_core-1.0.0a6.dist-info/entry_points.txt +0 -4
@@ -1,4 +1,4 @@
1
- """``langchain-core`` defines the base abstractions for the LangChain ecosystem.
1
+ """`langchain-core` defines the base abstractions for the LangChain ecosystem.
2
2
 
3
3
  The interfaces for core components like chat models, LLMs, vector stores, retrievers,
4
4
  and more are defined here. The universal invocation protocol (Runnables) along with
@@ -2,11 +2,10 @@
2
2
 
3
3
  This module is only relevant for LangChain developers, not for users.
4
4
 
5
- .. warning::
6
-
7
- This module and its submodules are for internal use only. Do not use them
8
- in your own code. We may change the API at any time with no warning.
5
+ !!! warning
9
6
 
7
+ This module and its submodules are for internal use only. Do not use them in your
8
+ own code. We may change the API at any time with no warning.
10
9
  """
11
10
 
12
11
  from typing import TYPE_CHECKING
@@ -4,18 +4,18 @@ This module was loosely adapted from matplotlibs _api/deprecation.py module:
4
4
 
5
5
  https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py
6
6
 
7
- .. warning::
7
+ !!! warning
8
8
 
9
- This module is for internal use only. Do not use it in your own code.
10
- We may change the API at any time with no warning.
9
+ This module is for internal use only. Do not use it in your own code. We may change
10
+ the API at any time with no warning.
11
11
  """
12
12
 
13
13
  import contextlib
14
14
  import functools
15
15
  import inspect
16
16
  import warnings
17
- from collections.abc import Generator
18
- from typing import Any, Callable, TypeVar, Union, cast
17
+ from collections.abc import Callable, Generator
18
+ from typing import Any, TypeVar, cast
19
19
 
20
20
  from langchain_core._api.internal import is_caller_internal
21
21
 
@@ -27,7 +27,7 @@ class LangChainBetaWarning(DeprecationWarning):
27
27
  # PUBLIC API
28
28
 
29
29
 
30
- T = TypeVar("T", bound=Union[Callable[..., Any], type])
30
+ T = TypeVar("T", bound=Callable[..., Any] | type)
31
31
 
32
32
 
33
33
  def beta(
@@ -40,40 +40,37 @@ def beta(
40
40
  """Decorator to mark a function, a class, or a property as beta.
41
41
 
42
42
  When marking a classmethod, a staticmethod, or a property, the
43
- ``@beta`` decorator should go *under* ``@classmethod`` and
44
- ``@staticmethod`` (i.e., `beta` should directly decorate the
45
- underlying callable), but *over* ``@property``.
43
+ `@beta` decorator should go *under* `@classmethod` and
44
+ `@staticmethod` (i.e., `beta` should directly decorate the
45
+ underlying callable), but *over* `@property`.
46
46
 
47
- When marking a class ``C`` intended to be used as a base class in a
48
- multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method
49
- (if ``C`` instead inherited its ``__init__`` from its own base class, then
50
- ``@beta`` would mess up ``__init__`` inheritance when installing its
51
- own (annotation-emitting) ``C.__init__``).
47
+ When marking a class `C` intended to be used as a base class in a
48
+ multiple inheritance hierarchy, `C` *must* define an `__init__` method
49
+ (if `C` instead inherited its `__init__` from its own base class, then
50
+ `@beta` would mess up `__init__` inheritance when installing its
51
+ own (annotation-emitting) `C.__init__`).
52
52
 
53
53
  Args:
54
- message : str, optional
54
+ message:
55
55
  Override the default beta message. The %(since)s,
56
56
  %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s,
57
57
  and %(removal)s format specifiers will be replaced by the
58
58
  values of the respective arguments passed to this function.
59
- name : str, optional
59
+ name:
60
60
  The name of the beta object.
61
- obj_type : str, optional
61
+ obj_type:
62
62
  The object type being beta.
63
- addendum : str, optional
63
+ addendum:
64
64
  Additional text appended directly to the final message.
65
65
 
66
66
  Returns:
67
67
  A decorator which can be used to mark functions or classes as beta.
68
68
 
69
- Examples:
70
-
71
- .. code-block:: python
72
-
73
- @beta
74
- def the_function_to_annotate():
75
- pass
76
-
69
+ ```python
70
+ @beta
71
+ def the_function_to_annotate():
72
+ pass
73
+ ```
77
74
  """
78
75
 
79
76
  def beta(
@@ -4,23 +4,21 @@ This module was adapted from matplotlibs _api/deprecation.py module:
4
4
 
5
5
  https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py
6
6
 
7
- .. warning::
7
+ !!! warning
8
8
 
9
- This module is for internal use only. Do not use it in your own code.
10
- We may change the API at any time with no warning.
9
+ This module is for internal use only. Do not use it in your own code. We may change
10
+ the API at any time with no warning.
11
11
  """
12
12
 
13
13
  import contextlib
14
14
  import functools
15
15
  import inspect
16
16
  import warnings
17
- from collections.abc import Generator
17
+ from collections.abc import Callable, Generator
18
18
  from typing import (
19
19
  Any,
20
- Callable,
21
20
  ParamSpec,
22
21
  TypeVar,
23
- Union,
24
22
  cast,
25
23
  )
26
24
 
@@ -42,7 +40,7 @@ class LangChainPendingDeprecationWarning(PendingDeprecationWarning):
42
40
 
43
41
 
44
42
  # Last Any should be FieldInfoV1 but this leads to circular imports
45
- T = TypeVar("T", bound=Union[type, Callable[..., Any], Any])
43
+ T = TypeVar("T", bound=type | Callable[..., Any] | Any)
46
44
 
47
45
 
48
46
  def _validate_deprecation_params(
@@ -84,62 +82,59 @@ def deprecated(
84
82
  """Decorator to mark a function, a class, or a property as deprecated.
85
83
 
86
84
  When deprecating a classmethod, a staticmethod, or a property, the
87
- ``@deprecated`` decorator should go *under* ``@classmethod`` and
88
- ``@staticmethod`` (i.e., `deprecated` should directly decorate the
89
- underlying callable), but *over* ``@property``.
85
+ `@deprecated` decorator should go *under* `@classmethod` and
86
+ `@staticmethod` (i.e., `deprecated` should directly decorate the
87
+ underlying callable), but *over* `@property`.
90
88
 
91
- When deprecating a class ``C`` intended to be used as a base class in a
92
- multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method
93
- (if ``C`` instead inherited its ``__init__`` from its own base class, then
94
- ``@deprecated`` would mess up ``__init__`` inheritance when installing its
95
- own (deprecation-emitting) ``C.__init__``).
89
+ When deprecating a class `C` intended to be used as a base class in a
90
+ multiple inheritance hierarchy, `C` *must* define an `__init__` method
91
+ (if `C` instead inherited its `__init__` from its own base class, then
92
+ `@deprecated` would mess up `__init__` inheritance when installing its
93
+ own (deprecation-emitting) `C.__init__`).
96
94
 
97
95
  Parameters are the same as for `warn_deprecated`, except that *obj_type*
98
96
  defaults to 'class' if decorating a class, 'attribute' if decorating a
99
97
  property, and 'function' otherwise.
100
98
 
101
99
  Args:
102
- since : str
100
+ since:
103
101
  The release at which this API became deprecated.
104
- message : str, optional
102
+ message:
105
103
  Override the default deprecation message. The %(since)s,
106
104
  %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s,
107
105
  and %(removal)s format specifiers will be replaced by the
108
106
  values of the respective arguments passed to this function.
109
- name : str, optional
107
+ name:
110
108
  The name of the deprecated object.
111
- alternative : str, optional
109
+ alternative:
112
110
  An alternative API that the user may use in place of the
113
111
  deprecated API. The deprecation warning will tell the user
114
112
  about this alternative if provided.
115
- alternative_import: str, optional
113
+ alternative_import:
116
114
  An alternative import that the user may use instead.
117
- pending : bool, optional
118
- If True, uses a PendingDeprecationWarning instead of a
115
+ pending:
116
+ If `True`, uses a `PendingDeprecationWarning` instead of a
119
117
  DeprecationWarning. Cannot be used together with removal.
120
- obj_type : str, optional
118
+ obj_type:
121
119
  The object type being deprecated.
122
- addendum : str, optional
120
+ addendum:
123
121
  Additional text appended directly to the final message.
124
- removal : str, optional
122
+ removal:
125
123
  The expected removal version. With the default (an empty
126
124
  string), a removal version is automatically computed from
127
125
  since. Set to other Falsy values to not schedule a removal
128
126
  date. Cannot be used together with pending.
129
- package: str, optional
127
+ package:
130
128
  The package of the deprecated object.
131
129
 
132
130
  Returns:
133
131
  A decorator to mark a function or class as deprecated.
134
132
 
135
- Examples:
136
-
137
- .. code-block:: python
138
-
139
- @deprecated("1.4.0")
140
- def the_function_to_deprecate():
141
- pass
142
-
133
+ ```python
134
+ @deprecated("1.4.0")
135
+ def the_function_to_deprecate():
136
+ pass
137
+ ```
143
138
  """
144
139
  _validate_deprecation_params(
145
140
  removal, alternative, alternative_import, pending=pending
@@ -276,7 +271,7 @@ def deprecated(
276
271
  if not _obj_type:
277
272
  _obj_type = "attribute"
278
273
  wrapped = None
279
- _name = _name or cast("Union[type, Callable]", obj.fget).__qualname__
274
+ _name = _name or cast("type | Callable", obj.fget).__qualname__
280
275
  old_doc = obj.__doc__
281
276
 
282
277
  class _DeprecatedProperty(property):
@@ -284,19 +279,17 @@ def deprecated(
284
279
 
285
280
  def __init__(
286
281
  self,
287
- fget: Union[Callable[[Any], Any], None] = None,
288
- fset: Union[Callable[[Any, Any], None], None] = None,
289
- fdel: Union[Callable[[Any], None], None] = None,
290
- doc: Union[str, None] = None,
282
+ fget: Callable[[Any], Any] | None = None,
283
+ fset: Callable[[Any, Any], None] | None = None,
284
+ fdel: Callable[[Any], None] | None = None,
285
+ doc: str | None = None,
291
286
  ) -> None:
292
287
  super().__init__(fget, fset, fdel, doc)
293
288
  self.__orig_fget = fget
294
289
  self.__orig_fset = fset
295
290
  self.__orig_fdel = fdel
296
291
 
297
- def __get__(
298
- self, instance: Any, owner: Union[type, None] = None
299
- ) -> Any:
292
+ def __get__(self, instance: Any, owner: type | None = None) -> Any:
300
293
  if instance is not None or owner is not None:
301
294
  emit_warning()
302
295
  if self.fget is None:
@@ -315,7 +308,7 @@ def deprecated(
315
308
  if self.fdel is not None:
316
309
  self.fdel(instance)
317
310
 
318
- def __set_name__(self, owner: Union[type, None], set_name: str) -> None:
311
+ def __set_name__(self, owner: type | None, set_name: str) -> None:
319
312
  nonlocal _name
320
313
  if _name == "<lambda>":
321
314
  _name = set_name
@@ -330,7 +323,7 @@ def deprecated(
330
323
  )
331
324
 
332
325
  else:
333
- _name = _name or cast("Union[type, Callable]", obj).__qualname__
326
+ _name = _name or cast("type | Callable", obj).__qualname__
334
327
  if not _obj_type:
335
328
  # edge case: when a function is within another function
336
329
  # within a test, this will call it a "method" not a "function"
@@ -363,24 +356,20 @@ def deprecated(
363
356
  _alternative
364
357
  and _alternative.rsplit(".", maxsplit=1)[-1].lower()
365
358
  == _alternative.rsplit(".", maxsplit=1)[-1]
366
- ):
367
- _alternative = f":meth:`~{_alternative}`"
368
- elif _alternative:
369
- _alternative = f":class:`~{_alternative}`"
359
+ ) or _alternative:
360
+ _alternative = f"`{_alternative}`"
370
361
 
371
362
  if (
372
363
  _alternative_import
373
364
  and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
374
365
  == _alternative_import.rsplit(".", maxsplit=1)[-1]
375
- ):
376
- _alternative_import = f":meth:`~{_alternative_import}`"
377
- elif _alternative_import:
378
- _alternative_import = f":class:`~{_alternative_import}`"
366
+ ) or _alternative_import:
367
+ _alternative_import = f"`{_alternative_import}`"
379
368
 
380
369
  components = [
381
370
  _message,
382
371
  f"Use {_alternative} instead." if _alternative else "",
383
- f"Use ``{_alternative_import}`` instead." if _alternative_import else "",
372
+ f"Use `{_alternative_import}` instead." if _alternative_import else "",
384
373
  _addendum,
385
374
  ]
386
375
  details = " ".join([component.strip() for component in components if component])
@@ -395,7 +384,7 @@ def deprecated(
395
384
  else:
396
385
  removal_str = ""
397
386
  new_doc = f"""\
398
- .. deprecated:: {since} {details} {removal_str}
387
+ !!! deprecated "{since} {details} {removal_str}"
399
388
 
400
389
  {old_doc}\
401
390
  """
@@ -448,7 +437,7 @@ def warn_deprecated(
448
437
  alternative_import:
449
438
  An alternative import that the user may use instead.
450
439
  pending:
451
- If True, uses a PendingDeprecationWarning instead of a
440
+ If `True`, uses a `PendingDeprecationWarning` instead of a
452
441
  DeprecationWarning. Cannot be used together with removal.
453
442
  obj_type:
454
443
  The object type being deprecated.
@@ -544,9 +533,9 @@ def rename_parameter(
544
533
  ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
545
534
  """Decorator indicating that parameter *old* of *func* is renamed to *new*.
546
535
 
547
- The actual implementation of *func* should use *new*, not *old*. If *old*
548
- is passed to *func*, a DeprecationWarning is emitted, and its value is
549
- used, even if *new* is also passed by keyword.
536
+ The actual implementation of *func* should use *new*, not *old*. If *old* is passed
537
+ to *func*, a DeprecationWarning is emitted, and its value is used, even if *new* is
538
+ also passed by keyword.
550
539
 
551
540
  Args:
552
541
  since: The version in which the parameter was renamed.
@@ -558,12 +547,10 @@ def rename_parameter(
558
547
  A decorator indicating that a parameter was renamed.
559
548
 
560
549
  Example:
561
-
562
- .. code-block:: python
563
-
564
- @_api.rename_parameter("3.1", "bad_name", "good_name")
565
- def func(good_name): ...
566
-
550
+ ```python
551
+ @_api.rename_parameter("3.1", "bad_name", "good_name")
552
+ def func(good_name): ...
553
+ ```
567
554
  """
568
555
 
569
556
  def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
@@ -1,6 +1,5 @@
1
1
  import os
2
2
  from pathlib import Path
3
- from typing import Optional, Union
4
3
 
5
4
  HERE = Path(__file__).parent
6
5
 
@@ -9,9 +8,7 @@ PACKAGE_DIR = HERE.parent
9
8
  SEPARATOR = os.sep
10
9
 
11
10
 
12
- def get_relative_path(
13
- file: Union[Path, str], *, relative_to: Path = PACKAGE_DIR
14
- ) -> str:
11
+ def get_relative_path(file: Path | str, *, relative_to: Path = PACKAGE_DIR) -> str:
15
12
  """Get the path of the file as a relative path to the package directory.
16
13
 
17
14
  Args:
@@ -27,9 +24,9 @@ def get_relative_path(
27
24
 
28
25
 
29
26
  def as_import_path(
30
- file: Union[Path, str],
27
+ file: Path | str,
31
28
  *,
32
- suffix: Optional[str] = None,
29
+ suffix: str | None = None,
33
30
  relative_to: Path = PACKAGE_DIR,
34
31
  ) -> str:
35
32
  """Path of the file as a LangChain import exclude langchain top namespace.
@@ -1,11 +1,10 @@
1
1
  from importlib import import_module
2
- from typing import Union
3
2
 
4
3
 
5
4
  def import_attr(
6
5
  attr_name: str,
7
- module_name: Union[str, None],
8
- package: Union[str, None],
6
+ module_name: str | None,
7
+ package: str | None,
9
8
  ) -> object:
10
9
  """Import an attribute from a module located in a package.
11
10
 
@@ -14,7 +13,7 @@ def import_attr(
14
13
 
15
14
  Args:
16
15
  attr_name: The name of the attribute to import.
17
- module_name: The name of the module to import from. If None, the attribute
16
+ module_name: The name of the module to import from. If `None`, the attribute
18
17
  is imported from the package itself.
19
18
  package: The name of the package where the module is located.
20
19
 
langchain_core/agents.py CHANGED
@@ -1,24 +1,24 @@
1
1
  """Schema definitions for representing agent actions, observations, and return values.
2
2
 
3
- **ATTENTION** The schema definitions are provided for backwards compatibility.
3
+ !!! warning
4
+ The schema definitions are provided for backwards compatibility.
4
5
 
5
- New agents should be built using the langgraph library
6
- (https://github.com/langchain-ai/langgraph)), which provides a simpler
7
- and more flexible way to define agents.
6
+ !!! warning
7
+ New agents should be built using the
8
+ [`langchain` library](https://pypi.org/project/langchain/), which provides a
9
+ simpler and more flexible way to define agents.
8
10
 
9
- Please see the migration guide for information on how to migrate existing
10
- agents to modern langgraph agents:
11
- https://python.langchain.com/docs/how_to/migrate_agent/
11
+ See docs on [building agents](https://docs.langchain.com/oss/python/langchain/agents).
12
12
 
13
13
  Agents use language models to choose a sequence of actions to take.
14
14
 
15
15
  A basic agent works in the following manner:
16
16
 
17
17
  1. Given a prompt an agent uses an LLM to request an action to take
18
- (e.g., a tool to run).
18
+ (e.g., a tool to run).
19
19
  2. The agent executes the action (e.g., runs the tool), and receives an observation.
20
20
  3. The agent returns the observation to the LLM, which can then be used to generate
21
- the next action.
21
+ the next action.
22
22
  4. When the agent reaches a stopping condition, it returns a final return value.
23
23
 
24
24
  The schemas for the agents themselves are defined in langchain.agents.agent.
@@ -28,7 +28,7 @@ from __future__ import annotations
28
28
 
29
29
  import json
30
30
  from collections.abc import Sequence
31
- from typing import Any, Literal, Union
31
+ from typing import Any, Literal
32
32
 
33
33
  from langchain_core.load.serializable import Serializable
34
34
  from langchain_core.messages import (
@@ -48,46 +48,46 @@ class AgentAction(Serializable):
48
48
 
49
49
  tool: str
50
50
  """The name of the Tool to execute."""
51
- tool_input: Union[str, dict]
51
+ tool_input: str | dict
52
52
  """The input to pass in to the Tool."""
53
53
  log: str
54
54
  """Additional information to log about the action.
55
- This log can be used in a few ways. First, it can be used to audit
56
- what exactly the LLM predicted to lead to this (tool, tool_input).
57
- Second, it can be used in future iterations to show the LLMs prior
58
- thoughts. This is useful when (tool, tool_input) does not contain
59
- full information about the LLM prediction (for example, any `thought`
60
- before the tool/tool_input)."""
55
+
56
+ This log can be used in a few ways. First, it can be used to audit what exactly the
57
+ LLM predicted to lead to this `(tool, tool_input)`.
58
+
59
+ Second, it can be used in future iterations to show the LLMs prior thoughts. This is
60
+ useful when `(tool, tool_input)` does not contain full information about the LLM
61
+ prediction (for example, any `thought` before the tool/tool_input).
62
+ """
61
63
  type: Literal["AgentAction"] = "AgentAction"
62
64
 
63
65
  # Override init to support instantiation by position for backward compat.
64
- def __init__(
65
- self, tool: str, tool_input: Union[str, dict], log: str, **kwargs: Any
66
- ):
67
- """Create an AgentAction.
66
+ def __init__(self, tool: str, tool_input: str | dict, log: str, **kwargs: Any):
67
+ """Create an `AgentAction`.
68
68
 
69
69
  Args:
70
70
  tool: The name of the tool to execute.
71
- tool_input: The input to pass in to the Tool.
71
+ tool_input: The input to pass in to the `Tool`.
72
72
  log: Additional information to log about the action.
73
73
  """
74
74
  super().__init__(tool=tool, tool_input=tool_input, log=log, **kwargs)
75
75
 
76
76
  @classmethod
77
77
  def is_lc_serializable(cls) -> bool:
78
- """AgentAction is serializable.
78
+ """`AgentAction` is serializable.
79
79
 
80
80
  Returns:
81
- True
81
+ `True`
82
82
  """
83
83
  return True
84
84
 
85
85
  @classmethod
86
86
  def get_lc_namespace(cls) -> list[str]:
87
- """Get the namespace of the langchain object.
87
+ """Get the namespace of the LangChain object.
88
88
 
89
89
  Returns:
90
- ``["langchain", "schema", "agent"]``
90
+ `["langchain", "schema", "agent"]`
91
91
  """
92
92
  return ["langchain", "schema", "agent"]
93
93
 
@@ -100,19 +100,23 @@ class AgentAction(Serializable):
100
100
  class AgentActionMessageLog(AgentAction):
101
101
  """Representation of an action to be executed by an agent.
102
102
 
103
- This is similar to AgentAction, but includes a message log consisting of
104
- chat messages. This is useful when working with ChatModels, and is used
105
- to reconstruct conversation history from the agent's perspective.
103
+ This is similar to `AgentAction`, but includes a message log consisting of
104
+ chat messages.
105
+
106
+ This is useful when working with `ChatModels`, and is used to reconstruct
107
+ conversation history from the agent's perspective.
106
108
  """
107
109
 
108
110
  message_log: Sequence[BaseMessage]
109
- """Similar to log, this can be used to pass along extra
110
- information about what exact messages were predicted by the LLM
111
- before parsing out the (tool, tool_input). This is again useful
112
- if (tool, tool_input) cannot be used to fully recreate the LLM
113
- prediction, and you need that LLM prediction (for future agent iteration).
111
+ """Similar to log, this can be used to pass along extra information about what exact
112
+ messages were predicted by the LLM before parsing out the `(tool, tool_input)`.
113
+
114
+ This is again useful if `(tool, tool_input)` cannot be used to fully recreate the
115
+ LLM prediction, and you need that LLM prediction (for future agent iteration).
116
+
114
117
  Compared to `log`, this is useful when the underlying LLM is a
115
- ChatModel (and therefore returns messages rather than a string)."""
118
+ chat model (and therefore returns messages rather than a string).
119
+ """
116
120
  # Ignoring type because we're overriding the type from AgentAction.
117
121
  # And this is the correct thing to do in this case.
118
122
  # The type literal is used for serialization purposes.
@@ -120,12 +124,12 @@ class AgentActionMessageLog(AgentAction):
120
124
 
121
125
 
122
126
  class AgentStep(Serializable):
123
- """Result of running an AgentAction."""
127
+ """Result of running an `AgentAction`."""
124
128
 
125
129
  action: AgentAction
126
- """The AgentAction that was executed."""
130
+ """The `AgentAction` that was executed."""
127
131
  observation: Any
128
- """The result of the AgentAction."""
132
+ """The result of the `AgentAction`."""
129
133
 
130
134
  @property
131
135
  def messages(self) -> Sequence[BaseMessage]:
@@ -134,19 +138,22 @@ class AgentStep(Serializable):
134
138
 
135
139
 
136
140
  class AgentFinish(Serializable):
137
- """Final return value of an ActionAgent.
141
+ """Final return value of an `ActionAgent`.
138
142
 
139
- Agents return an AgentFinish when they have reached a stopping condition.
143
+ Agents return an `AgentFinish` when they have reached a stopping condition.
140
144
  """
141
145
 
142
146
  return_values: dict
143
147
  """Dictionary of return values."""
144
148
  log: str
145
149
  """Additional information to log about the return value.
150
+
146
151
  This is used to pass along the full LLM prediction, not just the parsed out
147
- return value. For example, if the full LLM prediction was
148
- `Final Answer: 2` you may want to just return `2` as a return value, but pass
149
- along the full string as a `log` (for debugging or observability purposes).
152
+ return value.
153
+
154
+ For example, if the full LLM prediction was `Final Answer: 2` you may want to just
155
+ return `2` as a return value, but pass along the full string as a `log` (for
156
+ debugging or observability purposes).
150
157
  """
151
158
  type: Literal["AgentFinish"] = "AgentFinish"
152
159
 
@@ -156,15 +163,15 @@ class AgentFinish(Serializable):
156
163
 
157
164
  @classmethod
158
165
  def is_lc_serializable(cls) -> bool:
159
- """Return True as this class is serializable."""
166
+ """Return `True` as this class is serializable."""
160
167
  return True
161
168
 
162
169
  @classmethod
163
170
  def get_lc_namespace(cls) -> list[str]:
164
- """Get the namespace of the langchain object.
171
+ """Get the namespace of the LangChain object.
165
172
 
166
173
  Returns:
167
- ``["langchain", "schema", "agent"]``
174
+ `["langchain", "schema", "agent"]`
168
175
  """
169
176
  return ["langchain", "schema", "agent"]
170
177
 
@@ -204,7 +211,7 @@ def _convert_agent_observation_to_messages(
204
211
  observation: Observation to convert to a message.
205
212
 
206
213
  Returns:
207
- AIMessage that corresponds to the original tool invocation.
214
+ `AIMessage` that corresponds to the original tool invocation.
208
215
  """
209
216
  if isinstance(agent_action, AgentActionMessageLog):
210
217
  return [_create_function_message(agent_action, observation)]
@@ -227,7 +234,7 @@ def _create_function_message(
227
234
  observation: the result of the tool invocation.
228
235
 
229
236
  Returns:
230
- FunctionMessage that corresponds to the original tool invocation.
237
+ `FunctionMessage` that corresponds to the original tool invocation.
231
238
  """
232
239
  if not isinstance(observation, str):
233
240
  try: