langchain-core 1.0.0a5__py3-none-any.whl → 1.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +23 -26
  4. langchain_core/_api/deprecation.py +51 -64
  5. langchain_core/_api/path.py +3 -6
  6. langchain_core/_import_utils.py +3 -4
  7. langchain_core/agents.py +20 -22
  8. langchain_core/caches.py +65 -66
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +321 -336
  11. langchain_core/callbacks/file.py +44 -44
  12. langchain_core/callbacks/manager.py +436 -513
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +32 -32
  15. langchain_core/callbacks/usage.py +60 -57
  16. langchain_core/chat_history.py +53 -68
  17. langchain_core/document_loaders/base.py +27 -25
  18. langchain_core/document_loaders/blob_loaders.py +1 -1
  19. langchain_core/document_loaders/langsmith.py +44 -48
  20. langchain_core/documents/__init__.py +23 -3
  21. langchain_core/documents/base.py +98 -90
  22. langchain_core/documents/compressor.py +10 -10
  23. langchain_core/documents/transformers.py +34 -35
  24. langchain_core/embeddings/fake.py +50 -54
  25. langchain_core/example_selectors/length_based.py +1 -1
  26. langchain_core/example_selectors/semantic_similarity.py +28 -32
  27. langchain_core/exceptions.py +21 -20
  28. langchain_core/globals.py +3 -151
  29. langchain_core/indexing/__init__.py +1 -1
  30. langchain_core/indexing/api.py +121 -126
  31. langchain_core/indexing/base.py +73 -75
  32. langchain_core/indexing/in_memory.py +4 -6
  33. langchain_core/language_models/__init__.py +14 -29
  34. langchain_core/language_models/_utils.py +58 -61
  35. langchain_core/language_models/base.py +53 -162
  36. langchain_core/language_models/chat_models.py +298 -387
  37. langchain_core/language_models/fake.py +11 -11
  38. langchain_core/language_models/fake_chat_models.py +42 -36
  39. langchain_core/language_models/llms.py +125 -235
  40. langchain_core/load/dump.py +9 -12
  41. langchain_core/load/load.py +18 -28
  42. langchain_core/load/mapping.py +2 -4
  43. langchain_core/load/serializable.py +42 -40
  44. langchain_core/messages/__init__.py +10 -16
  45. langchain_core/messages/ai.py +148 -148
  46. langchain_core/messages/base.py +58 -52
  47. langchain_core/messages/block_translators/__init__.py +27 -17
  48. langchain_core/messages/block_translators/anthropic.py +6 -6
  49. langchain_core/messages/block_translators/bedrock_converse.py +5 -5
  50. langchain_core/messages/block_translators/google_genai.py +505 -20
  51. langchain_core/messages/block_translators/google_vertexai.py +4 -32
  52. langchain_core/messages/block_translators/groq.py +117 -21
  53. langchain_core/messages/block_translators/langchain_v0.py +5 -5
  54. langchain_core/messages/block_translators/openai.py +11 -11
  55. langchain_core/messages/chat.py +2 -6
  56. langchain_core/messages/content.py +337 -328
  57. langchain_core/messages/function.py +6 -10
  58. langchain_core/messages/human.py +24 -31
  59. langchain_core/messages/modifier.py +2 -2
  60. langchain_core/messages/system.py +19 -29
  61. langchain_core/messages/tool.py +74 -90
  62. langchain_core/messages/utils.py +474 -504
  63. langchain_core/output_parsers/__init__.py +13 -10
  64. langchain_core/output_parsers/base.py +61 -61
  65. langchain_core/output_parsers/format_instructions.py +9 -4
  66. langchain_core/output_parsers/json.py +12 -10
  67. langchain_core/output_parsers/list.py +21 -23
  68. langchain_core/output_parsers/openai_functions.py +49 -47
  69. langchain_core/output_parsers/openai_tools.py +16 -21
  70. langchain_core/output_parsers/pydantic.py +13 -14
  71. langchain_core/output_parsers/string.py +5 -5
  72. langchain_core/output_parsers/transform.py +15 -17
  73. langchain_core/output_parsers/xml.py +35 -34
  74. langchain_core/outputs/__init__.py +1 -1
  75. langchain_core/outputs/chat_generation.py +18 -18
  76. langchain_core/outputs/chat_result.py +1 -3
  77. langchain_core/outputs/generation.py +10 -11
  78. langchain_core/outputs/llm_result.py +10 -10
  79. langchain_core/prompt_values.py +11 -17
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +48 -56
  82. langchain_core/prompts/chat.py +275 -325
  83. langchain_core/prompts/dict.py +5 -5
  84. langchain_core/prompts/few_shot.py +81 -88
  85. langchain_core/prompts/few_shot_with_templates.py +11 -13
  86. langchain_core/prompts/image.py +12 -14
  87. langchain_core/prompts/loading.py +4 -6
  88. langchain_core/prompts/message.py +3 -3
  89. langchain_core/prompts/prompt.py +24 -39
  90. langchain_core/prompts/string.py +26 -10
  91. langchain_core/prompts/structured.py +49 -53
  92. langchain_core/rate_limiters.py +51 -60
  93. langchain_core/retrievers.py +61 -198
  94. langchain_core/runnables/base.py +1478 -1630
  95. langchain_core/runnables/branch.py +53 -57
  96. langchain_core/runnables/config.py +72 -89
  97. langchain_core/runnables/configurable.py +120 -137
  98. langchain_core/runnables/fallbacks.py +83 -79
  99. langchain_core/runnables/graph.py +91 -97
  100. langchain_core/runnables/graph_ascii.py +27 -28
  101. langchain_core/runnables/graph_mermaid.py +38 -50
  102. langchain_core/runnables/graph_png.py +15 -16
  103. langchain_core/runnables/history.py +135 -148
  104. langchain_core/runnables/passthrough.py +124 -150
  105. langchain_core/runnables/retry.py +46 -51
  106. langchain_core/runnables/router.py +25 -30
  107. langchain_core/runnables/schema.py +75 -80
  108. langchain_core/runnables/utils.py +60 -67
  109. langchain_core/stores.py +85 -121
  110. langchain_core/structured_query.py +8 -8
  111. langchain_core/sys_info.py +27 -29
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +285 -229
  114. langchain_core/tools/convert.py +160 -155
  115. langchain_core/tools/render.py +10 -10
  116. langchain_core/tools/retriever.py +12 -11
  117. langchain_core/tools/simple.py +19 -24
  118. langchain_core/tools/structured.py +32 -39
  119. langchain_core/tracers/__init__.py +1 -9
  120. langchain_core/tracers/base.py +97 -99
  121. langchain_core/tracers/context.py +29 -52
  122. langchain_core/tracers/core.py +49 -53
  123. langchain_core/tracers/evaluation.py +11 -11
  124. langchain_core/tracers/event_stream.py +65 -64
  125. langchain_core/tracers/langchain.py +21 -21
  126. langchain_core/tracers/log_stream.py +45 -45
  127. langchain_core/tracers/memory_stream.py +3 -3
  128. langchain_core/tracers/root_listeners.py +16 -16
  129. langchain_core/tracers/run_collector.py +2 -4
  130. langchain_core/tracers/schemas.py +0 -129
  131. langchain_core/tracers/stdout.py +3 -3
  132. langchain_core/utils/__init__.py +1 -4
  133. langchain_core/utils/_merge.py +2 -2
  134. langchain_core/utils/aiter.py +57 -61
  135. langchain_core/utils/env.py +9 -9
  136. langchain_core/utils/function_calling.py +89 -186
  137. langchain_core/utils/html.py +7 -8
  138. langchain_core/utils/input.py +6 -6
  139. langchain_core/utils/interactive_env.py +1 -1
  140. langchain_core/utils/iter.py +36 -40
  141. langchain_core/utils/json.py +4 -3
  142. langchain_core/utils/json_schema.py +9 -9
  143. langchain_core/utils/mustache.py +8 -10
  144. langchain_core/utils/pydantic.py +33 -35
  145. langchain_core/utils/strings.py +6 -9
  146. langchain_core/utils/usage.py +1 -1
  147. langchain_core/utils/utils.py +66 -62
  148. langchain_core/vectorstores/base.py +182 -216
  149. langchain_core/vectorstores/in_memory.py +101 -176
  150. langchain_core/vectorstores/utils.py +5 -5
  151. langchain_core/version.py +1 -1
  152. langchain_core-1.0.3.dist-info/METADATA +69 -0
  153. langchain_core-1.0.3.dist-info/RECORD +172 -0
  154. {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.3.dist-info}/WHEEL +1 -1
  155. langchain_core/memory.py +0 -120
  156. langchain_core/messages/block_translators/ollama.py +0 -47
  157. langchain_core/prompts/pipeline.py +0 -138
  158. langchain_core/pydantic_v1/__init__.py +0 -30
  159. langchain_core/pydantic_v1/dataclasses.py +0 -23
  160. langchain_core/pydantic_v1/main.py +0 -23
  161. langchain_core/tracers/langchain_v1.py +0 -31
  162. langchain_core/utils/loading.py +0 -35
  163. langchain_core-1.0.0a5.dist-info/METADATA +0 -77
  164. langchain_core-1.0.0a5.dist-info/RECORD +0 -181
  165. langchain_core-1.0.0a5.dist-info/entry_points.txt +0 -4
@@ -1,7 +1,8 @@
1
1
  """Convert functions and runnables to tools."""
2
2
 
3
3
  import inspect
4
- from typing import Any, Callable, Literal, Optional, Union, get_type_hints, overload
4
+ from collections.abc import Callable
5
+ from typing import Any, Literal, get_type_hints, overload
5
6
 
6
7
  from pydantic import BaseModel, Field, create_model
7
8
 
@@ -15,14 +16,14 @@ from langchain_core.tools.structured import StructuredTool
15
16
  @overload
16
17
  def tool(
17
18
  *,
18
- description: Optional[str] = None,
19
+ description: str | None = None,
19
20
  return_direct: bool = False,
20
- args_schema: Optional[ArgsSchema] = None,
21
+ args_schema: ArgsSchema | None = None,
21
22
  infer_schema: bool = True,
22
23
  response_format: Literal["content", "content_and_artifact"] = "content",
23
24
  parse_docstring: bool = False,
24
25
  error_on_invalid_docstring: bool = True,
25
- ) -> Callable[[Union[Callable, Runnable]], BaseTool]: ...
26
+ ) -> Callable[[Callable | Runnable], BaseTool]: ...
26
27
 
27
28
 
28
29
  @overload
@@ -30,9 +31,9 @@ def tool(
30
31
  name_or_callable: str,
31
32
  runnable: Runnable,
32
33
  *,
33
- description: Optional[str] = None,
34
+ description: str | None = None,
34
35
  return_direct: bool = False,
35
- args_schema: Optional[ArgsSchema] = None,
36
+ args_schema: ArgsSchema | None = None,
36
37
  infer_schema: bool = True,
37
38
  response_format: Literal["content", "content_and_artifact"] = "content",
38
39
  parse_docstring: bool = False,
@@ -44,9 +45,9 @@ def tool(
44
45
  def tool(
45
46
  name_or_callable: Callable,
46
47
  *,
47
- description: Optional[str] = None,
48
+ description: str | None = None,
48
49
  return_direct: bool = False,
49
- args_schema: Optional[ArgsSchema] = None,
50
+ args_schema: ArgsSchema | None = None,
50
51
  infer_schema: bool = True,
51
52
  response_format: Literal["content", "content_and_artifact"] = "content",
52
53
  parse_docstring: bool = False,
@@ -58,180 +59,186 @@ def tool(
58
59
  def tool(
59
60
  name_or_callable: str,
60
61
  *,
61
- description: Optional[str] = None,
62
+ description: str | None = None,
62
63
  return_direct: bool = False,
63
- args_schema: Optional[ArgsSchema] = None,
64
+ args_schema: ArgsSchema | None = None,
64
65
  infer_schema: bool = True,
65
66
  response_format: Literal["content", "content_and_artifact"] = "content",
66
67
  parse_docstring: bool = False,
67
68
  error_on_invalid_docstring: bool = True,
68
- ) -> Callable[[Union[Callable, Runnable]], BaseTool]: ...
69
+ ) -> Callable[[Callable | Runnable], BaseTool]: ...
69
70
 
70
71
 
71
72
  def tool(
72
- name_or_callable: Optional[Union[str, Callable]] = None,
73
- runnable: Optional[Runnable] = None,
73
+ name_or_callable: str | Callable | None = None,
74
+ runnable: Runnable | None = None,
74
75
  *args: Any,
75
- description: Optional[str] = None,
76
+ description: str | None = None,
76
77
  return_direct: bool = False,
77
- args_schema: Optional[ArgsSchema] = None,
78
+ args_schema: ArgsSchema | None = None,
78
79
  infer_schema: bool = True,
79
80
  response_format: Literal["content", "content_and_artifact"] = "content",
80
81
  parse_docstring: bool = False,
81
82
  error_on_invalid_docstring: bool = True,
82
- ) -> Union[
83
- BaseTool,
84
- Callable[[Union[Callable, Runnable]], BaseTool],
85
- ]:
86
- """Make tools out of functions, can be used with or without arguments.
83
+ ) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
84
+ """Convert Python functions and `Runnables` to LangChain tools.
85
+
86
+ Can be used as a decorator with or without arguments to create tools from functions.
87
+
88
+ Functions can have any signature - the tool will automatically infer input schemas
89
+ unless disabled.
90
+
91
+ !!! note "Requirements"
92
+ - Functions must have type hints for proper schema inference
93
+ - When `infer_schema=False`, functions must be `(str) -> str` and have
94
+ docstrings
95
+ - When using with `Runnable`, a string name must be provided
87
96
 
88
97
  Args:
89
- name_or_callable: Optional name of the tool or the callable to be
90
- converted to a tool. Must be provided as a positional argument.
91
- runnable: Optional runnable to convert to a tool. Must be provided as a
92
- positional argument.
98
+ name_or_callable: Optional name of the tool or the `Callable` to be
99
+ converted to a tool. Overrides the function's name.
100
+
101
+ Must be provided as a positional argument.
102
+ runnable: Optional `Runnable` to convert to a tool.
103
+
104
+ Must be provided as a positional argument.
93
105
  description: Optional description for the tool.
106
+
94
107
  Precedence for the tool description value is as follows:
95
108
 
96
- - ``description`` argument
97
- (used even if docstring and/or ``args_schema`` are provided)
98
- - tool function docstring
99
- (used even if ``args_schema`` is provided)
100
- - ``args_schema`` description
101
- (used only if `description` / docstring are not provided)
109
+ - This `description` argument
110
+ (used even if docstring and/or `args_schema` are provided)
111
+ - Tool function docstring
112
+ (used even if `args_schema` is provided)
113
+ - `args_schema` description
114
+ (used only if `description` and docstring are not provided)
102
115
  *args: Extra positional arguments. Must be empty.
103
- return_direct: Whether to return directly from the tool rather
104
- than continuing the agent loop. Defaults to False.
105
- args_schema: optional argument schema for user to specify.
106
- Defaults to None.
107
- infer_schema: Whether to infer the schema of the arguments from
108
- the function's signature. This also makes the resultant tool
109
- accept a dictionary input to its `run()` function.
110
- Defaults to True.
111
- response_format: The tool response format. If "content" then the output of
112
- the tool is interpreted as the contents of a ToolMessage. If
113
- "content_and_artifact" then the output is expected to be a two-tuple
114
- corresponding to the (content, artifact) of a ToolMessage.
115
- Defaults to "content".
116
- parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt to
116
+ return_direct: Whether to return directly from the tool rather than continuing
117
+ the agent loop.
118
+ args_schema: Optional argument schema for user to specify.
119
+ infer_schema: Whether to infer the schema of the arguments from the function's
120
+ signature. This also makes the resultant tool accept a dictionary input to
121
+ its `run()` function.
122
+ response_format: The tool response format.
123
+
124
+ If `'content'`, then the output of the tool is interpreted as the contents
125
+ of a `ToolMessage`.
126
+
127
+ If `'content_and_artifact'`, then the output is expected to be a two-tuple
128
+ corresponding to the `(content, artifact)` of a `ToolMessage`.
129
+ parse_docstring: If `infer_schema` and `parse_docstring`, will attempt to
117
130
  parse parameter descriptions from Google Style function docstrings.
118
- Defaults to False.
119
- error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
120
- whether to raise ValueError on invalid Google Style docstrings.
121
- Defaults to True.
131
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
132
+ whether to raise `ValueError` on invalid Google Style docstrings.
122
133
 
123
134
  Raises:
124
- ValueError: If too many positional arguments are provided.
125
- ValueError: If a runnable is provided without a string name.
135
+ ValueError: If too many positional arguments are provided (e.g. violating the
136
+ `*args` constraint).
137
+ ValueError: If a `Runnable` is provided without a string name. When using `tool`
138
+ with a `Runnable`, a `str` name must be provided as the `name_or_callable`.
126
139
  ValueError: If the first argument is not a string or callable with
127
- a ``__name__`` attribute.
140
+ a `__name__` attribute.
128
141
  ValueError: If the function does not have a docstring and description
129
- is not provided and ``infer_schema`` is False.
130
- ValueError: If ``parse_docstring`` is True and the function has an invalid
131
- Google-style docstring and ``error_on_invalid_docstring`` is True.
132
- ValueError: If a Runnable is provided that does not have an object schema.
142
+ is not provided and `infer_schema` is `False`.
143
+ ValueError: If `parse_docstring` is `True` and the function has an invalid
144
+ Google-style docstring and `error_on_invalid_docstring` is True.
145
+ ValueError: If a `Runnable` is provided that does not have an object schema.
133
146
 
134
147
  Returns:
135
148
  The tool.
136
149
 
137
- Requires:
138
- - Function must be of type (str) -> str
139
- - Function must have a docstring
140
-
141
150
  Examples:
142
- .. code-block:: python
143
-
144
- @tool
145
- def search_api(query: str) -> str:
146
- # Searches the API for the query.
147
- return
148
-
151
+ ```python
152
+ @tool
153
+ def search_api(query: str) -> str:
154
+ # Searches the API for the query.
155
+ return
149
156
 
150
- @tool("search", return_direct=True)
151
- def search_api(query: str) -> str:
152
- # Searches the API for the query.
153
- return
154
157
 
158
+ @tool("search", return_direct=True)
159
+ def search_api(query: str) -> str:
160
+ # Searches the API for the query.
161
+ return
155
162
 
156
- @tool(response_format="content_and_artifact")
157
- def search_api(query: str) -> tuple[str, dict]:
158
- return "partial json of results", {"full": "object of results"}
159
163
 
160
- .. versionadded:: 0.2.14
164
+ @tool(response_format="content_and_artifact")
165
+ def search_api(query: str) -> tuple[str, dict]:
166
+ return "partial json of results", {"full": "object of results"}
167
+ ```
161
168
 
162
169
  Parse Google-style docstrings:
163
170
 
164
- .. code-block:: python
165
-
166
- @tool(parse_docstring=True)
167
- def foo(bar: str, baz: int) -> str:
168
- \"\"\"The foo.
169
-
170
- Args:
171
- bar: The bar.
172
- baz: The baz.
173
- \"\"\"
174
- return bar
175
-
176
- foo.args_schema.model_json_schema()
177
-
178
- .. code-block:: python
179
-
180
- {
181
- "title": "foo",
182
- "description": "The foo.",
183
- "type": "object",
184
- "properties": {
185
- "bar": {
186
- "title": "Bar",
187
- "description": "The bar.",
188
- "type": "string",
189
- },
190
- "baz": {
191
- "title": "Baz",
192
- "description": "The baz.",
193
- "type": "integer",
194
- },
171
+ ```python
172
+ @tool(parse_docstring=True)
173
+ def foo(bar: str, baz: int) -> str:
174
+ \"\"\"The foo.
175
+
176
+ Args:
177
+ bar: The bar.
178
+ baz: The baz.
179
+ \"\"\"
180
+ return bar
181
+
182
+ foo.args_schema.model_json_schema()
183
+ ```
184
+
185
+ ```python
186
+ {
187
+ "title": "foo",
188
+ "description": "The foo.",
189
+ "type": "object",
190
+ "properties": {
191
+ "bar": {
192
+ "title": "Bar",
193
+ "description": "The bar.",
194
+ "type": "string",
195
195
  },
196
- "required": ["bar", "baz"],
197
- }
196
+ "baz": {
197
+ "title": "Baz",
198
+ "description": "The baz.",
199
+ "type": "integer",
200
+ },
201
+ },
202
+ "required": ["bar", "baz"],
203
+ }
204
+ ```
198
205
 
199
- Note that parsing by default will raise ``ValueError`` if the docstring
206
+ Note that parsing by default will raise `ValueError` if the docstring
200
207
  is considered invalid. A docstring is considered invalid if it contains
201
208
  arguments not in the function signature, or is unable to be parsed into
202
- a summary and "Args:" blocks. Examples below:
203
-
204
- .. code-block:: python
205
-
206
- # No args section
207
- def invalid_docstring_1(bar: str, baz: int) -> str:
208
- \"\"\"The foo.\"\"\"
209
- return bar
210
-
211
- # Improper whitespace between summary and args section
212
- def invalid_docstring_2(bar: str, baz: int) -> str:
213
- \"\"\"The foo.
214
- Args:
215
- bar: The bar.
216
- baz: The baz.
217
- \"\"\"
218
- return bar
219
-
220
- # Documented args absent from function signature
221
- def invalid_docstring_3(bar: str, baz: int) -> str:
222
- \"\"\"The foo.
223
-
224
- Args:
225
- banana: The bar.
226
- monkey: The baz.
227
- \"\"\"
228
- return bar
229
-
209
+ a summary and `"Args:"` blocks. Examples below:
210
+
211
+ ```python
212
+ # No args section
213
+ def invalid_docstring_1(bar: str, baz: int) -> str:
214
+ \"\"\"The foo.\"\"\"
215
+ return bar
216
+
217
+ # Improper whitespace between summary and args section
218
+ def invalid_docstring_2(bar: str, baz: int) -> str:
219
+ \"\"\"The foo.
220
+ Args:
221
+ bar: The bar.
222
+ baz: The baz.
223
+ \"\"\"
224
+ return bar
225
+
226
+ # Documented args absent from function signature
227
+ def invalid_docstring_3(bar: str, baz: int) -> str:
228
+ \"\"\"The foo.
229
+
230
+ Args:
231
+ banana: The bar.
232
+ monkey: The baz.
233
+ \"\"\"
234
+ return bar
235
+
236
+ ```
230
237
  """ # noqa: D214, D410, D411 # We're intentionally showing bad formatting in examples
231
238
 
232
239
  def _create_tool_factory(
233
240
  tool_name: str,
234
- ) -> Callable[[Union[Callable, Runnable]], BaseTool]:
241
+ ) -> Callable[[Callable | Runnable], BaseTool]:
235
242
  """Create a decorator that takes a callable and returns a tool.
236
243
 
237
244
  Args:
@@ -241,7 +248,7 @@ def tool(
241
248
  A function that takes a callable or Runnable and returns a tool.
242
249
  """
243
250
 
244
- def _tool_factory(dec_func: Union[Callable, Runnable]) -> BaseTool:
251
+ def _tool_factory(dec_func: Callable | Runnable) -> BaseTool:
245
252
  tool_description = description
246
253
  if isinstance(dec_func, Runnable):
247
254
  runnable = dec_func
@@ -251,18 +258,18 @@ def tool(
251
258
  raise ValueError(msg)
252
259
 
253
260
  async def ainvoke_wrapper(
254
- callbacks: Optional[Callbacks] = None, **kwargs: Any
261
+ callbacks: Callbacks | None = None, **kwargs: Any
255
262
  ) -> Any:
256
263
  return await runnable.ainvoke(kwargs, {"callbacks": callbacks})
257
264
 
258
265
  def invoke_wrapper(
259
- callbacks: Optional[Callbacks] = None, **kwargs: Any
266
+ callbacks: Callbacks | None = None, **kwargs: Any
260
267
  ) -> Any:
261
268
  return runnable.invoke(kwargs, {"callbacks": callbacks})
262
269
 
263
270
  coroutine = ainvoke_wrapper
264
271
  func = invoke_wrapper
265
- schema: Optional[ArgsSchema] = runnable.input_schema
272
+ schema: ArgsSchema | None = runnable.input_schema
266
273
  tool_description = description or repr(runnable)
267
274
  elif inspect.iscoroutinefunction(dec_func):
268
275
  coroutine = dec_func
@@ -352,7 +359,7 @@ def tool(
352
359
  # @tool(parse_docstring=True)
353
360
  # def my_tool():
354
361
  # pass
355
- def _partial(func: Union[Callable, Runnable]) -> BaseTool:
362
+ def _partial(func: Callable | Runnable) -> BaseTool:
356
363
  """Partial function that takes a callable and returns a tool."""
357
364
  name_ = func.get_name() if isinstance(func, Runnable) else func.__name__
358
365
  tool_factory = _create_tool_factory(name_)
@@ -370,7 +377,7 @@ def _get_description_from_runnable(runnable: Runnable) -> str:
370
377
  def _get_schema_from_runnable_and_arg_types(
371
378
  runnable: Runnable,
372
379
  name: str,
373
- arg_types: Optional[dict[str, type]] = None,
380
+ arg_types: dict[str, type] | None = None,
374
381
  ) -> type[BaseModel]:
375
382
  """Infer args_schema for tool."""
376
383
  if arg_types is None:
@@ -389,20 +396,20 @@ def _get_schema_from_runnable_and_arg_types(
389
396
 
390
397
  def convert_runnable_to_tool(
391
398
  runnable: Runnable,
392
- args_schema: Optional[type[BaseModel]] = None,
399
+ args_schema: type[BaseModel] | None = None,
393
400
  *,
394
- name: Optional[str] = None,
395
- description: Optional[str] = None,
396
- arg_types: Optional[dict[str, type]] = None,
401
+ name: str | None = None,
402
+ description: str | None = None,
403
+ arg_types: dict[str, type] | None = None,
397
404
  ) -> BaseTool:
398
405
  """Convert a Runnable into a BaseTool.
399
406
 
400
407
  Args:
401
408
  runnable: The runnable to convert.
402
- args_schema: The schema for the tool's input arguments. Defaults to None.
403
- name: The name of the tool. Defaults to None.
404
- description: The description of the tool. Defaults to None.
405
- arg_types: The types of the arguments. Defaults to None.
409
+ args_schema: The schema for the tool's input arguments.
410
+ name: The name of the tool.
411
+ description: The description of the tool.
412
+ arg_types: The types of the arguments.
406
413
 
407
414
  Returns:
408
415
  The tool.
@@ -421,12 +428,10 @@ def convert_runnable_to_tool(
421
428
  description=description,
422
429
  )
423
430
 
424
- async def ainvoke_wrapper(
425
- callbacks: Optional[Callbacks] = None, **kwargs: Any
426
- ) -> Any:
431
+ async def ainvoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
427
432
  return await runnable.ainvoke(kwargs, config={"callbacks": callbacks})
428
433
 
429
- def invoke_wrapper(callbacks: Optional[Callbacks] = None, **kwargs: Any) -> Any:
434
+ def invoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
430
435
  return runnable.invoke(kwargs, config={"callbacks": callbacks})
431
436
 
432
437
  if (
@@ -2,8 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Callable
5
6
  from inspect import signature
6
- from typing import Callable
7
7
 
8
8
  from langchain_core.tools.base import BaseTool
9
9
 
@@ -21,10 +21,10 @@ def render_text_description(tools: list[BaseTool]) -> str:
21
21
 
22
22
  Output will be in the format of:
23
23
 
24
- .. code-block:: markdown
25
-
26
- search: This tool is used for search
27
- calculator: This tool is used for math
24
+ ```txt
25
+ search: This tool is used for search
26
+ calculator: This tool is used for math
27
+ ```
28
28
  """
29
29
  descriptions = []
30
30
  for tool in tools:
@@ -49,11 +49,11 @@ def render_text_description_and_args(tools: list[BaseTool]) -> str:
49
49
 
50
50
  Output will be in the format of:
51
51
 
52
- .. code-block:: markdown
53
-
54
- search: This tool is used for search, args: {"query": {"type": "string"}}
55
- calculator: This tool is used for math, \
56
- args: {"expression": {"type": "string"}}
52
+ ```txt
53
+ search: This tool is used for search, args: {"query": {"type": "string"}}
54
+ calculator: This tool is used for math, \
55
+ args: {"expression": {"type": "string"}}
56
+ ```
57
57
  """
58
58
  tool_strings = []
59
59
  for tool in tools:
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from functools import partial
6
- from typing import TYPE_CHECKING, Literal, Optional, Union
6
+ from typing import TYPE_CHECKING, Literal
7
7
 
8
8
  from pydantic import BaseModel, Field
9
9
 
@@ -34,7 +34,7 @@ def _get_relevant_documents(
34
34
  document_separator: str,
35
35
  callbacks: Callbacks = None,
36
36
  response_format: Literal["content", "content_and_artifact"] = "content",
37
- ) -> Union[str, tuple[str, list[Document]]]:
37
+ ) -> str | tuple[str, list[Document]]:
38
38
  docs = retriever.invoke(query, config={"callbacks": callbacks})
39
39
  content = document_separator.join(
40
40
  format_document(doc, document_prompt) for doc in docs
@@ -52,7 +52,7 @@ async def _aget_relevant_documents(
52
52
  document_separator: str,
53
53
  callbacks: Callbacks = None,
54
54
  response_format: Literal["content", "content_and_artifact"] = "content",
55
- ) -> Union[str, tuple[str, list[Document]]]:
55
+ ) -> str | tuple[str, list[Document]]:
56
56
  docs = await retriever.ainvoke(query, config={"callbacks": callbacks})
57
57
  content = document_separator.join(
58
58
  [await aformat_document(doc, document_prompt) for doc in docs]
@@ -69,7 +69,7 @@ def create_retriever_tool(
69
69
  name: str,
70
70
  description: str,
71
71
  *,
72
- document_prompt: Optional[BasePromptTemplate] = None,
72
+ document_prompt: BasePromptTemplate | None = None,
73
73
  document_separator: str = "\n\n",
74
74
  response_format: Literal["content", "content_and_artifact"] = "content",
75
75
  ) -> Tool:
@@ -81,13 +81,14 @@ def create_retriever_tool(
81
81
  so should be unique and somewhat descriptive.
82
82
  description: The description for the tool. This will be passed to the language
83
83
  model, so should be descriptive.
84
- document_prompt: The prompt to use for the document. Defaults to None.
85
- document_separator: The separator to use between documents. Defaults to "\n\n".
86
- response_format: The tool response format. If "content" then the output of
87
- the tool is interpreted as the contents of a ToolMessage. If
88
- "content_and_artifact" then the output is expected to be a two-tuple
89
- corresponding to the (content, artifact) of a ToolMessage (artifact
90
- being a list of documents in this case). Defaults to "content".
84
+ document_prompt: The prompt to use for the document.
85
+ document_separator: The separator to use between documents.
86
+ response_format: The tool response format.
87
+
88
+ If `"content"` then the output of the tool is interpreted as the contents of
89
+ a `ToolMessage`. If `"content_and_artifact"` then the output is expected to
90
+ be a two-tuple corresponding to the `(content, artifact)` of a `ToolMessage`
91
+ (artifact being a list of documents in this case).
91
92
 
92
93
  Returns:
93
94
  Tool class to pass to an agent.