langchain-core 1.0.0a2__py3-none-any.whl → 1.0.0a4__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 (130) hide show
  1. langchain_core/_api/beta_decorator.py +17 -40
  2. langchain_core/_api/deprecation.py +20 -7
  3. langchain_core/_api/path.py +19 -2
  4. langchain_core/_import_utils.py +7 -0
  5. langchain_core/agents.py +10 -6
  6. langchain_core/callbacks/base.py +28 -15
  7. langchain_core/callbacks/manager.py +81 -69
  8. langchain_core/callbacks/usage.py +4 -2
  9. langchain_core/chat_history.py +29 -21
  10. langchain_core/document_loaders/base.py +34 -9
  11. langchain_core/document_loaders/langsmith.py +3 -0
  12. langchain_core/documents/base.py +35 -10
  13. langchain_core/documents/transformers.py +4 -2
  14. langchain_core/embeddings/fake.py +8 -5
  15. langchain_core/env.py +2 -3
  16. langchain_core/example_selectors/base.py +12 -0
  17. langchain_core/exceptions.py +7 -0
  18. langchain_core/globals.py +17 -28
  19. langchain_core/indexing/api.py +57 -45
  20. langchain_core/indexing/base.py +5 -8
  21. langchain_core/indexing/in_memory.py +23 -3
  22. langchain_core/language_models/__init__.py +6 -2
  23. langchain_core/language_models/_utils.py +27 -5
  24. langchain_core/language_models/base.py +33 -21
  25. langchain_core/language_models/chat_models.py +104 -31
  26. langchain_core/language_models/fake_chat_models.py +5 -7
  27. langchain_core/language_models/llms.py +54 -20
  28. langchain_core/load/dump.py +2 -3
  29. langchain_core/load/load.py +15 -1
  30. langchain_core/load/serializable.py +38 -43
  31. langchain_core/memory.py +7 -3
  32. langchain_core/messages/__init__.py +1 -1
  33. langchain_core/messages/ai.py +41 -34
  34. langchain_core/messages/base.py +20 -7
  35. langchain_core/messages/block_translators/__init__.py +10 -8
  36. langchain_core/messages/block_translators/anthropic.py +11 -7
  37. langchain_core/messages/block_translators/bedrock.py +76 -27
  38. langchain_core/messages/block_translators/bedrock_converse.py +259 -23
  39. langchain_core/messages/block_translators/google_genai.py +3 -1
  40. langchain_core/messages/block_translators/google_vertexai.py +3 -1
  41. langchain_core/messages/block_translators/groq.py +3 -1
  42. langchain_core/messages/block_translators/ollama.py +3 -1
  43. langchain_core/messages/block_translators/openai.py +50 -20
  44. langchain_core/messages/content.py +23 -13
  45. langchain_core/messages/human.py +2 -13
  46. langchain_core/messages/system.py +2 -6
  47. langchain_core/messages/tool.py +34 -14
  48. langchain_core/messages/utils.py +186 -73
  49. langchain_core/output_parsers/base.py +5 -2
  50. langchain_core/output_parsers/json.py +4 -4
  51. langchain_core/output_parsers/list.py +7 -22
  52. langchain_core/output_parsers/openai_functions.py +3 -0
  53. langchain_core/output_parsers/openai_tools.py +6 -1
  54. langchain_core/output_parsers/pydantic.py +4 -0
  55. langchain_core/output_parsers/string.py +5 -1
  56. langchain_core/output_parsers/xml.py +19 -19
  57. langchain_core/outputs/chat_generation.py +18 -7
  58. langchain_core/outputs/generation.py +14 -3
  59. langchain_core/outputs/llm_result.py +8 -1
  60. langchain_core/prompt_values.py +10 -4
  61. langchain_core/prompts/base.py +6 -11
  62. langchain_core/prompts/chat.py +88 -60
  63. langchain_core/prompts/dict.py +16 -8
  64. langchain_core/prompts/few_shot.py +9 -11
  65. langchain_core/prompts/few_shot_with_templates.py +5 -1
  66. langchain_core/prompts/image.py +12 -5
  67. langchain_core/prompts/loading.py +2 -2
  68. langchain_core/prompts/message.py +5 -6
  69. langchain_core/prompts/pipeline.py +13 -8
  70. langchain_core/prompts/prompt.py +22 -8
  71. langchain_core/prompts/string.py +18 -10
  72. langchain_core/prompts/structured.py +7 -2
  73. langchain_core/rate_limiters.py +2 -2
  74. langchain_core/retrievers.py +7 -6
  75. langchain_core/runnables/base.py +387 -246
  76. langchain_core/runnables/branch.py +11 -28
  77. langchain_core/runnables/config.py +20 -17
  78. langchain_core/runnables/configurable.py +34 -19
  79. langchain_core/runnables/fallbacks.py +20 -13
  80. langchain_core/runnables/graph.py +48 -38
  81. langchain_core/runnables/graph_ascii.py +40 -17
  82. langchain_core/runnables/graph_mermaid.py +54 -25
  83. langchain_core/runnables/graph_png.py +27 -31
  84. langchain_core/runnables/history.py +55 -58
  85. langchain_core/runnables/passthrough.py +44 -21
  86. langchain_core/runnables/retry.py +44 -23
  87. langchain_core/runnables/router.py +9 -8
  88. langchain_core/runnables/schema.py +9 -0
  89. langchain_core/runnables/utils.py +53 -90
  90. langchain_core/stores.py +19 -31
  91. langchain_core/sys_info.py +9 -8
  92. langchain_core/tools/base.py +36 -27
  93. langchain_core/tools/convert.py +25 -14
  94. langchain_core/tools/simple.py +36 -8
  95. langchain_core/tools/structured.py +25 -12
  96. langchain_core/tracers/base.py +2 -2
  97. langchain_core/tracers/context.py +5 -1
  98. langchain_core/tracers/core.py +110 -46
  99. langchain_core/tracers/evaluation.py +22 -26
  100. langchain_core/tracers/event_stream.py +97 -42
  101. langchain_core/tracers/langchain.py +12 -3
  102. langchain_core/tracers/langchain_v1.py +10 -2
  103. langchain_core/tracers/log_stream.py +56 -17
  104. langchain_core/tracers/root_listeners.py +4 -20
  105. langchain_core/tracers/run_collector.py +6 -16
  106. langchain_core/tracers/schemas.py +5 -1
  107. langchain_core/utils/aiter.py +14 -6
  108. langchain_core/utils/env.py +3 -0
  109. langchain_core/utils/function_calling.py +46 -20
  110. langchain_core/utils/interactive_env.py +6 -2
  111. langchain_core/utils/iter.py +12 -5
  112. langchain_core/utils/json.py +12 -3
  113. langchain_core/utils/json_schema.py +156 -40
  114. langchain_core/utils/loading.py +5 -1
  115. langchain_core/utils/mustache.py +25 -16
  116. langchain_core/utils/pydantic.py +38 -9
  117. langchain_core/utils/utils.py +25 -9
  118. langchain_core/vectorstores/base.py +7 -20
  119. langchain_core/vectorstores/in_memory.py +20 -14
  120. langchain_core/vectorstores/utils.py +18 -12
  121. langchain_core/version.py +1 -1
  122. langchain_core-1.0.0a4.dist-info/METADATA +77 -0
  123. langchain_core-1.0.0a4.dist-info/RECORD +181 -0
  124. langchain_core/beta/__init__.py +0 -1
  125. langchain_core/beta/runnables/__init__.py +0 -1
  126. langchain_core/beta/runnables/context.py +0 -448
  127. langchain_core-1.0.0a2.dist-info/METADATA +0 -106
  128. langchain_core-1.0.0a2.dist-info/RECORD +0 -184
  129. {langchain_core-1.0.0a2.dist-info → langchain_core-1.0.0a4.dist-info}/WHEEL +0 -0
  130. {langchain_core-1.0.0a2.dist-info → langchain_core-1.0.0a4.dist-info}/entry_points.txt +0 -0
@@ -63,6 +63,9 @@ def beta(
63
63
  addendum : str, optional
64
64
  Additional text appended directly to the final message.
65
65
 
66
+ Returns:
67
+ A decorator which can be used to mark functions or classes as beta.
68
+
66
69
  Examples:
67
70
 
68
71
  .. code-block:: python
@@ -153,50 +156,24 @@ def beta(
153
156
  _name = _name or obj.fget.__qualname__
154
157
  old_doc = obj.__doc__
155
158
 
156
- class _BetaProperty(property):
157
- """A beta property."""
158
-
159
- def __init__(
160
- self,
161
- fget: Union[Callable[[Any], Any], None] = None,
162
- fset: Union[Callable[[Any, Any], None], None] = None,
163
- fdel: Union[Callable[[Any], None], None] = None,
164
- doc: Union[str, None] = None,
165
- ) -> None:
166
- super().__init__(fget, fset, fdel, doc)
167
- self.__orig_fget = fget
168
- self.__orig_fset = fset
169
- self.__orig_fdel = fdel
170
- self.__doc__ = doc
171
-
172
- def __get__(
173
- self, instance: Any, owner: Union[type, None] = None
174
- ) -> Any:
175
- if instance is not None or owner is not None:
176
- emit_warning()
177
- return self.fget(instance)
178
-
179
- def __set__(self, instance: Any, value: Any) -> None:
180
- if instance is not None:
181
- emit_warning()
182
- return self.fset(instance, value)
159
+ def _fget(instance: Any) -> Any:
160
+ if instance is not None:
161
+ emit_warning()
162
+ return obj.fget(instance)
183
163
 
184
- def __delete__(self, instance: Any) -> None:
185
- if instance is not None:
186
- emit_warning()
187
- return self.fdel(instance)
164
+ def _fset(instance: Any, value: Any) -> None:
165
+ if instance is not None:
166
+ emit_warning()
167
+ obj.fset(instance, value)
188
168
 
189
- def __set_name__(self, owner: Union[type, None], set_name: str) -> None:
190
- nonlocal _name
191
- if _name == "<lambda>":
192
- _name = set_name
169
+ def _fdel(instance: Any) -> None:
170
+ if instance is not None:
171
+ emit_warning()
172
+ obj.fdel(instance)
193
173
 
194
- def finalize(wrapper: Callable[..., Any], new_doc: str) -> Any: # noqa: ARG001
174
+ def finalize(_wrapper: Callable[..., Any], new_doc: str) -> Any:
195
175
  """Finalize the property."""
196
- return _BetaProperty(
197
- fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
198
- )
199
-
176
+ return property(fget=_fget, fset=_fset, fdel=_fdel, doc=new_doc)
200
177
  else:
201
178
  _name = _name or obj.__qualname__
202
179
  if not _obj_type:
@@ -18,6 +18,7 @@ from collections.abc import Generator
18
18
  from typing import (
19
19
  Any,
20
20
  Callable,
21
+ ParamSpec,
21
22
  TypeVar,
22
23
  Union,
23
24
  cast,
@@ -25,7 +26,6 @@ from typing import (
25
26
 
26
27
  from pydantic.fields import FieldInfo
27
28
  from pydantic.v1.fields import FieldInfo as FieldInfoV1
28
- from typing_extensions import ParamSpec
29
29
 
30
30
  from langchain_core._api.internal import is_caller_internal
31
31
 
@@ -129,11 +129,14 @@ def deprecated(
129
129
  package: str, optional
130
130
  The package of the deprecated object.
131
131
 
132
+ Returns:
133
+ A decorator to mark a function or class as deprecated.
134
+
132
135
  Examples:
133
136
 
134
137
  .. code-block:: python
135
138
 
136
- @deprecated('1.4.0')
139
+ @deprecated("1.4.0")
137
140
  def the_function_to_deprecate():
138
141
  pass
139
142
 
@@ -358,7 +361,8 @@ def deprecated(
358
361
  # Modify the docstring to include a deprecation notice.
359
362
  if (
360
363
  _alternative
361
- and _alternative.split(".")[-1].lower() == _alternative.split(".")[-1]
364
+ and _alternative.rsplit(".", maxsplit=1)[-1].lower()
365
+ == _alternative.rsplit(".", maxsplit=1)[-1]
362
366
  ):
363
367
  _alternative = f":meth:`~{_alternative}`"
364
368
  elif _alternative:
@@ -366,8 +370,8 @@ def deprecated(
366
370
 
367
371
  if (
368
372
  _alternative_import
369
- and _alternative_import.split(".")[-1].lower()
370
- == _alternative_import.split(".")[-1]
373
+ and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
374
+ == _alternative_import.rsplit(".", maxsplit=1)[-1]
371
375
  ):
372
376
  _alternative_import = f":meth:`~{_alternative_import}`"
373
377
  elif _alternative_import:
@@ -471,7 +475,7 @@ def warn_deprecated(
471
475
  if not message:
472
476
  message = ""
473
477
  package_ = (
474
- package or name.split(".")[0].replace("_", "-")
478
+ package or name.split(".", maxsplit=1)[0].replace("_", "-")
475
479
  if "." in name
476
480
  else "LangChain"
477
481
  )
@@ -490,7 +494,7 @@ def warn_deprecated(
490
494
  message += f" and will be removed {removal}"
491
495
 
492
496
  if alternative_import:
493
- alt_package = alternative_import.split(".")[0].replace("_", "-")
497
+ alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")
494
498
  if alt_package == package_:
495
499
  message += f". Use {alternative_import} instead."
496
500
  else:
@@ -544,6 +548,15 @@ def rename_parameter(
544
548
  is passed to *func*, a DeprecationWarning is emitted, and its value is
545
549
  used, even if *new* is also passed by keyword.
546
550
 
551
+ Args:
552
+ since: The version in which the parameter was renamed.
553
+ removal: The version in which the old parameter will be removed.
554
+ old: The old parameter name.
555
+ new: The new parameter name.
556
+
557
+ Returns:
558
+ A decorator indicating that a parameter was renamed.
559
+
547
560
  Example:
548
561
 
549
562
  .. code-block:: python
@@ -12,7 +12,15 @@ SEPARATOR = os.sep
12
12
  def get_relative_path(
13
13
  file: Union[Path, str], *, relative_to: Path = PACKAGE_DIR
14
14
  ) -> str:
15
- """Get the path of the file as a relative path to the package directory."""
15
+ """Get the path of the file as a relative path to the package directory.
16
+
17
+ Args:
18
+ file: The file path to convert.
19
+ relative_to: The base path to make the file path relative to.
20
+
21
+ Returns:
22
+ The relative path as a string.
23
+ """
16
24
  if isinstance(file, str):
17
25
  file = Path(file)
18
26
  return str(file.relative_to(relative_to))
@@ -24,7 +32,16 @@ def as_import_path(
24
32
  suffix: Optional[str] = None,
25
33
  relative_to: Path = PACKAGE_DIR,
26
34
  ) -> str:
27
- """Path of the file as a LangChain import exclude langchain top namespace."""
35
+ """Path of the file as a LangChain import exclude langchain top namespace.
36
+
37
+ Args:
38
+ file: The file path to convert.
39
+ suffix: An optional suffix to append to the import path.
40
+ relative_to: The base path to make the file path relative to.
41
+
42
+ Returns:
43
+ The import path as a string.
44
+ """
28
45
  if isinstance(file, str):
29
46
  file = Path(file)
30
47
  path = get_relative_path(file, relative_to=relative_to)
@@ -17,6 +17,13 @@ def import_attr(
17
17
  module_name: The name of the module to import from. If None, the attribute
18
18
  is imported from the package itself.
19
19
  package: The name of the package where the module is located.
20
+
21
+ Raises:
22
+ ImportError: If the module cannot be found.
23
+ AttributeError: If the attribute does not exist in the module or package.
24
+
25
+ Returns:
26
+ The imported attribute.
20
27
  """
21
28
  if module_name == "__module__" or module_name is None:
22
29
  try:
langchain_core/agents.py CHANGED
@@ -14,13 +14,15 @@ Agents use language models to choose a sequence of actions to take.
14
14
 
15
15
  A basic agent works in the following manner:
16
16
 
17
- 1. Given a prompt an agent uses an LLM to request an action to take (e.g., a tool to run).
17
+ 1. Given a prompt an agent uses an LLM to request an action to take
18
+ (e.g., a tool to run).
18
19
  2. The agent executes the action (e.g., runs the tool), and receives an observation.
19
- 3. The agent returns the observation to the LLM, which can then be used to generate the next action.
20
+ 3. The agent returns the observation to the LLM, which can then be used to generate
21
+ the next action.
20
22
  4. When the agent reaches a stopping condition, it returns a final return value.
21
23
 
22
24
  The schemas for the agents themselves are defined in langchain.agents.agent.
23
- """ # noqa: E501
25
+ """
24
26
 
25
27
  from __future__ import annotations
26
28
 
@@ -84,7 +86,8 @@ class AgentAction(Serializable):
84
86
  def get_lc_namespace(cls) -> list[str]:
85
87
  """Get the namespace of the langchain object.
86
88
 
87
- Default is ["langchain", "schema", "agent"].
89
+ Returns:
90
+ ``["langchain", "schema", "agent"]``
88
91
  """
89
92
  return ["langchain", "schema", "agent"]
90
93
 
@@ -153,14 +156,15 @@ class AgentFinish(Serializable):
153
156
 
154
157
  @classmethod
155
158
  def is_lc_serializable(cls) -> bool:
156
- """Return whether or not the class is serializable."""
159
+ """Return True as this class is serializable."""
157
160
  return True
158
161
 
159
162
  @classmethod
160
163
  def get_lc_namespace(cls) -> list[str]:
161
164
  """Get the namespace of the langchain object.
162
165
 
163
- Default namespace is ["langchain", "schema", "agent"].
166
+ Returns:
167
+ ``["langchain", "schema", "agent"]``
164
168
  """
165
169
  return ["langchain", "schema", "agent"]
166
170
 
@@ -71,7 +71,9 @@ class LLMManagerMixin:
71
71
  parent_run_id: Optional[UUID] = None,
72
72
  **kwargs: Any,
73
73
  ) -> Any:
74
- """Run on new LLM token. Only available when streaming is enabled.
74
+ """Run on new output token. Only available when streaming is enabled.
75
+
76
+ For both chat models and non-chat models (legacy LLMs).
75
77
 
76
78
  Args:
77
79
  token (str): The new token.
@@ -243,7 +245,7 @@ class CallbackManagerMixin:
243
245
  ) -> Any:
244
246
  """Run when LLM starts running.
245
247
 
246
- .. ATTENTION::
248
+ .. warning::
247
249
  This method is called for non-chat models (regular LLMs). If you're
248
250
  implementing a handler for a chat model, you should use
249
251
  ``on_chat_model_start`` instead.
@@ -271,8 +273,9 @@ class CallbackManagerMixin:
271
273
  ) -> Any:
272
274
  """Run when a chat model starts running.
273
275
 
274
- **ATTENTION**: This method is called for chat models. If you're implementing
275
- a handler for a non-chat model, you should use ``on_llm_start`` instead.
276
+ .. warning::
277
+ This method is called for chat models. If you're implementing a handler for
278
+ a non-chat model, you should use ``on_llm_start`` instead.
276
279
 
277
280
  Args:
278
281
  serialized (dict[str, Any]): The serialized chat model.
@@ -489,9 +492,9 @@ class AsyncCallbackHandler(BaseCallbackHandler):
489
492
  metadata: Optional[dict[str, Any]] = None,
490
493
  **kwargs: Any,
491
494
  ) -> None:
492
- """Run when LLM starts running.
495
+ """Run when the model starts running.
493
496
 
494
- .. ATTENTION::
497
+ .. warning::
495
498
  This method is called for non-chat models (regular LLMs). If you're
496
499
  implementing a handler for a chat model, you should use
497
500
  ``on_chat_model_start`` instead.
@@ -519,8 +522,9 @@ class AsyncCallbackHandler(BaseCallbackHandler):
519
522
  ) -> Any:
520
523
  """Run when a chat model starts running.
521
524
 
522
- **ATTENTION**: This method is called for chat models. If you're implementing
523
- a handler for a non-chat model, you should use ``on_llm_start`` instead.
525
+ .. warning::
526
+ This method is called for chat models. If you're implementing a handler for
527
+ a non-chat model, you should use ``on_llm_start`` instead.
524
528
 
525
529
  Args:
526
530
  serialized (dict[str, Any]): The serialized chat model.
@@ -546,7 +550,9 @@ class AsyncCallbackHandler(BaseCallbackHandler):
546
550
  tags: Optional[list[str]] = None,
547
551
  **kwargs: Any,
548
552
  ) -> None:
549
- """Run on new LLM token. Only available when streaming is enabled.
553
+ """Run on new output token. Only available when streaming is enabled.
554
+
555
+ For both chat models and non-chat models (legacy LLMs).
550
556
 
551
557
  Args:
552
558
  token (str): The new token.
@@ -567,7 +573,7 @@ class AsyncCallbackHandler(BaseCallbackHandler):
567
573
  tags: Optional[list[str]] = None,
568
574
  **kwargs: Any,
569
575
  ) -> None:
570
- """Run when LLM ends running.
576
+ """Run when the model ends running.
571
577
 
572
578
  Args:
573
579
  response (LLMResult): The response which was generated.
@@ -867,7 +873,7 @@ class AsyncCallbackHandler(BaseCallbackHandler):
867
873
  metadata: Optional[dict[str, Any]] = None,
868
874
  **kwargs: Any,
869
875
  ) -> None:
870
- """Override to define a handler for a custom event.
876
+ """Override to define a handler for custom events.
871
877
 
872
878
  Args:
873
879
  name: The name of the custom event.
@@ -922,7 +928,7 @@ class BaseCallbackManager(CallbackManagerMixin):
922
928
  self.inheritable_metadata = inheritable_metadata or {}
923
929
 
924
930
  def copy(self) -> Self:
925
- """Copy the callback manager."""
931
+ """Return a copy of the callback manager."""
926
932
  return self.__class__(
927
933
  handlers=self.handlers.copy(),
928
934
  inheritable_handlers=self.inheritable_handlers.copy(),
@@ -947,11 +953,18 @@ class BaseCallbackManager(CallbackManagerMixin):
947
953
 
948
954
  .. code-block:: python
949
955
 
950
- from langchain_core.callbacks.manager import CallbackManager, trace_as_chain_group
956
+ from langchain_core.callbacks.manager import (
957
+ CallbackManager,
958
+ trace_as_chain_group,
959
+ )
951
960
  from langchain_core.callbacks.stdout import StdOutCallbackHandler
952
961
 
953
- manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
954
- with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
962
+ manager = CallbackManager(
963
+ handlers=[StdOutCallbackHandler()], tags=["tag2"]
964
+ )
965
+ with trace_as_chain_group(
966
+ "My Group Name", tags=["tag1"]
967
+ ) as group_manager:
955
968
  merged_manager = group_manager.merge(manager)
956
969
  print(merged_manager.handlers)
957
970
  # [