langchain-core 1.0.0a5__py3-none-any.whl → 1.0.3__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 +20 -22
  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 +436 -513
  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 +98 -90
  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 +1 -1
  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 +53 -162
  36. langchain_core/language_models/chat_models.py +298 -387
  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 +125 -235
  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 +58 -52
  47. langchain_core/messages/block_translators/__init__.py +27 -17
  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 +505 -20
  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 +337 -328
  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 +474 -504
  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 +16 -21
  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 +10 -11
  78. langchain_core/outputs/llm_result.py +10 -10
  79. langchain_core/prompt_values.py +11 -17
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +48 -56
  82. langchain_core/prompts/chat.py +275 -325
  83. langchain_core/prompts/dict.py +5 -5
  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 +3 -3
  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 +1478 -1630
  95. langchain_core/runnables/branch.py +53 -57
  96. langchain_core/runnables/config.py +72 -89
  97. langchain_core/runnables/configurable.py +120 -137
  98. langchain_core/runnables/fallbacks.py +83 -79
  99. langchain_core/runnables/graph.py +91 -97
  100. langchain_core/runnables/graph_ascii.py +27 -28
  101. langchain_core/runnables/graph_mermaid.py +38 -50
  102. langchain_core/runnables/graph_png.py +15 -16
  103. langchain_core/runnables/history.py +135 -148
  104. langchain_core/runnables/passthrough.py +124 -150
  105. langchain_core/runnables/retry.py +46 -51
  106. langchain_core/runnables/router.py +25 -30
  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 +27 -29
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +285 -229
  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 +89 -186
  137. langchain_core/utils/html.py +7 -8
  138. langchain_core/utils/input.py +6 -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 +33 -35
  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.3.dist-info/METADATA +69 -0
  153. langchain_core-1.0.3.dist-info/RECORD +172 -0
  154. {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.3.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.0a5.dist-info/METADATA +0 -77
  164. langchain_core-1.0.0a5.dist-info/RECORD +0 -181
  165. langchain_core-1.0.0a5.dist-info/entry_points.txt +0 -4
@@ -17,7 +17,7 @@ def default(obj: Any) -> Any:
17
17
  obj: The object to serialize to json if it is a Serializable object.
18
18
 
19
19
  Returns:
20
- A json serializable object or a SerializedNotImplemented object.
20
+ A JSON serializable object or a SerializedNotImplemented object.
21
21
  """
22
22
  if isinstance(obj, Serializable):
23
23
  return obj.to_json()
@@ -38,17 +38,16 @@ def _dump_pydantic_models(obj: Any) -> Any:
38
38
 
39
39
 
40
40
  def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
41
- """Return a json string representation of an object.
41
+ """Return a JSON string representation of an object.
42
42
 
43
43
  Args:
44
44
  obj: The object to dump.
45
- pretty: Whether to pretty print the json. If true, the json will be
46
- indented with 2 spaces (if no indent is provided as part of kwargs).
47
- Default is False.
48
- kwargs: Additional arguments to pass to json.dumps
45
+ pretty: Whether to pretty print the json. If `True`, the json will be
46
+ indented with 2 spaces (if no indent is provided as part of `kwargs`).
47
+ **kwargs: Additional arguments to pass to `json.dumps`
49
48
 
50
49
  Returns:
51
- A json string representation of the object.
50
+ A JSON string representation of the object.
52
51
 
53
52
  Raises:
54
53
  ValueError: If `default` is passed as a kwarg.
@@ -72,14 +71,12 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
72
71
  def dumpd(obj: Any) -> Any:
73
72
  """Return a dict representation of an object.
74
73
 
75
- .. note::
76
- Unfortunately this function is not as efficient as it could be because it first
77
- dumps the object to a json string and then loads it back into a dictionary.
78
-
79
74
  Args:
80
75
  obj: The object to dump.
81
76
 
82
77
  Returns:
83
- dictionary that can be serialized to json using json.dumps
78
+ Dictionary that can be serialized to json using `json.dumps`.
84
79
  """
80
+ # Unfortunately this function is not as efficient as it could be because it first
81
+ # dumps the object to a json string and then loads it back into a dictionary.
85
82
  return json.loads(dumps(obj))
@@ -3,7 +3,7 @@
3
3
  import importlib
4
4
  import json
5
5
  import os
6
- from typing import Any, Optional
6
+ from typing import Any
7
7
 
8
8
  from langchain_core._api import beta
9
9
  from langchain_core.load.mapping import (
@@ -50,12 +50,11 @@ class Reviver:
50
50
 
51
51
  def __init__(
52
52
  self,
53
- secrets_map: Optional[dict[str, str]] = None,
54
- valid_namespaces: Optional[list[str]] = None,
53
+ secrets_map: dict[str, str] | None = None,
54
+ valid_namespaces: list[str] | None = None,
55
55
  secrets_from_env: bool = True, # noqa: FBT001,FBT002
56
- additional_import_mappings: Optional[
57
- dict[tuple[str, ...], tuple[str, ...]]
58
- ] = None,
56
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]]
57
+ | None = None,
59
58
  *,
60
59
  ignore_unserializable_fields: bool = False,
61
60
  ) -> None:
@@ -64,16 +63,13 @@ class Reviver:
64
63
  Args:
65
64
  secrets_map: A map of secrets to load. If a secret is not found in
66
65
  the map, it will be loaded from the environment if `secrets_from_env`
67
- is True. Defaults to None.
66
+ is True.
68
67
  valid_namespaces: A list of additional namespaces (modules)
69
- to allow to be deserialized. Defaults to None.
68
+ to allow to be deserialized.
70
69
  secrets_from_env: Whether to load secrets from the environment.
71
- Defaults to True.
72
70
  additional_import_mappings: A dictionary of additional namespace mappings
73
71
  You can use this to override default mappings or add new mappings.
74
- Defaults to None.
75
72
  ignore_unserializable_fields: Whether to ignore unserializable fields.
76
- Defaults to False.
77
73
  """
78
74
  self.secrets_from_env = secrets_from_env
79
75
  self.secrets_map = secrets_map or {}
@@ -108,7 +104,7 @@ class Reviver:
108
104
  ValueError: If trying to deserialize something that cannot
109
105
  be deserialized in the current version of langchain-core.
110
106
  NotImplementedError: If the object is not implemented and
111
- ``ignore_unserializable_fields`` is False.
107
+ `ignore_unserializable_fields` is False.
112
108
  """
113
109
  if (
114
110
  value.get("lc") == 1
@@ -187,10 +183,10 @@ class Reviver:
187
183
  def loads(
188
184
  text: str,
189
185
  *,
190
- secrets_map: Optional[dict[str, str]] = None,
191
- valid_namespaces: Optional[list[str]] = None,
186
+ secrets_map: dict[str, str] | None = None,
187
+ valid_namespaces: list[str] | None = None,
192
188
  secrets_from_env: bool = True,
193
- additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
189
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
194
190
  ignore_unserializable_fields: bool = False,
195
191
  ) -> Any:
196
192
  """Revive a LangChain class from a JSON string.
@@ -201,16 +197,13 @@ def loads(
201
197
  text: The string to load.
202
198
  secrets_map: A map of secrets to load. If a secret is not found in
203
199
  the map, it will be loaded from the environment if `secrets_from_env`
204
- is True. Defaults to None.
200
+ is True.
205
201
  valid_namespaces: A list of additional namespaces (modules)
206
- to allow to be deserialized. Defaults to None.
202
+ to allow to be deserialized.
207
203
  secrets_from_env: Whether to load secrets from the environment.
208
- Defaults to True.
209
204
  additional_import_mappings: A dictionary of additional namespace mappings
210
205
  You can use this to override default mappings or add new mappings.
211
- Defaults to None.
212
206
  ignore_unserializable_fields: Whether to ignore unserializable fields.
213
- Defaults to False.
214
207
 
215
208
  Returns:
216
209
  Revived LangChain objects.
@@ -231,10 +224,10 @@ def loads(
231
224
  def load(
232
225
  obj: Any,
233
226
  *,
234
- secrets_map: Optional[dict[str, str]] = None,
235
- valid_namespaces: Optional[list[str]] = None,
227
+ secrets_map: dict[str, str] | None = None,
228
+ valid_namespaces: list[str] | None = None,
236
229
  secrets_from_env: bool = True,
237
- additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
230
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
238
231
  ignore_unserializable_fields: bool = False,
239
232
  ) -> Any:
240
233
  """Revive a LangChain class from a JSON object.
@@ -246,16 +239,13 @@ def load(
246
239
  obj: The object to load.
247
240
  secrets_map: A map of secrets to load. If a secret is not found in
248
241
  the map, it will be loaded from the environment if `secrets_from_env`
249
- is True. Defaults to None.
242
+ is True.
250
243
  valid_namespaces: A list of additional namespaces (modules)
251
- to allow to be deserialized. Defaults to None.
244
+ to allow to be deserialized.
252
245
  secrets_from_env: Whether to load secrets from the environment.
253
- Defaults to True.
254
246
  additional_import_mappings: A dictionary of additional namespace mappings
255
247
  You can use this to override default mappings or add new mappings.
256
- Defaults to None.
257
248
  ignore_unserializable_fields: Whether to ignore unserializable fields.
258
- Defaults to False.
259
249
 
260
250
  Returns:
261
251
  Revived LangChain objects.
@@ -413,11 +413,10 @@ SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
413
413
  "few_shot_with_templates",
414
414
  "FewShotPromptWithTemplates",
415
415
  ),
416
- ("langchain", "prompts", "pipeline", "PipelinePromptTemplate"): (
416
+ ("langchain", "prompts", "pipeline"): (
417
417
  "langchain_core",
418
418
  "prompts",
419
419
  "pipeline",
420
- "PipelinePromptTemplate",
421
420
  ),
422
421
  ("langchain", "prompts", "base", "StringPromptTemplate"): (
423
422
  "langchain_core",
@@ -846,11 +845,10 @@ OLD_CORE_NAMESPACES_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
846
845
  "few_shot_with_templates",
847
846
  "FewShotPromptWithTemplates",
848
847
  ),
849
- ("langchain_core", "prompts", "pipeline", "PipelinePromptTemplate"): (
848
+ ("langchain_core", "prompts", "pipeline"): (
850
849
  "langchain_core",
851
850
  "prompts",
852
851
  "pipeline",
853
- "PipelinePromptTemplate",
854
852
  ),
855
853
  ("langchain_core", "prompts", "string", "StringPromptTemplate"): (
856
854
  "langchain_core",
@@ -6,9 +6,7 @@ from abc import ABC
6
6
  from typing import (
7
7
  Any,
8
8
  Literal,
9
- Optional,
10
9
  TypedDict,
11
- Union,
12
10
  cast,
13
11
  )
14
12
 
@@ -27,16 +25,16 @@ class BaseSerialized(TypedDict):
27
25
  id: list[str]
28
26
  """The unique identifier of the object."""
29
27
  name: NotRequired[str]
30
- """The name of the object. Optional."""
28
+ """The name of the object."""
31
29
  graph: NotRequired[dict[str, Any]]
32
- """The graph of the object. Optional."""
30
+ """The graph of the object."""
33
31
 
34
32
 
35
33
  class SerializedConstructor(BaseSerialized):
36
34
  """Serialized constructor."""
37
35
 
38
36
  type: Literal["constructor"]
39
- """The type of the object. Must be ``'constructor'``."""
37
+ """The type of the object. Must be `'constructor'`."""
40
38
  kwargs: dict[str, Any]
41
39
  """The constructor arguments."""
42
40
 
@@ -45,16 +43,16 @@ class SerializedSecret(BaseSerialized):
45
43
  """Serialized secret."""
46
44
 
47
45
  type: Literal["secret"]
48
- """The type of the object. Must be ``'secret'``."""
46
+ """The type of the object. Must be `'secret'`."""
49
47
 
50
48
 
51
49
  class SerializedNotImplemented(BaseSerialized):
52
50
  """Serialized not implemented."""
53
51
 
54
52
  type: Literal["not_implemented"]
55
- """The type of the object. Must be ``'not_implemented'``."""
56
- repr: Optional[str]
57
- """The representation of the object. Optional."""
53
+ """The type of the object. Must be `'not_implemented'`."""
54
+ repr: str | None
55
+ """The representation of the object."""
58
56
 
59
57
 
60
58
  def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
@@ -63,7 +61,7 @@ def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
63
61
  Args:
64
62
  value: The value.
65
63
  key: The key.
66
- model: The pydantic model.
64
+ model: The Pydantic model.
67
65
 
68
66
  Returns:
69
67
  Whether the value is different from the default.
@@ -94,19 +92,22 @@ class Serializable(BaseModel, ABC):
94
92
 
95
93
  It relies on the following methods and properties:
96
94
 
97
- - ``is_lc_serializable``: Is this class serializable?
98
- By design, even if a class inherits from Serializable, it is not serializable by
99
- default. This is to prevent accidental serialization of objects that should not
100
- be serialized.
101
- - ``get_lc_namespace``: Get the namespace of the langchain object.
102
- During deserialization, this namespace is used to identify
103
- the correct class to instantiate.
104
- Please see the ``Reviver`` class in ``langchain_core.load.load`` for more details.
105
- During deserialization an additional mapping is handle
106
- classes that have moved or been renamed across package versions.
107
- - ``lc_secrets``: A map of constructor argument names to secret ids.
108
- - ``lc_attributes``: List of additional attribute names that should be included
109
- as part of the serialized representation.
95
+ - `is_lc_serializable`: Is this class serializable?
96
+ By design, even if a class inherits from `Serializable`, it is not serializable
97
+ by default. This is to prevent accidental serialization of objects that should
98
+ not be serialized.
99
+ - `get_lc_namespace`: Get the namespace of the LangChain object.
100
+
101
+ During deserialization, this namespace is used to identify
102
+ the correct class to instantiate.
103
+
104
+ Please see the `Reviver` class in `langchain_core.load.load` for more details.
105
+ During deserialization an additional mapping is handle classes that have moved
106
+ or been renamed across package versions.
107
+
108
+ - `lc_secrets`: A map of constructor argument names to secret ids.
109
+ - `lc_attributes`: List of additional attribute names that should be included
110
+ as part of the serialized representation.
110
111
  """
111
112
 
112
113
  # Remove default BaseModel init docstring.
@@ -118,24 +119,24 @@ class Serializable(BaseModel, ABC):
118
119
  def is_lc_serializable(cls) -> bool:
119
120
  """Is this class serializable?
120
121
 
121
- By design, even if a class inherits from Serializable, it is not serializable by
122
- default. This is to prevent accidental serialization of objects that should not
123
- be serialized.
122
+ By design, even if a class inherits from `Serializable`, it is not serializable
123
+ by default. This is to prevent accidental serialization of objects that should
124
+ not be serialized.
124
125
 
125
126
  Returns:
126
- Whether the class is serializable. Default is False.
127
+ Whether the class is serializable. Default is `False`.
127
128
  """
128
129
  return False
129
130
 
130
131
  @classmethod
131
132
  def get_lc_namespace(cls) -> list[str]:
132
- """Get the namespace of the langchain object.
133
+ """Get the namespace of the LangChain object.
133
134
 
134
135
  For example, if the class is `langchain.llms.openai.OpenAI`, then the
135
- namespace is ["langchain", "llms", "openai"]
136
+ namespace is `["langchain", "llms", "openai"]`
136
137
 
137
138
  Returns:
138
- The namespace as a list of strings.
139
+ The namespace.
139
140
  """
140
141
  return cls.__module__.split(".")
141
142
 
@@ -143,8 +144,7 @@ class Serializable(BaseModel, ABC):
143
144
  def lc_secrets(self) -> dict[str, str]:
144
145
  """A map of constructor argument names to secret ids.
145
146
 
146
- For example,
147
- {"openai_api_key": "OPENAI_API_KEY"}
147
+ For example, `{"openai_api_key": "OPENAI_API_KEY"}`
148
148
  """
149
149
  return {}
150
150
 
@@ -153,6 +153,7 @@ class Serializable(BaseModel, ABC):
153
153
  """List of attribute names that should be included in the serialized kwargs.
154
154
 
155
155
  These attributes must be accepted by the constructor.
156
+
156
157
  Default is an empty dictionary.
157
158
  """
158
159
  return {}
@@ -163,8 +164,9 @@ class Serializable(BaseModel, ABC):
163
164
 
164
165
  The unique identifier is a list of strings that describes the path
165
166
  to the object.
167
+
166
168
  For example, for the class `langchain.llms.openai.OpenAI`, the id is
167
- ["langchain", "llms", "openai", "OpenAI"].
169
+ `["langchain", "llms", "openai", "OpenAI"]`.
168
170
  """
169
171
  # Pydantic generics change the class name. So we need to do the following
170
172
  if (
@@ -188,14 +190,14 @@ class Serializable(BaseModel, ABC):
188
190
  if (k not in type(self).model_fields or try_neq_default(v, k, self))
189
191
  ]
190
192
 
191
- def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:
193
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
192
194
  """Serialize the object to JSON.
193
195
 
194
196
  Raises:
195
197
  ValueError: If the class has deprecated attributes.
196
198
 
197
199
  Returns:
198
- A json serializable object or a SerializedNotImplemented object.
200
+ A JSON serializable object or a `SerializedNotImplemented` object.
199
201
  """
200
202
  if not self.is_lc_serializable():
201
203
  return self.to_json_not_implemented()
@@ -270,7 +272,7 @@ class Serializable(BaseModel, ABC):
270
272
  """Serialize a "not implemented" object.
271
273
 
272
274
  Returns:
273
- SerializedNotImplemented.
275
+ `SerializedNotImplemented`.
274
276
  """
275
277
  return to_json_not_implemented(self)
276
278
 
@@ -285,8 +287,8 @@ def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
285
287
 
286
288
  Returns:
287
289
  Whether the field is useful. If the field is required, it is useful.
288
- If the field is not required, it is useful if the value is not None.
289
- If the field is not required and the value is None, it is useful if the
290
+ If the field is not required, it is useful if the value is not `None`.
291
+ If the field is not required and the value is `None`, it is useful if the
290
292
  default value is different from the value.
291
293
  """
292
294
  field = type(inst).model_fields.get(key)
@@ -345,10 +347,10 @@ def to_json_not_implemented(obj: object) -> SerializedNotImplemented:
345
347
  """Serialize a "not implemented" object.
346
348
 
347
349
  Args:
348
- obj: object to serialize.
350
+ obj: Object to serialize.
349
351
 
350
352
  Returns:
351
- SerializedNotImplemented
353
+ `SerializedNotImplemented`
352
354
  """
353
355
  id_: list[str] = []
354
356
  try:
@@ -1,19 +1,4 @@
1
- """**Messages** are objects used in prompts and chat conversations.
2
-
3
- **Class hierarchy:**
4
-
5
- .. code-block::
6
-
7
- BaseMessage --> SystemMessage, AIMessage, HumanMessage, ChatMessage, FunctionMessage, ToolMessage
8
- --> BaseMessageChunk --> SystemMessageChunk, AIMessageChunk, HumanMessageChunk, ChatMessageChunk, FunctionMessageChunk, ToolMessageChunk
9
-
10
- **Main helpers:**
11
-
12
- .. code-block::
13
-
14
- ChatPromptTemplate
15
-
16
- """ # noqa: E501
1
+ """**Messages** are objects used in prompts and chat conversations."""
17
2
 
18
3
  from typing import TYPE_CHECKING
19
4
 
@@ -24,6 +9,9 @@ if TYPE_CHECKING:
24
9
  from langchain_core.messages.ai import (
25
10
  AIMessage,
26
11
  AIMessageChunk,
12
+ InputTokenDetails,
13
+ OutputTokenDetails,
14
+ UsageMetadata,
27
15
  )
28
16
  from langchain_core.messages.base import (
29
17
  BaseMessage,
@@ -102,10 +90,12 @@ __all__ = (
102
90
  "HumanMessage",
103
91
  "HumanMessageChunk",
104
92
  "ImageContentBlock",
93
+ "InputTokenDetails",
105
94
  "InvalidToolCall",
106
95
  "MessageLikeRepresentation",
107
96
  "NonStandardAnnotation",
108
97
  "NonStandardContentBlock",
98
+ "OutputTokenDetails",
109
99
  "PlainTextContentBlock",
110
100
  "ReasoningContentBlock",
111
101
  "RemoveMessage",
@@ -119,6 +109,7 @@ __all__ = (
119
109
  "ToolCallChunk",
120
110
  "ToolMessage",
121
111
  "ToolMessageChunk",
112
+ "UsageMetadata",
122
113
  "VideoContentBlock",
123
114
  "_message_from_dict",
124
115
  "convert_to_messages",
@@ -160,6 +151,7 @@ _dynamic_imports = {
160
151
  "HumanMessageChunk": "human",
161
152
  "NonStandardAnnotation": "content",
162
153
  "NonStandardContentBlock": "content",
154
+ "OutputTokenDetails": "ai",
163
155
  "PlainTextContentBlock": "content",
164
156
  "ReasoningContentBlock": "content",
165
157
  "RemoveMessage": "modifier",
@@ -169,12 +161,14 @@ _dynamic_imports = {
169
161
  "SystemMessage": "system",
170
162
  "SystemMessageChunk": "system",
171
163
  "ImageContentBlock": "content",
164
+ "InputTokenDetails": "ai",
172
165
  "InvalidToolCall": "tool",
173
166
  "TextContentBlock": "content",
174
167
  "ToolCall": "tool",
175
168
  "ToolCallChunk": "tool",
176
169
  "ToolMessage": "tool",
177
170
  "ToolMessageChunk": "tool",
171
+ "UsageMetadata": "ai",
178
172
  "VideoContentBlock": "content",
179
173
  "AnyMessage": "utils",
180
174
  "MessageLikeRepresentation": "utils",