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
@@ -15,19 +15,20 @@ from langchain_core.utils._merge import merge_dicts
15
15
  class FunctionMessage(BaseMessage):
16
16
  """Message for passing the result of executing a tool back to a model.
17
17
 
18
- FunctionMessage are an older version of the ToolMessage schema, and
19
- do not contain the tool_call_id field.
18
+ `FunctionMessage` are an older version of the `ToolMessage` schema, and
19
+ do not contain the `tool_call_id` field.
20
20
 
21
- The tool_call_id field is used to associate the tool call request with the
22
- tool call response. This is useful in situations where a chat model is able
21
+ The `tool_call_id` field is used to associate the tool call request with the
22
+ tool call response. Useful in situations where a chat model is able
23
23
  to request multiple tool calls in parallel.
24
+
24
25
  """
25
26
 
26
27
  name: str
27
28
  """The name of the function that was executed."""
28
29
 
29
30
  type: Literal["function"] = "function"
30
- """The type of the message (used for serialization). Defaults to "function"."""
31
+ """The type of the message (used for serialization)."""
31
32
 
32
33
 
33
34
  class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
@@ -37,8 +38,7 @@ class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
37
38
  # to make sure that the chunk variant can be discriminated from the
38
39
  # non-chunk variant.
39
40
  type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" # type: ignore[assignment]
40
- """The type of the message (used for serialization).
41
- Defaults to "FunctionMessageChunk"."""
41
+ """The type of the message (used for serialization)."""
42
42
 
43
43
  @override
44
44
  def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
@@ -1,56 +1,63 @@
1
1
  """Human message."""
2
2
 
3
- from typing import Any, Literal, Union
3
+ from typing import Any, Literal, cast, overload
4
4
 
5
+ from langchain_core.messages import content as types
5
6
  from langchain_core.messages.base import BaseMessage, BaseMessageChunk
6
7
 
7
8
 
8
9
  class HumanMessage(BaseMessage):
9
- """Message from a human.
10
+ """Message from the user.
10
11
 
11
- HumanMessages are messages that are passed in from a human to the model.
12
+ A `HumanMessage` is a message that is passed in from a user to the model.
12
13
 
13
14
  Example:
14
-
15
- .. code-block:: python
16
-
17
- from langchain_core.messages import HumanMessage, SystemMessage
18
-
19
- messages = [
20
- SystemMessage(
21
- content="You are a helpful assistant! Your name is Bob."
22
- ),
23
- HumanMessage(
24
- content="What is your name?"
25
- )
26
- ]
27
-
28
- # Instantiate a chat model and invoke it with the messages
29
- model = ...
30
- print(model.invoke(messages))
31
-
15
+ ```python
16
+ from langchain_core.messages import HumanMessage, SystemMessage
17
+
18
+ messages = [
19
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
20
+ HumanMessage(content="What is your name?"),
21
+ ]
22
+
23
+ # Instantiate a chat model and invoke it with the messages
24
+ model = ...
25
+ print(model.invoke(messages))
26
+ ```
32
27
  """
33
28
 
34
- example: bool = False
35
- """Use to denote that a message is part of an example conversation.
29
+ type: Literal["human"] = "human"
30
+ """The type of the message (used for serialization)."""
36
31
 
37
- At the moment, this is ignored by most models. Usage is discouraged.
38
- Defaults to False.
39
- """
32
+ @overload
33
+ def __init__(
34
+ self,
35
+ content: str | list[str | dict],
36
+ **kwargs: Any,
37
+ ) -> None: ...
40
38
 
41
- type: Literal["human"] = "human"
42
- """The type of the message (used for serialization). Defaults to "human"."""
39
+ @overload
40
+ def __init__(
41
+ self,
42
+ content: str | list[str | dict] | None = None,
43
+ content_blocks: list[types.ContentBlock] | None = None,
44
+ **kwargs: Any,
45
+ ) -> None: ...
43
46
 
44
47
  def __init__(
45
- self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
48
+ self,
49
+ content: str | list[str | dict] | None = None,
50
+ content_blocks: list[types.ContentBlock] | None = None,
51
+ **kwargs: Any,
46
52
  ) -> None:
47
- """Pass in content as positional arg.
48
-
49
- Args:
50
- content: The string contents of the message.
51
- kwargs: Additional fields to pass to the message.
52
- """
53
- super().__init__(content=content, **kwargs)
53
+ """Specify `content` as positional arg or `content_blocks` for typing."""
54
+ if content_blocks is not None:
55
+ super().__init__(
56
+ content=cast("str | list[str | dict]", content_blocks),
57
+ **kwargs,
58
+ )
59
+ else:
60
+ super().__init__(content=content, **kwargs)
54
61
 
55
62
 
56
63
  class HumanMessageChunk(HumanMessage, BaseMessageChunk):
@@ -60,5 +67,4 @@ class HumanMessageChunk(HumanMessage, BaseMessageChunk):
60
67
  # to make sure that the chunk variant can be discriminated from the
61
68
  # non-chunk variant.
62
69
  type: Literal["HumanMessageChunk"] = "HumanMessageChunk" # type: ignore[assignment]
63
- """The type of the message (used for serialization).
64
- Defaults to "HumanMessageChunk"."""
70
+ """The type of the message (used for serialization)."""
@@ -9,7 +9,7 @@ class RemoveMessage(BaseMessage):
9
9
  """Message responsible for deleting other messages."""
10
10
 
11
11
  type: Literal["remove"] = "remove"
12
- """The type of the message (used for serialization). Defaults to "remove"."""
12
+ """The type of the message (used for serialization)."""
13
13
 
14
14
  def __init__(
15
15
  self,
@@ -20,10 +20,11 @@ class RemoveMessage(BaseMessage):
20
20
 
21
21
  Args:
22
22
  id: The ID of the message to remove.
23
- kwargs: Additional fields to pass to the message.
23
+ **kwargs: Additional fields to pass to the message.
24
24
 
25
25
  Raises:
26
26
  ValueError: If the 'content' field is passed in kwargs.
27
+
27
28
  """
28
29
  if kwargs.pop("content", None):
29
30
  msg = "RemoveMessage does not support 'content' field."
@@ -1,7 +1,8 @@
1
1
  """System message."""
2
2
 
3
- from typing import Any, Literal, Union
3
+ from typing import Any, Literal, cast, overload
4
4
 
5
+ from langchain_core.messages import content as types
5
6
  from langchain_core.messages.base import BaseMessage, BaseMessageChunk
6
7
 
7
8
 
@@ -12,38 +13,51 @@ class SystemMessage(BaseMessage):
12
13
  of input messages.
13
14
 
14
15
  Example:
16
+ ```python
17
+ from langchain_core.messages import HumanMessage, SystemMessage
15
18
 
16
- .. code-block:: python
17
-
18
- from langchain_core.messages import HumanMessage, SystemMessage
19
-
20
- messages = [
21
- SystemMessage(
22
- content="You are a helpful assistant! Your name is Bob."
23
- ),
24
- HumanMessage(
25
- content="What is your name?"
26
- )
27
- ]
28
-
29
- # Define a chat model and invoke it with the messages
30
- print(model.invoke(messages))
19
+ messages = [
20
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
21
+ HumanMessage(content="What is your name?"),
22
+ ]
31
23
 
24
+ # Define a chat model and invoke it with the messages
25
+ print(model.invoke(messages))
26
+ ```
32
27
  """
33
28
 
34
29
  type: Literal["system"] = "system"
35
- """The type of the message (used for serialization). Defaults to "system"."""
30
+ """The type of the message (used for serialization)."""
36
31
 
32
+ @overload
37
33
  def __init__(
38
- self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
39
- ) -> None:
40
- """Pass in content as positional arg.
34
+ self,
35
+ content: str | list[str | dict],
36
+ **kwargs: Any,
37
+ ) -> None: ...
41
38
 
42
- Args:
43
- content: The string contents of the message.
44
- kwargs: Additional fields to pass to the message.
45
- """
46
- super().__init__(content=content, **kwargs)
39
+ @overload
40
+ def __init__(
41
+ self,
42
+ content: str | list[str | dict] | None = None,
43
+ content_blocks: list[types.ContentBlock] | None = None,
44
+ **kwargs: Any,
45
+ ) -> None: ...
46
+
47
+ def __init__(
48
+ self,
49
+ content: str | list[str | dict] | None = None,
50
+ content_blocks: list[types.ContentBlock] | None = None,
51
+ **kwargs: Any,
52
+ ) -> None:
53
+ """Specify `content` as positional arg or `content_blocks` for typing."""
54
+ if content_blocks is not None:
55
+ super().__init__(
56
+ content=cast("str | list[str | dict]", content_blocks),
57
+ **kwargs,
58
+ )
59
+ else:
60
+ super().__init__(content=content, **kwargs)
47
61
 
48
62
 
49
63
  class SystemMessageChunk(SystemMessage, BaseMessageChunk):
@@ -53,5 +67,4 @@ class SystemMessageChunk(SystemMessage, BaseMessageChunk):
53
67
  # to make sure that the chunk variant can be discriminated from the
54
68
  # non-chunk variant.
55
69
  type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
56
- """The type of the message (used for serialization).
57
- Defaults to "SystemMessageChunk"."""
70
+ """The type of the message (used for serialization)."""
@@ -1,75 +1,73 @@
1
1
  """Messages for tools."""
2
2
 
3
3
  import json
4
- from typing import Any, Literal, Optional, Union
4
+ from typing import Any, Literal, cast, overload
5
5
  from uuid import UUID
6
6
 
7
7
  from pydantic import Field, model_validator
8
- from typing_extensions import override
8
+ from typing_extensions import NotRequired, TypedDict, override
9
9
 
10
+ from langchain_core.messages import content as types
10
11
  from langchain_core.messages.base import BaseMessage, BaseMessageChunk, merge_content
11
- from langchain_core.messages.content_blocks import InvalidToolCall as InvalidToolCall
12
- from langchain_core.messages.content_blocks import ToolCall as ToolCall
13
- from langchain_core.messages.content_blocks import ToolCallChunk as ToolCallChunk
12
+ from langchain_core.messages.content import InvalidToolCall
14
13
  from langchain_core.utils._merge import merge_dicts, merge_obj
15
14
 
16
15
 
17
16
  class ToolOutputMixin:
18
17
  """Mixin for objects that tools can return directly.
19
18
 
20
- If a custom BaseTool is invoked with a ToolCall and the output of custom code is
21
- not an instance of ToolOutputMixin, the output will automatically be coerced to a
22
- string and wrapped in a ToolMessage.
19
+ If a custom BaseTool is invoked with a `ToolCall` and the output of custom code is
20
+ not an instance of `ToolOutputMixin`, the output will automatically be coerced to
21
+ a string and wrapped in a `ToolMessage`.
22
+
23
23
  """
24
24
 
25
25
 
26
26
  class ToolMessage(BaseMessage, ToolOutputMixin):
27
27
  """Message for passing the result of executing a tool back to a model.
28
28
 
29
- ToolMessages contain the result of a tool invocation. Typically, the result
29
+ `ToolMessage` objects contain the result of a tool invocation. Typically, the result
30
30
  is encoded inside the `content` field.
31
31
 
32
- Example: A ToolMessage representing a result of 42 from a tool call with id
33
-
34
- .. code-block:: python
35
-
36
- from langchain_core.messages import ToolMessage
32
+ Example: A `ToolMessage` representing a result of `42` from a tool call with id
37
33
 
38
- ToolMessage(content='42', tool_call_id='call_Jja7J89XsjrOLA5r!MEOW!SL')
34
+ ```python
35
+ from langchain_core.messages import ToolMessage
39
36
 
37
+ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
38
+ ```
40
39
 
41
- Example: A ToolMessage where only part of the tool output is sent to the model
42
- and the full output is passed in to artifact.
40
+ Example: A `ToolMessage` where only part of the tool output is sent to the model
41
+ and the full output is passed in to artifact.
43
42
 
44
- .. versionadded:: 0.2.17
43
+ ```python
44
+ from langchain_core.messages import ToolMessage
45
45
 
46
- .. code-block:: python
46
+ tool_output = {
47
+ "stdout": "From the graph we can see that the correlation between "
48
+ "x and y is ...",
49
+ "stderr": None,
50
+ "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
51
+ }
47
52
 
48
- from langchain_core.messages import ToolMessage
49
-
50
- tool_output = {
51
- "stdout": "From the graph we can see that the correlation between x and y is ...",
52
- "stderr": None,
53
- "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
54
- }
55
-
56
- ToolMessage(
57
- content=tool_output["stdout"],
58
- artifact=tool_output,
59
- tool_call_id='call_Jja7J89XsjrOLA5r!MEOW!SL',
60
- )
53
+ ToolMessage(
54
+ content=tool_output["stdout"],
55
+ artifact=tool_output,
56
+ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
57
+ )
58
+ ```
61
59
 
62
- The tool_call_id field is used to associate the tool call request with the
63
- tool call response. This is useful in situations where a chat model is able
60
+ The `tool_call_id` field is used to associate the tool call request with the
61
+ tool call response. Useful in situations where a chat model is able
64
62
  to request multiple tool calls in parallel.
65
63
 
66
- """ # noqa: E501
64
+ """
67
65
 
68
66
  tool_call_id: str
69
67
  """Tool call that this message is responding to."""
70
68
 
71
69
  type: Literal["tool"] = "tool"
72
- """The type of the message (used for serialization). Defaults to "tool"."""
70
+ """The type of the message (used for serialization)."""
73
71
 
74
72
  artifact: Any = None
75
73
  """Artifact of the Tool execution which is not meant to be sent to the model.
@@ -78,19 +76,15 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
78
76
  a subset of the full tool output is being passed as message content but the full
79
77
  output is needed in other parts of the code.
80
78
 
81
- .. versionadded:: 0.2.17
82
79
  """
83
80
 
84
81
  status: Literal["success", "error"] = "success"
85
- """Status of the tool invocation.
86
-
87
- .. versionadded:: 0.2.24
88
- """
82
+ """Status of the tool invocation."""
89
83
 
90
84
  additional_kwargs: dict = Field(default_factory=dict, repr=False)
91
- """Currently inherited from BaseMessage, but not used."""
85
+ """Currently inherited from `BaseMessage`, but not used."""
92
86
  response_metadata: dict = Field(default_factory=dict, repr=False)
93
- """Currently inherited from BaseMessage, but not used."""
87
+ """Currently inherited from `BaseMessage`, but not used."""
94
88
 
95
89
  @model_validator(mode="before")
96
90
  @classmethod
@@ -99,6 +93,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
99
93
 
100
94
  Args:
101
95
  values: The model arguments.
96
+
102
97
  """
103
98
  content = values["content"]
104
99
  if isinstance(content, tuple):
@@ -136,16 +131,43 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
136
131
  values["tool_call_id"] = str(tool_call_id)
137
132
  return values
138
133
 
134
+ @overload
139
135
  def __init__(
140
- self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
136
+ self,
137
+ content: str | list[str | dict],
138
+ **kwargs: Any,
139
+ ) -> None: ...
140
+
141
+ @overload
142
+ def __init__(
143
+ self,
144
+ content: str | list[str | dict] | None = None,
145
+ content_blocks: list[types.ContentBlock] | None = None,
146
+ **kwargs: Any,
147
+ ) -> None: ...
148
+
149
+ def __init__(
150
+ self,
151
+ content: str | list[str | dict] | None = None,
152
+ content_blocks: list[types.ContentBlock] | None = None,
153
+ **kwargs: Any,
141
154
  ) -> None:
142
- """Create a ToolMessage.
155
+ """Initialize a `ToolMessage`.
156
+
157
+ Specify `content` as positional arg or `content_blocks` for typing.
143
158
 
144
159
  Args:
145
- content: The string contents of the message.
160
+ content: The contents of the message.
161
+ content_blocks: Typed standard content.
146
162
  **kwargs: Additional fields.
147
163
  """
148
- super().__init__(content=content, **kwargs)
164
+ if content_blocks is not None:
165
+ super().__init__(
166
+ content=cast("str | list[str | dict]", content_blocks),
167
+ **kwargs,
168
+ )
169
+ else:
170
+ super().__init__(content=content, **kwargs)
149
171
 
150
172
 
151
173
  class ToolMessageChunk(ToolMessage, BaseMessageChunk):
@@ -180,11 +202,38 @@ class ToolMessageChunk(ToolMessage, BaseMessageChunk):
180
202
  return super().__add__(other)
181
203
 
182
204
 
205
+ class ToolCall(TypedDict):
206
+ """Represents an AI's request to call a tool.
207
+
208
+ Example:
209
+ ```python
210
+ {"name": "foo", "args": {"a": 1}, "id": "123"}
211
+ ```
212
+
213
+ This represents a request to call the tool named `'foo'` with arguments
214
+ `{"a": 1}` and an identifier of `'123'`.
215
+
216
+ """
217
+
218
+ name: str
219
+ """The name of the tool to be called."""
220
+ args: dict[str, Any]
221
+ """The arguments to the tool call."""
222
+ id: str | None
223
+ """An identifier associated with the tool call.
224
+
225
+ An identifier is needed to associate a tool call request with a tool
226
+ call result in events when multiple concurrent tool calls are made.
227
+
228
+ """
229
+ type: NotRequired[Literal["tool_call"]]
230
+
231
+
183
232
  def tool_call(
184
233
  *,
185
234
  name: str,
186
235
  args: dict[str, Any],
187
- id: Optional[str],
236
+ id: str | None,
188
237
  ) -> ToolCall:
189
238
  """Create a tool call.
190
239
 
@@ -192,16 +241,49 @@ def tool_call(
192
241
  name: The name of the tool to be called.
193
242
  args: The arguments to the tool call.
194
243
  id: An identifier associated with the tool call.
244
+
245
+ Returns:
246
+ The created tool call.
195
247
  """
196
248
  return ToolCall(name=name, args=args, id=id, type="tool_call")
197
249
 
198
250
 
251
+ class ToolCallChunk(TypedDict):
252
+ """A chunk of a tool call (yielded when streaming).
253
+
254
+ When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
255
+ all string attributes are concatenated. Chunks are only merged if their
256
+ values of `index` are equal and not None.
257
+
258
+ Example:
259
+ ```python
260
+ left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
261
+ right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
262
+
263
+ (
264
+ AIMessageChunk(content="", tool_call_chunks=left_chunks)
265
+ + AIMessageChunk(content="", tool_call_chunks=right_chunks)
266
+ ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
267
+ ```
268
+ """
269
+
270
+ name: str | None
271
+ """The name of the tool to be called."""
272
+ args: str | None
273
+ """The arguments to the tool call."""
274
+ id: str | None
275
+ """An identifier associated with the tool call."""
276
+ index: int | None
277
+ """The index of the tool call in a sequence."""
278
+ type: NotRequired[Literal["tool_call_chunk"]]
279
+
280
+
199
281
  def tool_call_chunk(
200
282
  *,
201
- name: Optional[str] = None,
202
- args: Optional[str] = None,
203
- id: Optional[str] = None,
204
- index: Optional[int] = None,
283
+ name: str | None = None,
284
+ args: str | None = None,
285
+ id: str | None = None,
286
+ index: int | None = None,
205
287
  ) -> ToolCallChunk:
206
288
  """Create a tool call chunk.
207
289
 
@@ -210,6 +292,9 @@ def tool_call_chunk(
210
292
  args: The arguments to the tool call.
211
293
  id: An identifier associated with the tool call.
212
294
  index: The index of the tool call in a sequence.
295
+
296
+ Returns:
297
+ The created tool call chunk.
213
298
  """
214
299
  return ToolCallChunk(
215
300
  name=name, args=args, id=id, index=index, type="tool_call_chunk"
@@ -218,10 +303,10 @@ def tool_call_chunk(
218
303
 
219
304
  def invalid_tool_call(
220
305
  *,
221
- name: Optional[str] = None,
222
- args: Optional[str] = None,
223
- id: Optional[str] = None,
224
- error: Optional[str] = None,
306
+ name: str | None = None,
307
+ args: str | None = None,
308
+ id: str | None = None,
309
+ error: str | None = None,
225
310
  ) -> InvalidToolCall:
226
311
  """Create an invalid tool call.
227
312
 
@@ -230,6 +315,9 @@ def invalid_tool_call(
230
315
  args: The arguments to the tool call.
231
316
  id: An identifier associated with the tool call.
232
317
  error: An error message associated with the tool call.
318
+
319
+ Returns:
320
+ The created invalid tool call.
233
321
  """
234
322
  return InvalidToolCall(
235
323
  name=name, args=args, id=id, error=error, type="invalid_tool_call"
@@ -239,7 +327,14 @@ def invalid_tool_call(
239
327
  def default_tool_parser(
240
328
  raw_tool_calls: list[dict],
241
329
  ) -> tuple[list[ToolCall], list[InvalidToolCall]]:
242
- """Best-effort parsing of tools."""
330
+ """Best-effort parsing of tools.
331
+
332
+ Args:
333
+ raw_tool_calls: List of raw tool call dicts to parse.
334
+
335
+ Returns:
336
+ A list of tool calls and invalid tool calls.
337
+ """
243
338
  tool_calls = []
244
339
  invalid_tool_calls = []
245
340
  for raw_tool_call in raw_tool_calls:
@@ -267,7 +362,14 @@ def default_tool_parser(
267
362
 
268
363
 
269
364
  def default_tool_chunk_parser(raw_tool_calls: list[dict]) -> list[ToolCallChunk]:
270
- """Best-effort parsing of tool chunks."""
365
+ """Best-effort parsing of tool chunks.
366
+
367
+ Args:
368
+ raw_tool_calls: List of raw tool call dicts to parse.
369
+
370
+ Returns:
371
+ List of parsed ToolCallChunk objects.
372
+ """
271
373
  tool_call_chunks = []
272
374
  for tool_call in raw_tool_calls:
273
375
  if "function" not in tool_call: