langchain-core 1.0.0rc1__py3-none-any.whl → 1.0.0rc2__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 (92) hide show
  1. langchain_core/agents.py +3 -3
  2. langchain_core/caches.py +44 -48
  3. langchain_core/callbacks/base.py +5 -5
  4. langchain_core/callbacks/file.py +2 -2
  5. langchain_core/callbacks/stdout.py +1 -1
  6. langchain_core/chat_history.py +1 -1
  7. langchain_core/document_loaders/base.py +21 -21
  8. langchain_core/document_loaders/langsmith.py +2 -2
  9. langchain_core/documents/base.py +39 -39
  10. langchain_core/embeddings/fake.py +4 -2
  11. langchain_core/example_selectors/semantic_similarity.py +4 -6
  12. langchain_core/exceptions.py +3 -4
  13. langchain_core/indexing/api.py +8 -14
  14. langchain_core/language_models/__init__.py +11 -25
  15. langchain_core/language_models/_utils.py +2 -1
  16. langchain_core/language_models/base.py +7 -0
  17. langchain_core/language_models/chat_models.py +14 -16
  18. langchain_core/language_models/fake_chat_models.py +3 -3
  19. langchain_core/language_models/llms.py +4 -4
  20. langchain_core/load/dump.py +3 -4
  21. langchain_core/load/load.py +0 -9
  22. langchain_core/load/serializable.py +3 -3
  23. langchain_core/messages/ai.py +20 -22
  24. langchain_core/messages/base.py +8 -8
  25. langchain_core/messages/block_translators/__init__.py +1 -1
  26. langchain_core/messages/block_translators/anthropic.py +1 -1
  27. langchain_core/messages/block_translators/bedrock_converse.py +1 -1
  28. langchain_core/messages/block_translators/google_genai.py +3 -2
  29. langchain_core/messages/block_translators/google_vertexai.py +4 -32
  30. langchain_core/messages/block_translators/langchain_v0.py +1 -1
  31. langchain_core/messages/block_translators/openai.py +1 -1
  32. langchain_core/messages/chat.py +2 -6
  33. langchain_core/messages/content.py +34 -17
  34. langchain_core/messages/function.py +3 -7
  35. langchain_core/messages/human.py +4 -9
  36. langchain_core/messages/modifier.py +1 -1
  37. langchain_core/messages/system.py +2 -10
  38. langchain_core/messages/tool.py +30 -42
  39. langchain_core/messages/utils.py +24 -30
  40. langchain_core/output_parsers/base.py +24 -24
  41. langchain_core/output_parsers/json.py +0 -1
  42. langchain_core/output_parsers/list.py +1 -1
  43. langchain_core/output_parsers/openai_functions.py +2 -2
  44. langchain_core/output_parsers/openai_tools.py +4 -9
  45. langchain_core/output_parsers/string.py +1 -1
  46. langchain_core/outputs/generation.py +1 -1
  47. langchain_core/prompt_values.py +7 -7
  48. langchain_core/prompts/base.py +1 -1
  49. langchain_core/prompts/chat.py +12 -13
  50. langchain_core/prompts/dict.py +2 -2
  51. langchain_core/prompts/few_shot_with_templates.py +1 -1
  52. langchain_core/prompts/image.py +1 -1
  53. langchain_core/prompts/message.py +2 -2
  54. langchain_core/prompts/prompt.py +7 -8
  55. langchain_core/prompts/string.py +1 -1
  56. langchain_core/prompts/structured.py +2 -2
  57. langchain_core/rate_limiters.py +23 -29
  58. langchain_core/retrievers.py +29 -29
  59. langchain_core/runnables/base.py +9 -16
  60. langchain_core/runnables/branch.py +1 -1
  61. langchain_core/runnables/config.py +1 -1
  62. langchain_core/runnables/configurable.py +2 -2
  63. langchain_core/runnables/fallbacks.py +1 -1
  64. langchain_core/runnables/graph.py +23 -28
  65. langchain_core/runnables/graph_mermaid.py +9 -9
  66. langchain_core/runnables/graph_png.py +1 -1
  67. langchain_core/runnables/history.py +2 -2
  68. langchain_core/runnables/passthrough.py +3 -3
  69. langchain_core/runnables/router.py +1 -1
  70. langchain_core/runnables/utils.py +5 -5
  71. langchain_core/tools/base.py +9 -10
  72. langchain_core/tools/convert.py +13 -17
  73. langchain_core/tools/retriever.py +6 -6
  74. langchain_core/tools/simple.py +1 -1
  75. langchain_core/tools/structured.py +5 -10
  76. langchain_core/tracers/memory_stream.py +1 -1
  77. langchain_core/tracers/root_listeners.py +2 -2
  78. langchain_core/tracers/stdout.py +1 -2
  79. langchain_core/utils/__init__.py +1 -1
  80. langchain_core/utils/aiter.py +1 -1
  81. langchain_core/utils/function_calling.py +15 -38
  82. langchain_core/utils/input.py +1 -1
  83. langchain_core/utils/iter.py +1 -1
  84. langchain_core/utils/json.py +1 -1
  85. langchain_core/utils/strings.py +1 -1
  86. langchain_core/vectorstores/base.py +14 -25
  87. langchain_core/vectorstores/utils.py +2 -2
  88. langchain_core/version.py +1 -1
  89. {langchain_core-1.0.0rc1.dist-info → langchain_core-1.0.0rc2.dist-info}/METADATA +1 -1
  90. langchain_core-1.0.0rc2.dist-info/RECORD +172 -0
  91. langchain_core-1.0.0rc1.dist-info/RECORD +0 -172
  92. {langchain_core-1.0.0rc1.dist-info → langchain_core-1.0.0rc2.dist-info}/WHEEL +0 -0
@@ -154,7 +154,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
154
154
  examples: List of examples to use in the prompt.
155
155
  embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
156
156
  vectorstore_cls: A vector store DB interface class, e.g. FAISS.
157
- k: Number of examples to select. Default is 4.
157
+ k: Number of examples to select.
158
158
  input_keys: If provided, the search is based on the input variables
159
159
  instead of all variables.
160
160
  example_keys: If provided, keys to filter examples to.
@@ -198,7 +198,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
198
198
  examples: List of examples to use in the prompt.
199
199
  embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
200
200
  vectorstore_cls: A vector store DB interface class, e.g. FAISS.
201
- k: Number of examples to select. Default is 4.
201
+ k: Number of examples to select.
202
202
  input_keys: If provided, the search is based on the input variables
203
203
  instead of all variables.
204
204
  example_keys: If provided, keys to filter examples to.
@@ -285,9 +285,8 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
285
285
  examples: List of examples to use in the prompt.
286
286
  embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
287
287
  vectorstore_cls: A vector store DB interface class, e.g. FAISS.
288
- k: Number of examples to select. Default is 4.
288
+ k: Number of examples to select.
289
289
  fetch_k: Number of Documents to fetch to pass to MMR algorithm.
290
- Default is 20.
291
290
  input_keys: If provided, the search is based on the input variables
292
291
  instead of all variables.
293
292
  example_keys: If provided, keys to filter examples to.
@@ -333,9 +332,8 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
333
332
  examples: List of examples to use in the prompt.
334
333
  embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
335
334
  vectorstore_cls: A vector store DB interface class, e.g. FAISS.
336
- k: Number of examples to select. Default is 4.
335
+ k: Number of examples to select.
337
336
  fetch_k: Number of Documents to fetch to pass to MMR algorithm.
338
- Default is 20.
339
337
  input_keys: If provided, the search is based on the input variables
340
338
  instead of all variables.
341
339
  example_keys: If provided, keys to filter examples to.
@@ -16,7 +16,7 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
16
16
  """Exception that output parsers should raise to signify a parsing error.
17
17
 
18
18
  This exists to differentiate parsing errors from other code or execution errors
19
- that also may arise inside the output parser. OutputParserExceptions will be
19
+ that also may arise inside the output parser. `OutputParserException` will be
20
20
  available to catch and handle in ways to fix the parsing error, while other
21
21
  errors will be raised.
22
22
  """
@@ -28,7 +28,7 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
28
28
  llm_output: str | None = None,
29
29
  send_to_llm: bool = False, # noqa: FBT001,FBT002
30
30
  ):
31
- """Create an OutputParserException.
31
+ """Create an `OutputParserException`.
32
32
 
33
33
  Args:
34
34
  error: The error that's being re-raised or an error message.
@@ -37,11 +37,10 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
37
37
  llm_output: String model output which is error-ing.
38
38
 
39
39
  send_to_llm: Whether to send the observation and llm_output back to an Agent
40
- after an OutputParserException has been raised.
40
+ after an `OutputParserException` has been raised.
41
41
  This gives the underlying model driving the agent the context that the
42
42
  previous output was improperly structured, in the hopes that it will
43
43
  update the output to the correct format.
44
- Defaults to `False`.
45
44
 
46
45
  Raises:
47
46
  ValueError: If `send_to_llm` is True but either observation or
@@ -326,8 +326,8 @@ def index(
326
326
  record_manager: Timestamped set to keep track of which documents were
327
327
  updated.
328
328
  vector_store: VectorStore or DocumentIndex to index the documents into.
329
- batch_size: Batch size to use when indexing. Default is 100.
330
- cleanup: How to handle clean up of documents. Default is None.
329
+ batch_size: Batch size to use when indexing.
330
+ cleanup: How to handle clean up of documents.
331
331
 
332
332
  - incremental: Cleans up all documents that haven't been updated AND
333
333
  that are associated with source ids that were seen during indexing.
@@ -342,15 +342,12 @@ def index(
342
342
  source ids that were seen during indexing.
343
343
  - None: Do not delete any documents.
344
344
  source_id_key: Optional key that helps identify the original source
345
- of the document. Default is None.
345
+ of the document.
346
346
  cleanup_batch_size: Batch size to use when cleaning up documents.
347
- Default is 1_000.
348
347
  force_update: Force update documents even if they are present in the
349
348
  record manager. Useful if you are re-indexing with updated embeddings.
350
- Default is False.
351
349
  key_encoder: Hashing algorithm to use for hashing the document content and
352
- metadata. Default is "sha1".
353
- Other options include "blake2b", "sha256", and "sha512".
350
+ metadata. Options include "blake2b", "sha256", and "sha512".
354
351
 
355
352
  !!! version-added "Added in version 0.3.66"
356
353
 
@@ -667,8 +664,8 @@ async def aindex(
667
664
  record_manager: Timestamped set to keep track of which documents were
668
665
  updated.
669
666
  vector_store: VectorStore or DocumentIndex to index the documents into.
670
- batch_size: Batch size to use when indexing. Default is 100.
671
- cleanup: How to handle clean up of documents. Default is None.
667
+ batch_size: Batch size to use when indexing.
668
+ cleanup: How to handle clean up of documents.
672
669
 
673
670
  - incremental: Cleans up all documents that haven't been updated AND
674
671
  that are associated with source ids that were seen during indexing.
@@ -683,15 +680,12 @@ async def aindex(
683
680
  source ids that were seen during indexing.
684
681
  - None: Do not delete any documents.
685
682
  source_id_key: Optional key that helps identify the original source
686
- of the document. Default is None.
683
+ of the document.
687
684
  cleanup_batch_size: Batch size to use when cleaning up documents.
688
- Default is 1_000.
689
685
  force_update: Force update documents even if they are present in the
690
686
  record manager. Useful if you are re-indexing with updated embeddings.
691
- Default is False.
692
687
  key_encoder: Hashing algorithm to use for hashing the document content and
693
- metadata. Default is "sha1".
694
- Other options include "blake2b", "sha256", and "sha512".
688
+ metadata. Options include "blake2b", "sha256", and "sha512".
695
689
 
696
690
  !!! version-added "Added in version 0.3.66"
697
691
 
@@ -1,43 +1,29 @@
1
1
  """Language models.
2
2
 
3
- **Language Model** is a type of model that can generate text or complete
4
- text prompts.
3
+ LangChain has two main classes to work with language models: chat models and
4
+ "old-fashioned" LLMs.
5
5
 
6
- LangChain has two main classes to work with language models: **Chat Models**
7
- and "old-fashioned" **LLMs**.
8
-
9
- **Chat Models**
6
+ **Chat models**
10
7
 
11
8
  Language models that use a sequence of messages as inputs and return chat messages
12
- as outputs (as opposed to using plain text). These are traditionally newer models (
13
- older models are generally LLMs, see below). Chat models support the assignment of
9
+ as outputs (as opposed to using plain text). Chat models support the assignment of
14
10
  distinct roles to conversation messages, helping to distinguish messages from the AI,
15
11
  users, and instructions such as system messages.
16
12
 
17
13
  The key abstraction for chat models is `BaseChatModel`. Implementations
18
- should inherit from this class. Please see LangChain how-to guides with more
19
- information on how to implement a custom chat model.
20
-
21
- To implement a custom Chat Model, inherit from `BaseChatModel`. See
22
- the following guide for more information on how to implement a custom Chat Model:
14
+ should inherit from this class.
23
15
 
24
- https://python.langchain.com/docs/how_to/custom_chat_model/
16
+ See existing [chat model integrations](https://docs.langchain.com/oss/python/integrations/chat).
25
17
 
26
18
  **LLMs**
27
19
 
28
20
  Language models that takes a string as input and returns a string.
29
- These are traditionally older models (newer models generally are Chat Models,
30
- see below).
31
-
32
- Although the underlying models are string in, string out, the LangChain wrappers
33
- also allow these models to take messages as input. This gives them the same interface
34
- as Chat Models. When messages are passed in as input, they will be formatted into a
35
- string under the hood before being passed to the underlying model.
36
-
37
- To implement a custom LLM, inherit from `BaseLLM` or `LLM`.
38
- Please see the following guide for more information on how to implement a custom LLM:
21
+ These are traditionally older models (newer models generally are chat models).
39
22
 
40
- https://python.langchain.com/docs/how_to/custom_llm/
23
+ Although the underlying models are string in, string out, the LangChain wrappers also
24
+ allow these models to take messages as input. This gives them the same interface as
25
+ chat models. When messages are passed in as input, they will be formatted into a string
26
+ under the hood before being passed to the underlying model.
41
27
  """
42
28
 
43
29
  from typing import TYPE_CHECKING
@@ -89,7 +89,8 @@ class ParsedDataUri(TypedDict):
89
89
  def _parse_data_uri(uri: str) -> ParsedDataUri | None:
90
90
  """Parse a data URI into its components.
91
91
 
92
- If parsing fails, return None. If either MIME type or data is missing, return None.
92
+ If parsing fails, return `None`. If either MIME type or data is missing, return
93
+ `None`.
93
94
 
94
95
  Example:
95
96
  ```python
@@ -96,9 +96,16 @@ def _get_token_ids_default_method(text: str) -> list[int]:
96
96
 
97
97
 
98
98
  LanguageModelInput = PromptValue | str | Sequence[MessageLikeRepresentation]
99
+ """Input to a language model."""
100
+
99
101
  LanguageModelOutput = BaseMessage | str
102
+ """Output from a language model."""
103
+
100
104
  LanguageModelLike = Runnable[LanguageModelInput, LanguageModelOutput]
105
+ """Input/output interface for a language model."""
106
+
101
107
  LanguageModelOutputVar = TypeVar("LanguageModelOutputVar", AIMessage, str)
108
+ """Type variable for the output of a language model."""
102
109
 
103
110
 
104
111
  def _get_verbosity() -> bool:
@@ -264,21 +264,21 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
264
264
 
265
265
  This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
266
266
 
267
- | Method | Description |
268
- | ---------------------------- | -------------------------------------------------------------------------------------------- |
269
- | `bind_tools` | Create chat model that can call tools. |
270
- | `with_structured_output` | Create wrapper that structures model output using schema. |
271
- | `with_retry` | Create wrapper that retries model calls on failure. |
272
- | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
273
- | `configurable_fields` | Specify init args of the model that can be configured at runtime via the `RunnableConfig`. |
274
- | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the `RunnableConfig`. |
267
+ | Method | Description |
268
+ | ---------------------------- | ------------------------------------------------------------------------------------------ |
269
+ | `bind_tools` | Create chat model that can call tools. |
270
+ | `with_structured_output` | Create wrapper that structures model output using schema. |
271
+ | `with_retry` | Create wrapper that retries model calls on failure. |
272
+ | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
273
+ | `configurable_fields` | Specify init args of the model that can be configured at runtime via the `RunnableConfig`. |
274
+ | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the `RunnableConfig`. |
275
275
 
276
276
  Creating custom chat model:
277
277
  Custom chat model implementations should inherit from this class.
278
278
  Please reference the table below for information about which
279
279
  methods and properties are required or optional for implementations.
280
280
 
281
- | Method/Property | Description | Required/Optional |
281
+ | Method/Property | Description | Required |
282
282
  | -------------------------------- | ------------------------------------------------------------------ | ----------------- |
283
283
  | `_generate` | Use to generate a chat result from a prompt | Required |
284
284
  | `_llm_type` (property) | Used to uniquely identify the type of the model. Used for logging. | Required |
@@ -287,9 +287,6 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
287
287
  | `_agenerate` | Use to implement a native async method | Optional |
288
288
  | `_astream` | Use to implement async version of `_stream` | Optional |
289
289
 
290
- Follow the guide for more information on how to implement a custom chat model:
291
- [Guide](https://python.langchain.com/docs/how_to/custom_chat_model/).
292
-
293
290
  """ # noqa: E501
294
291
 
295
292
  rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True)
@@ -325,11 +322,12 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
325
322
  Supported values:
326
323
 
327
324
  - `'v0'`: provider-specific format in content (can lazily-parse with
328
- `.content_blocks`)
329
- - `'v1'`: standardized format in content (consistent with `.content_blocks`)
325
+ `content_blocks`)
326
+ - `'v1'`: standardized format in content (consistent with `content_blocks`)
330
327
 
331
- Partner packages (e.g., `langchain-openai`) can also use this field to roll out
332
- new content formats in a backward-compatible way.
328
+ Partner packages (e.g.,
329
+ [`langchain-openai`](https://pypi.org/project/langchain-openai)) can also use this
330
+ field to roll out new content formats in a backward-compatible way.
333
331
 
334
332
  !!! version-added "Added in version 1.0"
335
333
 
@@ -1,4 +1,4 @@
1
- """Fake ChatModel for testing purposes."""
1
+ """Fake chat model for testing purposes."""
2
2
 
3
3
  import asyncio
4
4
  import re
@@ -19,7 +19,7 @@ from langchain_core.runnables import RunnableConfig
19
19
 
20
20
 
21
21
  class FakeMessagesListChatModel(BaseChatModel):
22
- """Fake `ChatModel` for testing purposes."""
22
+ """Fake chat model for testing purposes."""
23
23
 
24
24
  responses: list[BaseMessage]
25
25
  """List of responses to **cycle** through in order."""
@@ -57,7 +57,7 @@ class FakeListChatModelError(Exception):
57
57
 
58
58
 
59
59
  class FakeListChatModel(SimpleChatModel):
60
- """Fake ChatModel for testing purposes."""
60
+ """Fake chat model for testing purposes."""
61
61
 
62
62
  responses: list[str]
63
63
  """List of responses to **cycle** through in order."""
@@ -74,8 +74,8 @@ def create_base_retry_decorator(
74
74
 
75
75
  Args:
76
76
  error_types: List of error types to retry on.
77
- max_retries: Number of retries. Default is 1.
78
- run_manager: Callback manager for the run. Default is None.
77
+ max_retries: Number of retries.
78
+ run_manager: Callback manager for the run.
79
79
 
80
80
  Returns:
81
81
  A retry decorator.
@@ -153,7 +153,7 @@ def get_prompts(
153
153
  Args:
154
154
  params: Dictionary of parameters.
155
155
  prompts: List of prompts.
156
- cache: Cache object. Default is None.
156
+ cache: Cache object.
157
157
 
158
158
  Returns:
159
159
  A tuple of existing prompts, llm_string, missing prompt indexes,
@@ -189,7 +189,7 @@ async def aget_prompts(
189
189
  Args:
190
190
  params: Dictionary of parameters.
191
191
  prompts: List of prompts.
192
- cache: Cache object. Default is None.
192
+ cache: Cache object.
193
193
 
194
194
  Returns:
195
195
  A tuple of existing prompts, llm_string, missing prompt indexes,
@@ -42,10 +42,9 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
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
50
  A json string representation of the object.
@@ -67,12 +67,9 @@ class Reviver:
67
67
  valid_namespaces: A list of additional namespaces (modules)
68
68
  to allow to be deserialized.
69
69
  secrets_from_env: Whether to load secrets from the environment.
70
- Defaults to `True`.
71
70
  additional_import_mappings: A dictionary of additional namespace mappings
72
71
  You can use this to override default mappings or add new mappings.
73
-
74
72
  ignore_unserializable_fields: Whether to ignore unserializable fields.
75
- Defaults to `False`.
76
73
  """
77
74
  self.secrets_from_env = secrets_from_env
78
75
  self.secrets_map = secrets_map or {}
@@ -204,12 +201,9 @@ def loads(
204
201
  valid_namespaces: A list of additional namespaces (modules)
205
202
  to allow to be deserialized.
206
203
  secrets_from_env: Whether to load secrets from the environment.
207
- Defaults to `True`.
208
204
  additional_import_mappings: A dictionary of additional namespace mappings
209
205
  You can use this to override default mappings or add new mappings.
210
-
211
206
  ignore_unserializable_fields: Whether to ignore unserializable fields.
212
- Defaults to `False`.
213
207
 
214
208
  Returns:
215
209
  Revived LangChain objects.
@@ -249,12 +243,9 @@ def load(
249
243
  valid_namespaces: A list of additional namespaces (modules)
250
244
  to allow to be deserialized.
251
245
  secrets_from_env: Whether to load secrets from the environment.
252
- Defaults to `True`.
253
246
  additional_import_mappings: A dictionary of additional namespace mappings
254
247
  You can use this to override default mappings or add new mappings.
255
-
256
248
  ignore_unserializable_fields: Whether to ignore unserializable fields.
257
- Defaults to `False`.
258
249
 
259
250
  Returns:
260
251
  Revived LangChain objects.
@@ -96,7 +96,7 @@ class Serializable(BaseModel, ABC):
96
96
  By design, even if a class inherits from `Serializable`, it is not serializable
97
97
  by default. This is to prevent accidental serialization of objects that should
98
98
  not be serialized.
99
- - `get_lc_namespace`: Get the namespace of the langchain object.
99
+ - `get_lc_namespace`: Get the namespace of the LangChain object.
100
100
  During deserialization, this namespace is used to identify
101
101
  the correct class to instantiate.
102
102
  Please see the `Reviver` class in `langchain_core.load.load` for more details.
@@ -127,10 +127,10 @@ class Serializable(BaseModel, ABC):
127
127
 
128
128
  @classmethod
129
129
  def get_lc_namespace(cls) -> list[str]:
130
- """Get the namespace of the langchain object.
130
+ """Get the namespace of the LangChain object.
131
131
 
132
132
  For example, if the class is `langchain.llms.openai.OpenAI`, then the
133
- namespace is ["langchain", "llms", "openai"]
133
+ namespace is `["langchain", "llms", "openai"]`
134
134
 
135
135
  Returns:
136
136
  The namespace.
@@ -148,27 +148,26 @@ class UsageMetadata(TypedDict):
148
148
  class AIMessage(BaseMessage):
149
149
  """Message from an AI.
150
150
 
151
- AIMessage is returned from a chat model as a response to a prompt.
151
+ An `AIMessage` is returned from a chat model as a response to a prompt.
152
152
 
153
153
  This message represents the output of the model and consists of both
154
- the raw output as returned by the model together standardized fields
154
+ the raw output as returned by the model and standardized fields
155
155
  (e.g., tool calls, usage metadata) added by the LangChain framework.
156
156
 
157
157
  """
158
158
 
159
159
  tool_calls: list[ToolCall] = []
160
- """If provided, tool calls associated with the message."""
160
+ """If present, tool calls associated with the message."""
161
161
  invalid_tool_calls: list[InvalidToolCall] = []
162
- """If provided, tool calls with parsing errors associated with the message."""
162
+ """If present, tool calls with parsing errors associated with the message."""
163
163
  usage_metadata: UsageMetadata | None = None
164
- """If provided, usage metadata for a message, such as token counts.
164
+ """If present, usage metadata for a message, such as token counts.
165
165
 
166
166
  This is a standard representation of token usage that is consistent across models.
167
-
168
167
  """
169
168
 
170
169
  type: Literal["ai"] = "ai"
171
- """The type of the message (used for deserialization). Defaults to "ai"."""
170
+ """The type of the message (used for deserialization)."""
172
171
 
173
172
  @overload
174
173
  def __init__(
@@ -191,7 +190,7 @@ class AIMessage(BaseMessage):
191
190
  content_blocks: list[types.ContentBlock] | None = None,
192
191
  **kwargs: Any,
193
192
  ) -> None:
194
- """Initialize `AIMessage`.
193
+ """Initialize an `AIMessage`.
195
194
 
196
195
  Specify `content` as positional arg or `content_blocks` for typing.
197
196
 
@@ -217,7 +216,11 @@ class AIMessage(BaseMessage):
217
216
 
218
217
  @property
219
218
  def lc_attributes(self) -> dict:
220
- """Attrs to be serialized even if they are derived from other init args."""
219
+ """Attributes to be serialized.
220
+
221
+ Includes all attributes, even if they are derived from other initialization
222
+ arguments.
223
+ """
221
224
  return {
222
225
  "tool_calls": self.tool_calls,
223
226
  "invalid_tool_calls": self.invalid_tool_calls,
@@ -225,7 +228,7 @@ class AIMessage(BaseMessage):
225
228
 
226
229
  @property
227
230
  def content_blocks(self) -> list[types.ContentBlock]:
228
- """Return content blocks of the message.
231
+ """Return standard, typed `ContentBlock` dicts from the message.
229
232
 
230
233
  If the message has a known model provider, use the provider-specific translator
231
234
  first before falling back to best-effort parsing. For details, see the property
@@ -331,11 +334,10 @@ class AIMessage(BaseMessage):
331
334
 
332
335
  @override
333
336
  def pretty_repr(self, html: bool = False) -> str:
334
- """Return a pretty representation of the message.
337
+ """Return a pretty representation of the message for display.
335
338
 
336
339
  Args:
337
340
  html: Whether to return an HTML-formatted string.
338
- Defaults to `False`.
339
341
 
340
342
  Returns:
341
343
  A pretty representation of the message.
@@ -372,23 +374,19 @@ class AIMessage(BaseMessage):
372
374
 
373
375
 
374
376
  class AIMessageChunk(AIMessage, BaseMessageChunk):
375
- """Message chunk from an AI."""
377
+ """Message chunk from an AI (yielded when streaming)."""
376
378
 
377
379
  # Ignoring mypy re-assignment here since we're overriding the value
378
380
  # to make sure that the chunk variant can be discriminated from the
379
381
  # non-chunk variant.
380
382
  type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
381
- """The type of the message (used for deserialization).
382
-
383
- Defaults to `AIMessageChunk`.
384
-
385
- """
383
+ """The type of the message (used for deserialization)."""
386
384
 
387
385
  tool_call_chunks: list[ToolCallChunk] = []
388
386
  """If provided, tool call chunks associated with the message."""
389
387
 
390
388
  chunk_position: Literal["last"] | None = None
391
- """Optional span represented by an aggregated AIMessageChunk.
389
+ """Optional span represented by an aggregated `AIMessageChunk`.
392
390
 
393
391
  If a chunk with `chunk_position="last"` is aggregated into a stream,
394
392
  `tool_call_chunks` in message content will be parsed into `tool_calls`.
@@ -396,7 +394,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
396
394
 
397
395
  @property
398
396
  def lc_attributes(self) -> dict:
399
- """Attrs to be serialized even if they are derived from other init args."""
397
+ """Attributes to be serialized, even if they are derived from other initialization args.""" # noqa: E501
400
398
  return {
401
399
  "tool_calls": self.tool_calls,
402
400
  "invalid_tool_calls": self.invalid_tool_calls,
@@ -404,7 +402,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
404
402
 
405
403
  @property
406
404
  def content_blocks(self) -> list[types.ContentBlock]:
407
- """Return content blocks of the message."""
405
+ """Return standard, typed `ContentBlock` dicts from the message."""
408
406
  if self.response_metadata.get("output_version") == "v1":
409
407
  return cast("list[types.ContentBlock]", self.content)
410
408
 
@@ -553,7 +551,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
553
551
 
554
552
  @model_validator(mode="after")
555
553
  def init_server_tool_calls(self) -> Self:
556
- """Parse server_tool_call_chunks."""
554
+ """Parse `server_tool_call_chunks`."""
557
555
  if (
558
556
  self.chunk_position == "last"
559
557
  and self.response_metadata.get("output_version") == "v1"
@@ -92,11 +92,11 @@ class TextAccessor(str):
92
92
  class BaseMessage(Serializable):
93
93
  """Base abstract message class.
94
94
 
95
- Messages are the inputs and outputs of a `ChatModel`.
95
+ Messages are the inputs and outputs of a chat model.
96
96
  """
97
97
 
98
98
  content: str | list[str | dict]
99
- """The string contents of the message."""
99
+ """The contents of the message."""
100
100
 
101
101
  additional_kwargs: dict = Field(default_factory=dict)
102
102
  """Reserved for additional payload data associated with the message.
@@ -159,12 +159,12 @@ class BaseMessage(Serializable):
159
159
  content_blocks: list[types.ContentBlock] | None = None,
160
160
  **kwargs: Any,
161
161
  ) -> None:
162
- """Initialize `BaseMessage`.
162
+ """Initialize a `BaseMessage`.
163
163
 
164
164
  Specify `content` as positional arg or `content_blocks` for typing.
165
165
 
166
166
  Args:
167
- content: The string contents of the message.
167
+ content: The contents of the message.
168
168
  content_blocks: Typed standard content.
169
169
  **kwargs: Additional arguments to pass to the parent class.
170
170
  """
@@ -184,7 +184,7 @@ class BaseMessage(Serializable):
184
184
 
185
185
  @classmethod
186
186
  def get_lc_namespace(cls) -> list[str]:
187
- """Get the namespace of the langchain object.
187
+ """Get the namespace of the LangChain object.
188
188
 
189
189
  Returns:
190
190
  `["langchain", "schema", "messages"]`
@@ -262,7 +262,7 @@ class BaseMessage(Serializable):
262
262
  Can be used as both property (`message.text`) and method (`message.text()`).
263
263
 
264
264
  !!! deprecated
265
- As of langchain-core 1.0.0, calling `.text()` as a method is deprecated.
265
+ As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated.
266
266
  Use `.text` as a property instead. This method will be removed in 2.0.0.
267
267
 
268
268
  Returns:
@@ -307,7 +307,7 @@ class BaseMessage(Serializable):
307
307
 
308
308
  Args:
309
309
  html: Whether to format the message as HTML. If `True`, the message will be
310
- formatted with HTML tags. Default is False.
310
+ formatted with HTML tags.
311
311
 
312
312
  Returns:
313
313
  A pretty representation of the message.
@@ -464,7 +464,7 @@ def get_msg_title_repr(title: str, *, bold: bool = False) -> str:
464
464
 
465
465
  Args:
466
466
  title: The title.
467
- bold: Whether to bold the title. Default is False.
467
+ bold: Whether to bold the title.
468
468
 
469
469
  Returns:
470
470
  The title representation.
@@ -28,7 +28,7 @@ dictionary with two keys:
28
28
  - `'translate_content'`: Function to translate `AIMessage` content.
29
29
  - `'translate_content_chunk'`: Function to translate `AIMessageChunk` content.
30
30
 
31
- When calling `.content_blocks` on an `AIMessage` or `AIMessageChunk`, if
31
+ When calling `content_blocks` on an `AIMessage` or `AIMessageChunk`, if
32
32
  `model_provider` is set in `response_metadata`, the corresponding translator
33
33
  functions will be used to parse the content into blocks. Otherwise, best-effort parsing
34
34
  in `BaseMessage` will be used.
@@ -31,7 +31,7 @@ def _convert_to_v1_from_anthropic_input(
31
31
  ) -> list[types.ContentBlock]:
32
32
  """Convert Anthropic format blocks to v1 format.
33
33
 
34
- During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1
34
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
35
35
  block as a `'non_standard'` block with the original block stored in the `value`
36
36
  field. This function attempts to unpack those blocks and convert any blocks that
37
37
  might be Anthropic format to v1 ContentBlocks.
@@ -35,7 +35,7 @@ def _convert_to_v1_from_converse_input(
35
35
  ) -> list[types.ContentBlock]:
36
36
  """Convert Bedrock Converse format blocks to v1 format.
37
37
 
38
- During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1
38
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
39
39
  block as a `'non_standard'` block with the original block stored in the `value`
40
40
  field. This function attempts to unpack those blocks and convert any blocks that
41
41
  might be Converse format to v1 ContentBlocks.