langchain-core 1.0.0a6__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 +53 -51
  47. langchain_core/messages/block_translators/__init__.py +19 -22
  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 +10 -7
  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 +1476 -1626
  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 +284 -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.0a6.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.0a6.dist-info/METADATA +0 -67
  164. langchain_core-1.0.0a6.dist-info/RECORD +0 -181
  165. langchain_core-1.0.0a6.dist-info/entry_points.txt +0 -4
@@ -3,14 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import inspect
6
- from collections.abc import Sequence
6
+ from collections.abc import Callable, Sequence
7
7
  from types import GenericAlias
8
8
  from typing import (
9
9
  TYPE_CHECKING,
10
10
  Any,
11
- Callable,
12
- Optional,
13
- Union,
14
11
  )
15
12
 
16
13
  from pydantic import BaseModel
@@ -34,7 +31,7 @@ if TYPE_CHECKING:
34
31
  from langchain_core.tracers.schemas import Run
35
32
 
36
33
 
37
- MessagesOrDictWithMessages = Union[Sequence["BaseMessage"], dict[str, Any]]
34
+ MessagesOrDictWithMessages = Sequence["BaseMessage"] | dict[str, Any]
38
35
  GetSessionHistoryCallable = Callable[..., BaseChatMessageHistory]
39
36
 
40
37
 
@@ -60,22 +57,21 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
60
57
  In this case, the invocation would look like this:
61
58
 
62
59
  `with_history.invoke(..., config={"configurable": {"session_id": "bar"}})`
63
- ; e.g., ``{"configurable": {"session_id": "<SESSION_ID>"}}``.
60
+ ; e.g., `{"configurable": {"session_id": "<SESSION_ID>"}}`.
64
61
 
65
62
  The configuration can be customized by passing in a list of
66
- ``ConfigurableFieldSpec`` objects to the ``history_factory_config`` parameter (see
63
+ `ConfigurableFieldSpec` objects to the `history_factory_config` parameter (see
67
64
  example below).
68
65
 
69
66
  In the examples, we will use a chat message history with an in-memory
70
67
  implementation to make it easy to experiment and see the results.
71
68
 
72
69
  For production use cases, you will want to use a persistent implementation
73
- of chat message history, such as ``RedisChatMessageHistory``.
70
+ of chat message history, such as `RedisChatMessageHistory`.
74
71
 
75
72
  Example: Chat message history with an in-memory implementation for testing.
76
73
 
77
- .. code-block:: python
78
-
74
+ ```python
79
75
  from operator import itemgetter
80
76
 
81
77
  from langchain_openai.chat_models import ChatOpenAI
@@ -119,150 +115,143 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
119
115
  history.add_message(AIMessage(content="hello"))
120
116
  print(store) # noqa: T201
121
117
 
118
+ ```
122
119
 
123
120
  Example where the wrapped Runnable takes a dictionary input:
124
121
 
125
- .. code-block:: python
126
-
127
- from typing import Optional
122
+ ```python
123
+ from typing import Optional
128
124
 
129
- from langchain_community.chat_models import ChatAnthropic
130
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
131
- from langchain_core.runnables.history import RunnableWithMessageHistory
125
+ from langchain_community.chat_models import ChatAnthropic
126
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
127
+ from langchain_core.runnables.history import RunnableWithMessageHistory
132
128
 
133
129
 
134
- prompt = ChatPromptTemplate.from_messages(
135
- [
136
- ("system", "You're an assistant who's good at {ability}"),
137
- MessagesPlaceholder(variable_name="history"),
138
- ("human", "{question}"),
139
- ]
140
- )
130
+ prompt = ChatPromptTemplate.from_messages(
131
+ [
132
+ ("system", "You're an assistant who's good at {ability}"),
133
+ MessagesPlaceholder(variable_name="history"),
134
+ ("human", "{question}"),
135
+ ]
136
+ )
141
137
 
142
- chain = prompt | ChatAnthropic(model="claude-2")
138
+ chain = prompt | ChatAnthropic(model="claude-2")
143
139
 
144
- chain_with_history = RunnableWithMessageHistory(
145
- chain,
146
- # Uses the get_by_session_id function defined in the example
147
- # above.
148
- get_by_session_id,
149
- input_messages_key="question",
150
- history_messages_key="history",
151
- )
140
+ chain_with_history = RunnableWithMessageHistory(
141
+ chain,
142
+ # Uses the get_by_session_id function defined in the example
143
+ # above.
144
+ get_by_session_id,
145
+ input_messages_key="question",
146
+ history_messages_key="history",
147
+ )
152
148
 
153
- print(
154
- chain_with_history.invoke( # noqa: T201
155
- {"ability": "math", "question": "What does cosine mean?"},
156
- config={"configurable": {"session_id": "foo"}},
157
- )
149
+ print(
150
+ chain_with_history.invoke( # noqa: T201
151
+ {"ability": "math", "question": "What does cosine mean?"},
152
+ config={"configurable": {"session_id": "foo"}},
158
153
  )
154
+ )
159
155
 
160
- # Uses the store defined in the example above.
161
- print(store) # noqa: T201
156
+ # Uses the store defined in the example above.
157
+ print(store) # noqa: T201
162
158
 
163
- print(
164
- chain_with_history.invoke( # noqa: T201
165
- {"ability": "math", "question": "What's its inverse"},
166
- config={"configurable": {"session_id": "foo"}},
167
- )
159
+ print(
160
+ chain_with_history.invoke( # noqa: T201
161
+ {"ability": "math", "question": "What's its inverse"},
162
+ config={"configurable": {"session_id": "foo"}},
168
163
  )
164
+ )
169
165
 
170
- print(store) # noqa: T201
171
-
166
+ print(store) # noqa: T201
167
+ ```
172
168
 
173
169
  Example where the session factory takes two keys, user_id and conversation id):
174
170
 
175
- .. code-block:: python
176
-
177
- store = {}
171
+ ```python
172
+ store = {}
178
173
 
179
174
 
180
- def get_session_history(
181
- user_id: str, conversation_id: str
182
- ) -> BaseChatMessageHistory:
183
- if (user_id, conversation_id) not in store:
184
- store[(user_id, conversation_id)] = InMemoryHistory()
185
- return store[(user_id, conversation_id)]
175
+ def get_session_history(
176
+ user_id: str, conversation_id: str
177
+ ) -> BaseChatMessageHistory:
178
+ if (user_id, conversation_id) not in store:
179
+ store[(user_id, conversation_id)] = InMemoryHistory()
180
+ return store[(user_id, conversation_id)]
186
181
 
187
182
 
188
- prompt = ChatPromptTemplate.from_messages(
189
- [
190
- ("system", "You're an assistant who's good at {ability}"),
191
- MessagesPlaceholder(variable_name="history"),
192
- ("human", "{question}"),
193
- ]
194
- )
183
+ prompt = ChatPromptTemplate.from_messages(
184
+ [
185
+ ("system", "You're an assistant who's good at {ability}"),
186
+ MessagesPlaceholder(variable_name="history"),
187
+ ("human", "{question}"),
188
+ ]
189
+ )
195
190
 
196
- chain = prompt | ChatAnthropic(model="claude-2")
197
-
198
- with_message_history = RunnableWithMessageHistory(
199
- chain,
200
- get_session_history=get_session_history,
201
- input_messages_key="question",
202
- history_messages_key="history",
203
- history_factory_config=[
204
- ConfigurableFieldSpec(
205
- id="user_id",
206
- annotation=str,
207
- name="User ID",
208
- description="Unique identifier for the user.",
209
- default="",
210
- is_shared=True,
211
- ),
212
- ConfigurableFieldSpec(
213
- id="conversation_id",
214
- annotation=str,
215
- name="Conversation ID",
216
- description="Unique identifier for the conversation.",
217
- default="",
218
- is_shared=True,
219
- ),
220
- ],
221
- )
191
+ chain = prompt | ChatAnthropic(model="claude-2")
222
192
 
223
- with_message_history.invoke(
224
- {"ability": "math", "question": "What does cosine mean?"},
225
- config={"configurable": {"user_id": "123", "conversation_id": "1"}},
226
- )
193
+ with_message_history = RunnableWithMessageHistory(
194
+ chain,
195
+ get_session_history=get_session_history,
196
+ input_messages_key="question",
197
+ history_messages_key="history",
198
+ history_factory_config=[
199
+ ConfigurableFieldSpec(
200
+ id="user_id",
201
+ annotation=str,
202
+ name="User ID",
203
+ description="Unique identifier for the user.",
204
+ default="",
205
+ is_shared=True,
206
+ ),
207
+ ConfigurableFieldSpec(
208
+ id="conversation_id",
209
+ annotation=str,
210
+ name="Conversation ID",
211
+ description="Unique identifier for the conversation.",
212
+ default="",
213
+ is_shared=True,
214
+ ),
215
+ ],
216
+ )
227
217
 
218
+ with_message_history.invoke(
219
+ {"ability": "math", "question": "What does cosine mean?"},
220
+ config={"configurable": {"user_id": "123", "conversation_id": "1"}},
221
+ )
222
+ ```
228
223
  """
229
224
 
230
225
  get_session_history: GetSessionHistoryCallable
231
226
  """Function that returns a new BaseChatMessageHistory.
232
- This function should either take a single positional argument ``session_id`` of type
227
+ This function should either take a single positional argument `session_id` of type
233
228
  string and return a corresponding chat message history instance"""
234
- input_messages_key: Optional[str] = None
229
+ input_messages_key: str | None = None
235
230
  """Must be specified if the base runnable accepts a dict as input.
236
231
  The key in the input dict that contains the messages."""
237
- output_messages_key: Optional[str] = None
232
+ output_messages_key: str | None = None
238
233
  """Must be specified if the base Runnable returns a dict as output.
239
234
  The key in the output dict that contains the messages."""
240
- history_messages_key: Optional[str] = None
235
+ history_messages_key: str | None = None
241
236
  """Must be specified if the base runnable accepts a dict as input and expects a
242
237
  separate key for historical messages."""
243
238
  history_factory_config: Sequence[ConfigurableFieldSpec]
244
239
  """Configure fields that should be passed to the chat history factory.
245
- See ``ConfigurableFieldSpec`` for more details."""
240
+ See `ConfigurableFieldSpec` for more details."""
246
241
 
247
242
  def __init__(
248
243
  self,
249
- runnable: Union[
250
- Runnable[
251
- list[BaseMessage],
252
- Union[str, BaseMessage, MessagesOrDictWithMessages],
253
- ],
254
- Runnable[
255
- dict[str, Any],
256
- Union[str, BaseMessage, MessagesOrDictWithMessages],
257
- ],
258
- LanguageModelLike,
259
- ],
244
+ runnable: Runnable[
245
+ list[BaseMessage], str | BaseMessage | MessagesOrDictWithMessages
246
+ ]
247
+ | Runnable[dict[str, Any], str | BaseMessage | MessagesOrDictWithMessages]
248
+ | LanguageModelLike,
260
249
  get_session_history: GetSessionHistoryCallable,
261
250
  *,
262
- input_messages_key: Optional[str] = None,
263
- output_messages_key: Optional[str] = None,
264
- history_messages_key: Optional[str] = None,
265
- history_factory_config: Optional[Sequence[ConfigurableFieldSpec]] = None,
251
+ input_messages_key: str | None = None,
252
+ output_messages_key: str | None = None,
253
+ history_messages_key: str | None = None,
254
+ history_factory_config: Sequence[ConfigurableFieldSpec] | None = None,
266
255
  **kwargs: Any,
267
256
  ) -> None:
268
257
  """Initialize RunnableWithMessageHistory.
@@ -271,53 +260,53 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
271
260
  runnable: The base Runnable to be wrapped.
272
261
  Must take as input one of:
273
262
 
274
- 1. A list of ``BaseMessage``
263
+ 1. A list of `BaseMessage`
275
264
  2. A dict with one key for all messages
276
265
  3. A dict with one key for the current input string/message(s) and
277
- a separate key for historical messages. If the input key points
278
- to a string, it will be treated as a ``HumanMessage`` in history.
266
+ a separate key for historical messages. If the input key points
267
+ to a string, it will be treated as a `HumanMessage` in history.
279
268
 
280
269
  Must return as output one of:
281
270
 
282
- 1. A string which can be treated as an ``AIMessage``
283
- 2. A ``BaseMessage`` or sequence of ``BaseMessage``
284
- 3. A dict with a key for a ``BaseMessage`` or sequence of
285
- ``BaseMessage``
271
+ 1. A string which can be treated as an `AIMessage`
272
+ 2. A `BaseMessage` or sequence of `BaseMessage`
273
+ 3. A dict with a key for a `BaseMessage` or sequence of
274
+ `BaseMessage`
286
275
 
287
276
  get_session_history: Function that returns a new BaseChatMessageHistory.
288
277
  This function should either take a single positional argument
289
278
  `session_id` of type string and return a corresponding
290
279
  chat message history instance.
291
- .. code-block:: python
292
-
293
- def get_session_history(
294
- session_id: str, *, user_id: Optional[str] = None
295
- ) -> BaseChatMessageHistory: ...
280
+ ```python
281
+ def get_session_history(
282
+ session_id: str, *, user_id: str | None = None
283
+ ) -> BaseChatMessageHistory: ...
284
+ ```
296
285
 
297
286
  Or it should take keyword arguments that match the keys of
298
287
  `session_history_config_specs` and return a corresponding
299
288
  chat message history instance.
300
289
 
301
- .. code-block:: python
302
-
303
- def get_session_history(
304
- *,
305
- user_id: str,
306
- thread_id: str,
307
- ) -> BaseChatMessageHistory: ...
290
+ ```python
291
+ def get_session_history(
292
+ *,
293
+ user_id: str,
294
+ thread_id: str,
295
+ ) -> BaseChatMessageHistory: ...
296
+ ```
308
297
 
309
298
  input_messages_key: Must be specified if the base runnable accepts a dict
310
- as input. Default is None.
299
+ as input.
311
300
  output_messages_key: Must be specified if the base runnable returns a dict
312
- as output. Default is None.
301
+ as output.
313
302
  history_messages_key: Must be specified if the base runnable accepts a dict
314
303
  as input and expects a separate key for historical messages.
315
304
  history_factory_config: Configure fields that should be passed to the
316
- chat history factory. See ``ConfigurableFieldSpec`` for more details.
305
+ chat history factory. See `ConfigurableFieldSpec` for more details.
317
306
  Specifying these allows you to pass multiple config keys
318
307
  into the get_session_history factory.
319
308
  **kwargs: Arbitrary additional kwargs to pass to parent class
320
- ``RunnableBindingBase`` init.
309
+ `RunnableBindingBase` init.
321
310
 
322
311
  """
323
312
  history_chain: Runnable = RunnableLambda(
@@ -381,13 +370,11 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
381
370
  )
382
371
 
383
372
  @override
384
- def get_input_schema(
385
- self, config: Optional[RunnableConfig] = None
386
- ) -> type[BaseModel]:
373
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
387
374
  fields: dict = {}
388
375
  if self.input_messages_key and self.history_messages_key:
389
376
  fields[self.input_messages_key] = (
390
- Union[str, BaseMessage, Sequence[BaseMessage]],
377
+ str | BaseMessage | Sequence[BaseMessage],
391
378
  ...,
392
379
  )
393
380
  elif self.input_messages_key:
@@ -411,13 +398,13 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
411
398
 
412
399
  @override
413
400
  def get_output_schema(
414
- self, config: Optional[RunnableConfig] = None
401
+ self, config: RunnableConfig | None = None
415
402
  ) -> type[BaseModel]:
416
- """Get a pydantic model that can be used to validate output to the Runnable.
403
+ """Get a Pydantic model that can be used to validate output to the `Runnable`.
417
404
 
418
- Runnables that leverage the configurable_fields and configurable_alternatives
419
- methods will have a dynamic output schema that depends on which
420
- configuration the Runnable is invoked with.
405
+ `Runnable` objects that leverage the `configurable_fields` and
406
+ `configurable_alternatives` methods will have a dynamic output schema that
407
+ depends on which configuration the `Runnable` is invoked with.
421
408
 
422
409
  This method allows to get an output schema for a specific configuration.
423
410
 
@@ -425,7 +412,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
425
412
  config: A config to use when generating the schema.
426
413
 
427
414
  Returns:
428
- A pydantic model that can be used to validate output.
415
+ A Pydantic model that can be used to validate output.
429
416
  """
430
417
  root_type = self.OutputType
431
418
 
@@ -443,7 +430,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
443
430
  )
444
431
 
445
432
  def _get_input_messages(
446
- self, input_val: Union[str, BaseMessage, Sequence[BaseMessage], dict]
433
+ self, input_val: str | BaseMessage | Sequence[BaseMessage] | dict
447
434
  ) -> list[BaseMessage]:
448
435
  # If dictionary, try to pluck the single key representing messages
449
436
  if isinstance(input_val, dict):
@@ -481,7 +468,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
481
468
  raise ValueError(msg)
482
469
 
483
470
  def _get_output_messages(
484
- self, output_val: Union[str, BaseMessage, Sequence[BaseMessage], dict]
471
+ self, output_val: str | BaseMessage | Sequence[BaseMessage] | dict
485
472
  ) -> list[BaseMessage]:
486
473
  # If dictionary, try to pluck the single key representing messages
487
474
  if isinstance(output_val, dict):
@@ -571,7 +558,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
571
558
  output_messages = self._get_output_messages(output_val)
572
559
  await hist.aadd_messages(input_messages + output_messages)
573
560
 
574
- def _merge_configs(self, *configs: Optional[RunnableConfig]) -> RunnableConfig:
561
+ def _merge_configs(self, *configs: RunnableConfig | None) -> RunnableConfig:
575
562
  config = super()._merge_configs(*configs)
576
563
  expected_keys = [field_spec.id for field_spec in self.history_factory_config]
577
564