langchain-core 1.0.0a6__py3-none-any.whl → 1.0.0a8__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 (131) hide show
  1. langchain_core/_api/__init__.py +3 -3
  2. langchain_core/_api/beta_decorator.py +6 -6
  3. langchain_core/_api/deprecation.py +21 -29
  4. langchain_core/_api/path.py +3 -6
  5. langchain_core/_import_utils.py +2 -3
  6. langchain_core/agents.py +10 -11
  7. langchain_core/caches.py +7 -7
  8. langchain_core/callbacks/base.py +91 -91
  9. langchain_core/callbacks/file.py +11 -11
  10. langchain_core/callbacks/manager.py +86 -89
  11. langchain_core/callbacks/stdout.py +8 -8
  12. langchain_core/callbacks/usage.py +4 -4
  13. langchain_core/chat_history.py +5 -5
  14. langchain_core/document_loaders/base.py +2 -2
  15. langchain_core/document_loaders/langsmith.py +15 -15
  16. langchain_core/documents/base.py +16 -16
  17. langchain_core/documents/compressor.py +4 -4
  18. langchain_core/example_selectors/length_based.py +1 -1
  19. langchain_core/example_selectors/semantic_similarity.py +17 -19
  20. langchain_core/exceptions.py +3 -3
  21. langchain_core/globals.py +3 -151
  22. langchain_core/indexing/api.py +44 -43
  23. langchain_core/indexing/base.py +30 -30
  24. langchain_core/indexing/in_memory.py +3 -3
  25. langchain_core/language_models/_utils.py +5 -7
  26. langchain_core/language_models/base.py +18 -132
  27. langchain_core/language_models/chat_models.py +118 -227
  28. langchain_core/language_models/fake.py +11 -11
  29. langchain_core/language_models/fake_chat_models.py +35 -29
  30. langchain_core/language_models/llms.py +91 -201
  31. langchain_core/load/dump.py +1 -1
  32. langchain_core/load/load.py +11 -12
  33. langchain_core/load/mapping.py +2 -4
  34. langchain_core/load/serializable.py +2 -4
  35. langchain_core/messages/ai.py +17 -20
  36. langchain_core/messages/base.py +23 -25
  37. langchain_core/messages/block_translators/__init__.py +2 -5
  38. langchain_core/messages/block_translators/anthropic.py +3 -3
  39. langchain_core/messages/block_translators/bedrock_converse.py +2 -2
  40. langchain_core/messages/block_translators/langchain_v0.py +2 -2
  41. langchain_core/messages/block_translators/openai.py +6 -6
  42. langchain_core/messages/content.py +120 -124
  43. langchain_core/messages/human.py +7 -7
  44. langchain_core/messages/system.py +7 -7
  45. langchain_core/messages/tool.py +24 -24
  46. langchain_core/messages/utils.py +67 -79
  47. langchain_core/output_parsers/base.py +12 -14
  48. langchain_core/output_parsers/json.py +4 -4
  49. langchain_core/output_parsers/list.py +3 -5
  50. langchain_core/output_parsers/openai_functions.py +3 -3
  51. langchain_core/output_parsers/openai_tools.py +3 -3
  52. langchain_core/output_parsers/pydantic.py +2 -2
  53. langchain_core/output_parsers/transform.py +13 -15
  54. langchain_core/output_parsers/xml.py +7 -9
  55. langchain_core/outputs/chat_generation.py +4 -4
  56. langchain_core/outputs/chat_result.py +1 -3
  57. langchain_core/outputs/generation.py +2 -2
  58. langchain_core/outputs/llm_result.py +5 -5
  59. langchain_core/prompts/__init__.py +1 -5
  60. langchain_core/prompts/base.py +10 -15
  61. langchain_core/prompts/chat.py +31 -82
  62. langchain_core/prompts/dict.py +2 -2
  63. langchain_core/prompts/few_shot.py +5 -5
  64. langchain_core/prompts/few_shot_with_templates.py +4 -4
  65. langchain_core/prompts/loading.py +3 -5
  66. langchain_core/prompts/prompt.py +4 -16
  67. langchain_core/prompts/string.py +2 -1
  68. langchain_core/prompts/structured.py +16 -23
  69. langchain_core/rate_limiters.py +3 -4
  70. langchain_core/retrievers.py +14 -14
  71. langchain_core/runnables/base.py +928 -1042
  72. langchain_core/runnables/branch.py +36 -40
  73. langchain_core/runnables/config.py +27 -35
  74. langchain_core/runnables/configurable.py +108 -124
  75. langchain_core/runnables/fallbacks.py +76 -72
  76. langchain_core/runnables/graph.py +39 -45
  77. langchain_core/runnables/graph_ascii.py +9 -11
  78. langchain_core/runnables/graph_mermaid.py +18 -19
  79. langchain_core/runnables/graph_png.py +8 -9
  80. langchain_core/runnables/history.py +114 -127
  81. langchain_core/runnables/passthrough.py +113 -139
  82. langchain_core/runnables/retry.py +43 -48
  83. langchain_core/runnables/router.py +23 -28
  84. langchain_core/runnables/schema.py +42 -44
  85. langchain_core/runnables/utils.py +28 -31
  86. langchain_core/stores.py +9 -13
  87. langchain_core/structured_query.py +8 -8
  88. langchain_core/tools/base.py +62 -115
  89. langchain_core/tools/convert.py +31 -35
  90. langchain_core/tools/render.py +1 -1
  91. langchain_core/tools/retriever.py +4 -4
  92. langchain_core/tools/simple.py +13 -17
  93. langchain_core/tools/structured.py +12 -15
  94. langchain_core/tracers/base.py +62 -64
  95. langchain_core/tracers/context.py +17 -35
  96. langchain_core/tracers/core.py +49 -53
  97. langchain_core/tracers/evaluation.py +11 -11
  98. langchain_core/tracers/event_stream.py +58 -60
  99. langchain_core/tracers/langchain.py +13 -13
  100. langchain_core/tracers/log_stream.py +22 -24
  101. langchain_core/tracers/root_listeners.py +14 -14
  102. langchain_core/tracers/run_collector.py +2 -4
  103. langchain_core/tracers/schemas.py +8 -8
  104. langchain_core/tracers/stdout.py +2 -1
  105. langchain_core/utils/__init__.py +0 -3
  106. langchain_core/utils/_merge.py +2 -2
  107. langchain_core/utils/aiter.py +24 -28
  108. langchain_core/utils/env.py +4 -4
  109. langchain_core/utils/function_calling.py +31 -41
  110. langchain_core/utils/html.py +3 -4
  111. langchain_core/utils/input.py +3 -3
  112. langchain_core/utils/iter.py +15 -19
  113. langchain_core/utils/json.py +3 -2
  114. langchain_core/utils/json_schema.py +6 -6
  115. langchain_core/utils/mustache.py +3 -5
  116. langchain_core/utils/pydantic.py +16 -18
  117. langchain_core/utils/usage.py +1 -1
  118. langchain_core/utils/utils.py +29 -29
  119. langchain_core/vectorstores/base.py +18 -21
  120. langchain_core/vectorstores/in_memory.py +14 -87
  121. langchain_core/vectorstores/utils.py +2 -2
  122. langchain_core/version.py +1 -1
  123. {langchain_core-1.0.0a6.dist-info → langchain_core-1.0.0a8.dist-info}/METADATA +10 -21
  124. langchain_core-1.0.0a8.dist-info/RECORD +176 -0
  125. {langchain_core-1.0.0a6.dist-info → langchain_core-1.0.0a8.dist-info}/WHEEL +1 -1
  126. langchain_core/messages/block_translators/ollama.py +0 -47
  127. langchain_core/prompts/pipeline.py +0 -138
  128. langchain_core/tracers/langchain_v1.py +0 -31
  129. langchain_core/utils/loading.py +0 -35
  130. langchain_core-1.0.0a6.dist-info/RECORD +0 -181
  131. langchain_core-1.0.0a6.dist-info/entry_points.txt +0 -4
@@ -1,6 +1,6 @@
1
1
  """Helper class to draw a state graph into a PNG file."""
2
2
 
3
- from typing import Any, Optional
3
+ from typing import Any
4
4
 
5
5
  from langchain_core.runnables.graph import Graph, LabelsDict
6
6
 
@@ -18,15 +18,14 @@ class PngDrawer:
18
18
  It requires ``graphviz`` and ``pygraphviz`` to be installed.
19
19
 
20
20
  Example:
21
-
22
- .. code-block:: python
23
-
24
- drawer = PngDrawer()
25
- drawer.draw(state_graph, "graph.png")
21
+ ```python
22
+ drawer = PngDrawer()
23
+ drawer.draw(state_graph, "graph.png")
24
+ ```
26
25
  """
27
26
 
28
27
  def __init__(
29
- self, fontname: Optional[str] = None, labels: Optional[LabelsDict] = None
28
+ self, fontname: str | None = None, labels: LabelsDict | None = None
30
29
  ) -> None:
31
30
  """Initializes the PNG drawer.
32
31
 
@@ -96,7 +95,7 @@ class PngDrawer:
96
95
  viz: Any,
97
96
  source: str,
98
97
  target: str,
99
- label: Optional[str] = None,
98
+ label: str | None = None,
100
99
  conditional: bool = False, # noqa: FBT001,FBT002
101
100
  ) -> None:
102
101
  """Adds an edge to the graph.
@@ -117,7 +116,7 @@ class PngDrawer:
117
116
  style="dotted" if conditional else "solid",
118
117
  )
119
118
 
120
- def draw(self, graph: Graph, output_path: Optional[str] = None) -> Optional[bytes]:
119
+ def draw(self, graph: Graph, output_path: str | None = None) -> bytes | None:
121
120
  """Draw the given state graph into a PNG file.
122
121
 
123
122
  Requires `graphviz` and `pygraphviz` to be installed.
@@ -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
 
@@ -74,8 +71,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
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,125 +115,124 @@ 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
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]
@@ -246,23 +241,17 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
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.
@@ -288,23 +277,23 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
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: Optional[str] = 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
299
  as input. Default is None.
@@ -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,7 +398,7 @@ 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
403
  """Get a pydantic model that can be used to validate output to the Runnable.
417
404
 
@@ -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