langchain-core 0.4.0.dev0__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of langchain-core might be problematic. Click here for more details.

Files changed (172) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +45 -70
  4. langchain_core/_api/deprecation.py +80 -80
  5. langchain_core/_api/path.py +22 -8
  6. langchain_core/_import_utils.py +10 -4
  7. langchain_core/agents.py +25 -21
  8. langchain_core/caches.py +53 -63
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +341 -348
  11. langchain_core/callbacks/file.py +55 -44
  12. langchain_core/callbacks/manager.py +546 -683
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +35 -36
  15. langchain_core/callbacks/usage.py +65 -70
  16. langchain_core/chat_history.py +48 -55
  17. langchain_core/document_loaders/base.py +46 -21
  18. langchain_core/document_loaders/langsmith.py +39 -36
  19. langchain_core/documents/__init__.py +0 -1
  20. langchain_core/documents/base.py +96 -74
  21. langchain_core/documents/compressor.py +12 -9
  22. langchain_core/documents/transformers.py +29 -28
  23. langchain_core/embeddings/fake.py +56 -57
  24. langchain_core/env.py +2 -3
  25. langchain_core/example_selectors/base.py +12 -0
  26. langchain_core/example_selectors/length_based.py +1 -1
  27. langchain_core/example_selectors/semantic_similarity.py +21 -25
  28. langchain_core/exceptions.py +15 -9
  29. langchain_core/globals.py +4 -163
  30. langchain_core/indexing/api.py +132 -125
  31. langchain_core/indexing/base.py +64 -67
  32. langchain_core/indexing/in_memory.py +26 -6
  33. langchain_core/language_models/__init__.py +15 -27
  34. langchain_core/language_models/_utils.py +267 -117
  35. langchain_core/language_models/base.py +92 -177
  36. langchain_core/language_models/chat_models.py +547 -407
  37. langchain_core/language_models/fake.py +11 -11
  38. langchain_core/language_models/fake_chat_models.py +72 -118
  39. langchain_core/language_models/llms.py +168 -242
  40. langchain_core/load/dump.py +8 -11
  41. langchain_core/load/load.py +32 -28
  42. langchain_core/load/mapping.py +2 -4
  43. langchain_core/load/serializable.py +50 -56
  44. langchain_core/messages/__init__.py +36 -51
  45. langchain_core/messages/ai.py +377 -150
  46. langchain_core/messages/base.py +239 -47
  47. langchain_core/messages/block_translators/__init__.py +111 -0
  48. langchain_core/messages/block_translators/anthropic.py +470 -0
  49. langchain_core/messages/block_translators/bedrock.py +94 -0
  50. langchain_core/messages/block_translators/bedrock_converse.py +297 -0
  51. langchain_core/messages/block_translators/google_genai.py +530 -0
  52. langchain_core/messages/block_translators/google_vertexai.py +21 -0
  53. langchain_core/messages/block_translators/groq.py +143 -0
  54. langchain_core/messages/block_translators/langchain_v0.py +301 -0
  55. langchain_core/messages/block_translators/openai.py +1010 -0
  56. langchain_core/messages/chat.py +2 -3
  57. langchain_core/messages/content.py +1423 -0
  58. langchain_core/messages/function.py +7 -7
  59. langchain_core/messages/human.py +44 -38
  60. langchain_core/messages/modifier.py +3 -2
  61. langchain_core/messages/system.py +40 -27
  62. langchain_core/messages/tool.py +160 -58
  63. langchain_core/messages/utils.py +527 -638
  64. langchain_core/output_parsers/__init__.py +1 -14
  65. langchain_core/output_parsers/base.py +68 -104
  66. langchain_core/output_parsers/json.py +13 -17
  67. langchain_core/output_parsers/list.py +11 -33
  68. langchain_core/output_parsers/openai_functions.py +56 -74
  69. langchain_core/output_parsers/openai_tools.py +68 -109
  70. langchain_core/output_parsers/pydantic.py +15 -13
  71. langchain_core/output_parsers/string.py +6 -2
  72. langchain_core/output_parsers/transform.py +17 -60
  73. langchain_core/output_parsers/xml.py +34 -44
  74. langchain_core/outputs/__init__.py +1 -1
  75. langchain_core/outputs/chat_generation.py +26 -11
  76. langchain_core/outputs/chat_result.py +1 -3
  77. langchain_core/outputs/generation.py +17 -6
  78. langchain_core/outputs/llm_result.py +15 -8
  79. langchain_core/prompt_values.py +29 -123
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +48 -63
  82. langchain_core/prompts/chat.py +259 -288
  83. langchain_core/prompts/dict.py +19 -11
  84. langchain_core/prompts/few_shot.py +84 -90
  85. langchain_core/prompts/few_shot_with_templates.py +14 -12
  86. langchain_core/prompts/image.py +19 -14
  87. langchain_core/prompts/loading.py +6 -8
  88. langchain_core/prompts/message.py +7 -8
  89. langchain_core/prompts/prompt.py +42 -43
  90. langchain_core/prompts/string.py +37 -16
  91. langchain_core/prompts/structured.py +43 -46
  92. langchain_core/rate_limiters.py +51 -60
  93. langchain_core/retrievers.py +52 -192
  94. langchain_core/runnables/base.py +1727 -1683
  95. langchain_core/runnables/branch.py +52 -73
  96. langchain_core/runnables/config.py +89 -103
  97. langchain_core/runnables/configurable.py +128 -130
  98. langchain_core/runnables/fallbacks.py +93 -82
  99. langchain_core/runnables/graph.py +127 -127
  100. langchain_core/runnables/graph_ascii.py +63 -41
  101. langchain_core/runnables/graph_mermaid.py +87 -70
  102. langchain_core/runnables/graph_png.py +31 -36
  103. langchain_core/runnables/history.py +145 -161
  104. langchain_core/runnables/passthrough.py +141 -144
  105. langchain_core/runnables/retry.py +84 -68
  106. langchain_core/runnables/router.py +33 -37
  107. langchain_core/runnables/schema.py +79 -72
  108. langchain_core/runnables/utils.py +95 -139
  109. langchain_core/stores.py +85 -131
  110. langchain_core/structured_query.py +11 -15
  111. langchain_core/sys_info.py +31 -32
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +221 -247
  114. langchain_core/tools/convert.py +144 -161
  115. langchain_core/tools/render.py +10 -10
  116. langchain_core/tools/retriever.py +12 -19
  117. langchain_core/tools/simple.py +52 -29
  118. langchain_core/tools/structured.py +56 -60
  119. langchain_core/tracers/__init__.py +1 -9
  120. langchain_core/tracers/_streaming.py +6 -7
  121. langchain_core/tracers/base.py +103 -112
  122. langchain_core/tracers/context.py +29 -48
  123. langchain_core/tracers/core.py +142 -105
  124. langchain_core/tracers/evaluation.py +30 -34
  125. langchain_core/tracers/event_stream.py +162 -117
  126. langchain_core/tracers/langchain.py +34 -36
  127. langchain_core/tracers/log_stream.py +87 -49
  128. langchain_core/tracers/memory_stream.py +3 -3
  129. langchain_core/tracers/root_listeners.py +18 -34
  130. langchain_core/tracers/run_collector.py +8 -20
  131. langchain_core/tracers/schemas.py +0 -125
  132. langchain_core/tracers/stdout.py +3 -3
  133. langchain_core/utils/__init__.py +1 -4
  134. langchain_core/utils/_merge.py +47 -9
  135. langchain_core/utils/aiter.py +70 -66
  136. langchain_core/utils/env.py +12 -9
  137. langchain_core/utils/function_calling.py +139 -206
  138. langchain_core/utils/html.py +7 -8
  139. langchain_core/utils/input.py +6 -6
  140. langchain_core/utils/interactive_env.py +6 -2
  141. langchain_core/utils/iter.py +48 -45
  142. langchain_core/utils/json.py +14 -4
  143. langchain_core/utils/json_schema.py +159 -43
  144. langchain_core/utils/mustache.py +32 -25
  145. langchain_core/utils/pydantic.py +67 -40
  146. langchain_core/utils/strings.py +5 -5
  147. langchain_core/utils/usage.py +1 -1
  148. langchain_core/utils/utils.py +104 -62
  149. langchain_core/vectorstores/base.py +131 -179
  150. langchain_core/vectorstores/in_memory.py +113 -182
  151. langchain_core/vectorstores/utils.py +23 -17
  152. langchain_core/version.py +1 -1
  153. langchain_core-1.0.0.dist-info/METADATA +68 -0
  154. langchain_core-1.0.0.dist-info/RECORD +172 -0
  155. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0.dist-info}/WHEEL +1 -1
  156. langchain_core/beta/__init__.py +0 -1
  157. langchain_core/beta/runnables/__init__.py +0 -1
  158. langchain_core/beta/runnables/context.py +0 -448
  159. langchain_core/memory.py +0 -116
  160. langchain_core/messages/content_blocks.py +0 -1435
  161. langchain_core/prompts/pipeline.py +0 -133
  162. langchain_core/pydantic_v1/__init__.py +0 -30
  163. langchain_core/pydantic_v1/dataclasses.py +0 -23
  164. langchain_core/pydantic_v1/main.py +0 -23
  165. langchain_core/tracers/langchain_v1.py +0 -23
  166. langchain_core/utils/loading.py +0 -31
  167. langchain_core/v1/__init__.py +0 -1
  168. langchain_core/v1/chat_models.py +0 -1047
  169. langchain_core/v1/messages.py +0 -755
  170. langchain_core-0.4.0.dev0.dist-info/METADATA +0 -108
  171. langchain_core-0.4.0.dev0.dist-info/RECORD +0 -177
  172. langchain_core-0.4.0.dev0.dist-info/entry_points.txt +0 -4
@@ -6,6 +6,8 @@ from typing import Any
6
6
  from pydantic import BaseModel
7
7
 
8
8
  from langchain_core.load.serializable import Serializable, to_json_not_implemented
9
+ from langchain_core.messages import AIMessage
10
+ from langchain_core.outputs import ChatGeneration
9
11
 
10
12
 
11
13
  def default(obj: Any) -> Any:
@@ -23,9 +25,6 @@ def default(obj: Any) -> Any:
23
25
 
24
26
 
25
27
  def _dump_pydantic_models(obj: Any) -> Any:
26
- from langchain_core.messages import AIMessage
27
- from langchain_core.outputs import ChatGeneration
28
-
29
28
  if (
30
29
  isinstance(obj, ChatGeneration)
31
30
  and isinstance(obj.message, AIMessage)
@@ -43,10 +42,9 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
43
42
 
44
43
  Args:
45
44
  obj: The object to dump.
46
- pretty: Whether to pretty print the json. If true, the json will be
47
- indented with 2 spaces (if no indent is provided as part of kwargs).
48
- Default is False.
49
- 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`
50
48
 
51
49
  Returns:
52
50
  A json string representation of the object.
@@ -73,10 +71,9 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
73
71
  def dumpd(obj: Any) -> Any:
74
72
  """Return a dict representation of an object.
75
73
 
76
- Note:
77
- Unfortunately this function is not as efficient as it could be
78
- because it first dumps the object to a json string and then loads it
79
- back into a dictionary.
74
+ !!! note
75
+ Unfortunately this function is not as efficient as it could be because it first
76
+ dumps the object to a json string and then loads it back into a dictionary.
80
77
 
81
78
  Args:
82
79
  obj: The object to dump.
@@ -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 {}
@@ -95,7 +91,21 @@ class Reviver:
95
91
  self.ignore_unserializable_fields = ignore_unserializable_fields
96
92
 
97
93
  def __call__(self, value: dict[str, Any]) -> Any:
98
- """Revive the value."""
94
+ """Revive the value.
95
+
96
+ Args:
97
+ value: The value to revive.
98
+
99
+ Returns:
100
+ The revived value.
101
+
102
+ Raises:
103
+ ValueError: If the namespace is invalid.
104
+ ValueError: If trying to deserialize something that cannot
105
+ be deserialized in the current version of langchain-core.
106
+ NotImplementedError: If the object is not implemented and
107
+ `ignore_unserializable_fields` is False.
108
+ """
99
109
  if (
100
110
  value.get("lc") == 1
101
111
  and value.get("type") == "secret"
@@ -173,10 +183,10 @@ class Reviver:
173
183
  def loads(
174
184
  text: str,
175
185
  *,
176
- secrets_map: Optional[dict[str, str]] = None,
177
- valid_namespaces: Optional[list[str]] = None,
186
+ secrets_map: dict[str, str] | None = None,
187
+ valid_namespaces: list[str] | None = None,
178
188
  secrets_from_env: bool = True,
179
- additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
189
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
180
190
  ignore_unserializable_fields: bool = False,
181
191
  ) -> Any:
182
192
  """Revive a LangChain class from a JSON string.
@@ -187,16 +197,13 @@ def loads(
187
197
  text: The string to load.
188
198
  secrets_map: A map of secrets to load. If a secret is not found in
189
199
  the map, it will be loaded from the environment if `secrets_from_env`
190
- is True. Defaults to None.
200
+ is True.
191
201
  valid_namespaces: A list of additional namespaces (modules)
192
- to allow to be deserialized. Defaults to None.
202
+ to allow to be deserialized.
193
203
  secrets_from_env: Whether to load secrets from the environment.
194
- Defaults to True.
195
204
  additional_import_mappings: A dictionary of additional namespace mappings
196
205
  You can use this to override default mappings or add new mappings.
197
- Defaults to None.
198
206
  ignore_unserializable_fields: Whether to ignore unserializable fields.
199
- Defaults to False.
200
207
 
201
208
  Returns:
202
209
  Revived LangChain objects.
@@ -217,10 +224,10 @@ def loads(
217
224
  def load(
218
225
  obj: Any,
219
226
  *,
220
- secrets_map: Optional[dict[str, str]] = None,
221
- valid_namespaces: Optional[list[str]] = None,
227
+ secrets_map: dict[str, str] | None = None,
228
+ valid_namespaces: list[str] | None = None,
222
229
  secrets_from_env: bool = True,
223
- additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
230
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
224
231
  ignore_unserializable_fields: bool = False,
225
232
  ) -> Any:
226
233
  """Revive a LangChain class from a JSON object.
@@ -232,16 +239,13 @@ def load(
232
239
  obj: The object to load.
233
240
  secrets_map: A map of secrets to load. If a secret is not found in
234
241
  the map, it will be loaded from the environment if `secrets_from_env`
235
- is True. Defaults to None.
242
+ is True.
236
243
  valid_namespaces: A list of additional namespaces (modules)
237
- to allow to be deserialized. Defaults to None.
244
+ to allow to be deserialized.
238
245
  secrets_from_env: Whether to load secrets from the environment.
239
- Defaults to True.
240
246
  additional_import_mappings: A dictionary of additional namespace mappings
241
247
  You can use this to override default mappings or add new mappings.
242
- Defaults to None.
243
248
  ignore_unserializable_fields: Whether to ignore unserializable fields.
244
- Defaults to False.
245
249
 
246
250
  Returns:
247
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
 
@@ -20,53 +18,41 @@ logger = logging.getLogger(__name__)
20
18
 
21
19
 
22
20
  class BaseSerialized(TypedDict):
23
- """Base class for serialized objects.
24
-
25
- Parameters:
26
- lc: The version of the serialization format.
27
- id: The unique identifier of the object.
28
- name: The name of the object. Optional.
29
- graph: The graph of the object. Optional.
30
- """
21
+ """Base class for serialized objects."""
31
22
 
32
23
  lc: int
24
+ """The version of the serialization format."""
33
25
  id: list[str]
26
+ """The unique identifier of the object."""
34
27
  name: NotRequired[str]
28
+ """The name of the object."""
35
29
  graph: NotRequired[dict[str, Any]]
30
+ """The graph of the object."""
36
31
 
37
32
 
38
33
  class SerializedConstructor(BaseSerialized):
39
- """Serialized constructor.
40
-
41
- Parameters:
42
- type: The type of the object. Must be "constructor".
43
- kwargs: The constructor arguments.
44
- """
34
+ """Serialized constructor."""
45
35
 
46
36
  type: Literal["constructor"]
37
+ """The type of the object. Must be `'constructor'`."""
47
38
  kwargs: dict[str, Any]
39
+ """The constructor arguments."""
48
40
 
49
41
 
50
42
  class SerializedSecret(BaseSerialized):
51
- """Serialized secret.
52
-
53
- Parameters:
54
- type: The type of the object. Must be "secret".
55
- """
43
+ """Serialized secret."""
56
44
 
57
45
  type: Literal["secret"]
46
+ """The type of the object. Must be `'secret'`."""
58
47
 
59
48
 
60
49
  class SerializedNotImplemented(BaseSerialized):
61
- """Serialized not implemented.
62
-
63
- Parameters:
64
- type: The type of the object. Must be "not_implemented".
65
- repr: The representation of the object. Optional.
66
- """
50
+ """Serialized not implemented."""
67
51
 
68
52
  type: Literal["not_implemented"]
69
- repr: Optional[str]
53
+ """The type of the object. Must be `'not_implemented'`."""
54
+ repr: str | None
55
+ """The representation of the object."""
70
56
 
71
57
 
72
58
  def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
@@ -75,13 +61,10 @@ def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
75
61
  Args:
76
62
  value: The value.
77
63
  key: The key.
78
- model: The pydantic model.
64
+ model: The Pydantic model.
79
65
 
80
66
  Returns:
81
67
  Whether the value is different from the default.
82
-
83
- Raises:
84
- Exception: If the key is not in the model.
85
68
  """
86
69
  field = type(model).model_fields[key]
87
70
  return _try_neq_default(value, field)
@@ -110,15 +93,15 @@ class Serializable(BaseModel, ABC):
110
93
  It relies on the following methods and properties:
111
94
 
112
95
  - `is_lc_serializable`: Is this class serializable?
113
- By design, even if a class inherits from Serializable, it is not serializable by
114
- default. This is to prevent accidental serialization of objects that should not
115
- be serialized.
116
- - `get_lc_namespace`: Get the namespace of the langchain object.
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.
117
100
  During deserialization, this namespace is used to identify
118
101
  the correct class to instantiate.
119
102
  Please see the `Reviver` class in `langchain_core.load.load` for more details.
120
- During deserialization an additional mapping is handle
121
- classes that have moved or been renamed across package versions.
103
+ During deserialization an additional mapping is handle classes that have moved
104
+ or been renamed across package versions.
122
105
  - `lc_secrets`: A map of constructor argument names to secret ids.
123
106
  - `lc_attributes`: List of additional attribute names that should be included
124
107
  as part of the serialized representation.
@@ -126,28 +109,31 @@ class Serializable(BaseModel, ABC):
126
109
 
127
110
  # Remove default BaseModel init docstring.
128
111
  def __init__(self, *args: Any, **kwargs: Any) -> None:
129
- """""" # noqa: D419
112
+ """""" # noqa: D419 # Intentional blank docstring
130
113
  super().__init__(*args, **kwargs)
131
114
 
132
115
  @classmethod
133
116
  def is_lc_serializable(cls) -> bool:
134
117
  """Is this class serializable?
135
118
 
136
- By design, even if a class inherits from Serializable, it is not serializable by
137
- default. This is to prevent accidental serialization of objects that should not
138
- be serialized.
119
+ By design, even if a class inherits from `Serializable`, it is not serializable
120
+ by default. This is to prevent accidental serialization of objects that should
121
+ not be serialized.
139
122
 
140
123
  Returns:
141
- Whether the class is serializable. Default is False.
124
+ Whether the class is serializable. Default is `False`.
142
125
  """
143
126
  return False
144
127
 
145
128
  @classmethod
146
129
  def get_lc_namespace(cls) -> list[str]:
147
- """Get the namespace of the langchain object.
130
+ """Get the namespace of the LangChain object.
148
131
 
149
132
  For example, if the class is `langchain.llms.openai.OpenAI`, then the
150
- namespace is ["langchain", "llms", "openai"]
133
+ namespace is `["langchain", "llms", "openai"]`
134
+
135
+ Returns:
136
+ The namespace.
151
137
  """
152
138
  return cls.__module__.split(".")
153
139
 
@@ -155,8 +141,7 @@ class Serializable(BaseModel, ABC):
155
141
  def lc_secrets(self) -> dict[str, str]:
156
142
  """A map of constructor argument names to secret ids.
157
143
 
158
- For example,
159
- {"openai_api_key": "OPENAI_API_KEY"}
144
+ For example, `{"openai_api_key": "OPENAI_API_KEY"}`
160
145
  """
161
146
  return {}
162
147
 
@@ -165,18 +150,20 @@ class Serializable(BaseModel, ABC):
165
150
  """List of attribute names that should be included in the serialized kwargs.
166
151
 
167
152
  These attributes must be accepted by the constructor.
153
+
168
154
  Default is an empty dictionary.
169
155
  """
170
156
  return {}
171
157
 
172
158
  @classmethod
173
159
  def lc_id(cls) -> list[str]:
174
- """A unique identifier for this class for serialization purposes.
160
+ """Return a unique identifier for this class for serialization purposes.
175
161
 
176
162
  The unique identifier is a list of strings that describes the path
177
163
  to the object.
164
+
178
165
  For example, for the class `langchain.llms.openai.OpenAI`, the id is
179
- ["langchain", "llms", "openai", "OpenAI"].
166
+ `["langchain", "llms", "openai", "OpenAI"]`.
180
167
  """
181
168
  # Pydantic generics change the class name. So we need to do the following
182
169
  if (
@@ -200,11 +187,14 @@ class Serializable(BaseModel, ABC):
200
187
  if (k not in type(self).model_fields or try_neq_default(v, k, self))
201
188
  ]
202
189
 
203
- def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:
190
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
204
191
  """Serialize the object to JSON.
205
192
 
193
+ Raises:
194
+ ValueError: If the class has deprecated attributes.
195
+
206
196
  Returns:
207
- A json serializable object or a SerializedNotImplemented object.
197
+ A json serializable object or a `SerializedNotImplemented` object.
208
198
  """
209
199
  if not self.is_lc_serializable():
210
200
  return self.to_json_not_implemented()
@@ -276,7 +266,11 @@ class Serializable(BaseModel, ABC):
276
266
  }
277
267
 
278
268
  def to_json_not_implemented(self) -> SerializedNotImplemented:
279
- """Serialize a "not implemented" object."""
269
+ """Serialize a "not implemented" object.
270
+
271
+ Returns:
272
+ `SerializedNotImplemented`.
273
+ """
280
274
  return to_json_not_implemented(self)
281
275
 
282
276
 
@@ -290,8 +284,8 @@ def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
290
284
 
291
285
  Returns:
292
286
  Whether the field is useful. If the field is required, it is useful.
293
- If the field is not required, it is useful if the value is not None.
294
- If the field is not required and the value is None, it is useful if the
287
+ If the field is not required, it is useful if the value is not `None`.
288
+ If the field is not required and the value is `None`, it is useful if the
295
289
  default value is different from the value.
296
290
  """
297
291
  field = type(inst).model_fields.get(key)
@@ -350,10 +344,10 @@ def to_json_not_implemented(obj: object) -> SerializedNotImplemented:
350
344
  """Serialize a "not implemented" object.
351
345
 
352
346
  Args:
353
- obj: object to serialize.
347
+ obj: Object to serialize.
354
348
 
355
349
  Returns:
356
- SerializedNotImplemented
350
+ `SerializedNotImplemented`
357
351
  """
358
352
  id_: list[str] = []
359
353
  try:
@@ -1,23 +1,9 @@
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
 
20
5
  from langchain_core._import_utils import import_attr
6
+ from langchain_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX, ensure_id
21
7
 
22
8
  if TYPE_CHECKING:
23
9
  from langchain_core.messages.ai import (
@@ -31,28 +17,29 @@ if TYPE_CHECKING:
31
17
  message_to_dict,
32
18
  messages_to_dict,
33
19
  )
20
+ from langchain_core.messages.block_translators.openai import (
21
+ convert_to_openai_data_block,
22
+ convert_to_openai_image_block,
23
+ )
34
24
  from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
35
- from langchain_core.messages.content_blocks import (
25
+ from langchain_core.messages.content import (
36
26
  Annotation,
37
27
  AudioContentBlock,
38
28
  Citation,
39
- CodeInterpreterCall,
40
- CodeInterpreterOutput,
41
- CodeInterpreterResult,
42
29
  ContentBlock,
43
30
  DataContentBlock,
44
31
  FileContentBlock,
45
32
  ImageContentBlock,
33
+ InvalidToolCall,
46
34
  NonStandardAnnotation,
47
35
  NonStandardContentBlock,
48
36
  PlainTextContentBlock,
49
37
  ReasoningContentBlock,
38
+ ServerToolCall,
39
+ ServerToolCallChunk,
40
+ ServerToolResult,
50
41
  TextContentBlock,
51
42
  VideoContentBlock,
52
- WebSearchCall,
53
- WebSearchResult,
54
- convert_to_openai_data_block,
55
- convert_to_openai_image_block,
56
43
  is_data_content_block,
57
44
  )
58
45
  from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
@@ -60,7 +47,6 @@ if TYPE_CHECKING:
60
47
  from langchain_core.messages.modifier import RemoveMessage
61
48
  from langchain_core.messages.system import SystemMessage, SystemMessageChunk
62
49
  from langchain_core.messages.tool import (
63
- InvalidToolCall,
64
50
  ToolCall,
65
51
  ToolCallChunk,
66
52
  ToolMessage,
@@ -81,6 +67,8 @@ if TYPE_CHECKING:
81
67
  )
82
68
 
83
69
  __all__ = (
70
+ "LC_AUTO_PREFIX",
71
+ "LC_ID_PREFIX",
84
72
  "AIMessage",
85
73
  "AIMessageChunk",
86
74
  "Annotation",
@@ -91,9 +79,6 @@ __all__ = (
91
79
  "ChatMessage",
92
80
  "ChatMessageChunk",
93
81
  "Citation",
94
- "CodeInterpreterCall",
95
- "CodeInterpreterOutput",
96
- "CodeInterpreterResult",
97
82
  "ContentBlock",
98
83
  "DataContentBlock",
99
84
  "FileContentBlock",
@@ -109,6 +94,9 @@ __all__ = (
109
94
  "PlainTextContentBlock",
110
95
  "ReasoningContentBlock",
111
96
  "RemoveMessage",
97
+ "ServerToolCall",
98
+ "ServerToolCallChunk",
99
+ "ServerToolResult",
112
100
  "SystemMessage",
113
101
  "SystemMessageChunk",
114
102
  "TextContentBlock",
@@ -117,13 +105,12 @@ __all__ = (
117
105
  "ToolMessage",
118
106
  "ToolMessageChunk",
119
107
  "VideoContentBlock",
120
- "WebSearchCall",
121
- "WebSearchResult",
122
108
  "_message_from_dict",
123
109
  "convert_to_messages",
124
110
  "convert_to_openai_data_block",
125
111
  "convert_to_openai_image_block",
126
112
  "convert_to_openai_messages",
113
+ "ensure_id",
127
114
  "filter_messages",
128
115
  "get_buffer_string",
129
116
  "is_data_content_block",
@@ -139,53 +126,51 @@ __all__ = (
139
126
  _dynamic_imports = {
140
127
  "AIMessage": "ai",
141
128
  "AIMessageChunk": "ai",
142
- "Annotation": "content_blocks",
143
- "AudioContentBlock": "content_blocks",
129
+ "Annotation": "content",
130
+ "AudioContentBlock": "content",
144
131
  "BaseMessage": "base",
145
132
  "BaseMessageChunk": "base",
146
133
  "merge_content": "base",
147
134
  "message_to_dict": "base",
148
135
  "messages_to_dict": "base",
149
- "Citation": "content_blocks",
150
- "ContentBlock": "content_blocks",
136
+ "Citation": "content",
137
+ "ContentBlock": "content",
151
138
  "ChatMessage": "chat",
152
139
  "ChatMessageChunk": "chat",
153
- "CodeInterpreterCall": "content_blocks",
154
- "CodeInterpreterOutput": "content_blocks",
155
- "CodeInterpreterResult": "content_blocks",
156
- "DataContentBlock": "content_blocks",
157
- "FileContentBlock": "content_blocks",
140
+ "DataContentBlock": "content",
141
+ "FileContentBlock": "content",
158
142
  "FunctionMessage": "function",
159
143
  "FunctionMessageChunk": "function",
160
144
  "HumanMessage": "human",
161
145
  "HumanMessageChunk": "human",
162
- "NonStandardAnnotation": "content_blocks",
163
- "NonStandardContentBlock": "content_blocks",
164
- "PlainTextContentBlock": "content_blocks",
165
- "ReasoningContentBlock": "content_blocks",
146
+ "NonStandardAnnotation": "content",
147
+ "NonStandardContentBlock": "content",
148
+ "PlainTextContentBlock": "content",
149
+ "ReasoningContentBlock": "content",
166
150
  "RemoveMessage": "modifier",
151
+ "ServerToolCall": "content",
152
+ "ServerToolCallChunk": "content",
153
+ "ServerToolResult": "content",
167
154
  "SystemMessage": "system",
168
155
  "SystemMessageChunk": "system",
169
- "WebSearchCall": "content_blocks",
170
- "WebSearchResult": "content_blocks",
171
- "ImageContentBlock": "content_blocks",
156
+ "ImageContentBlock": "content",
172
157
  "InvalidToolCall": "tool",
173
- "TextContentBlock": "content_blocks",
158
+ "TextContentBlock": "content",
174
159
  "ToolCall": "tool",
175
160
  "ToolCallChunk": "tool",
176
161
  "ToolMessage": "tool",
177
162
  "ToolMessageChunk": "tool",
178
- "VideoContentBlock": "content_blocks",
163
+ "VideoContentBlock": "content",
179
164
  "AnyMessage": "utils",
180
165
  "MessageLikeRepresentation": "utils",
181
166
  "_message_from_dict": "utils",
182
167
  "convert_to_messages": "utils",
183
- "convert_to_openai_data_block": "content_blocks",
184
- "convert_to_openai_image_block": "content_blocks",
168
+ "convert_to_openai_data_block": "block_translators.openai",
169
+ "convert_to_openai_image_block": "block_translators.openai",
185
170
  "convert_to_openai_messages": "utils",
186
171
  "filter_messages": "utils",
187
172
  "get_buffer_string": "utils",
188
- "is_data_content_block": "content_blocks",
173
+ "is_data_content_block": "content",
189
174
  "merge_message_runs": "utils",
190
175
  "message_chunk_to_message": "utils",
191
176
  "messages_from_dict": "utils",