langchain-core 0.3.75__py3-none-any.whl → 0.3.76__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 (116) hide show
  1. langchain_core/_api/beta_decorator.py +17 -40
  2. langchain_core/_api/deprecation.py +19 -6
  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/beta/runnables/context.py +1 -2
  7. langchain_core/callbacks/base.py +11 -4
  8. langchain_core/callbacks/manager.py +81 -69
  9. langchain_core/callbacks/usage.py +4 -2
  10. langchain_core/chat_history.py +4 -6
  11. langchain_core/document_loaders/base.py +34 -9
  12. langchain_core/document_loaders/langsmith.py +3 -0
  13. langchain_core/documents/base.py +35 -10
  14. langchain_core/documents/transformers.py +4 -2
  15. langchain_core/embeddings/fake.py +8 -5
  16. langchain_core/env.py +2 -3
  17. langchain_core/example_selectors/base.py +12 -0
  18. langchain_core/exceptions.py +7 -0
  19. langchain_core/globals.py +17 -28
  20. langchain_core/indexing/api.py +56 -44
  21. langchain_core/indexing/base.py +5 -8
  22. langchain_core/indexing/in_memory.py +23 -3
  23. langchain_core/language_models/__init__.py +3 -2
  24. langchain_core/language_models/base.py +31 -20
  25. langchain_core/language_models/chat_models.py +94 -25
  26. langchain_core/language_models/fake_chat_models.py +5 -7
  27. langchain_core/language_models/llms.py +49 -17
  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/ai.py +36 -19
  33. langchain_core/messages/base.py +13 -6
  34. langchain_core/messages/content_blocks.py +23 -2
  35. langchain_core/messages/human.py +2 -6
  36. langchain_core/messages/system.py +2 -6
  37. langchain_core/messages/tool.py +33 -13
  38. langchain_core/messages/utils.py +182 -72
  39. langchain_core/output_parsers/base.py +5 -2
  40. langchain_core/output_parsers/json.py +4 -4
  41. langchain_core/output_parsers/list.py +7 -22
  42. langchain_core/output_parsers/openai_functions.py +3 -0
  43. langchain_core/output_parsers/openai_tools.py +6 -1
  44. langchain_core/output_parsers/pydantic.py +4 -0
  45. langchain_core/output_parsers/string.py +5 -1
  46. langchain_core/output_parsers/xml.py +19 -19
  47. langchain_core/outputs/chat_generation.py +18 -7
  48. langchain_core/outputs/generation.py +14 -3
  49. langchain_core/outputs/llm_result.py +8 -1
  50. langchain_core/prompt_values.py +10 -4
  51. langchain_core/prompts/base.py +4 -9
  52. langchain_core/prompts/chat.py +87 -58
  53. langchain_core/prompts/dict.py +16 -8
  54. langchain_core/prompts/few_shot.py +9 -11
  55. langchain_core/prompts/few_shot_with_templates.py +5 -1
  56. langchain_core/prompts/image.py +12 -5
  57. langchain_core/prompts/message.py +5 -6
  58. langchain_core/prompts/pipeline.py +13 -8
  59. langchain_core/prompts/prompt.py +22 -8
  60. langchain_core/prompts/string.py +18 -10
  61. langchain_core/prompts/structured.py +7 -2
  62. langchain_core/rate_limiters.py +2 -2
  63. langchain_core/retrievers.py +7 -6
  64. langchain_core/runnables/base.py +402 -183
  65. langchain_core/runnables/branch.py +14 -19
  66. langchain_core/runnables/config.py +9 -15
  67. langchain_core/runnables/configurable.py +34 -19
  68. langchain_core/runnables/fallbacks.py +20 -13
  69. langchain_core/runnables/graph.py +44 -37
  70. langchain_core/runnables/graph_ascii.py +40 -17
  71. langchain_core/runnables/graph_mermaid.py +27 -15
  72. langchain_core/runnables/graph_png.py +27 -31
  73. langchain_core/runnables/history.py +55 -58
  74. langchain_core/runnables/passthrough.py +44 -21
  75. langchain_core/runnables/retry.py +9 -5
  76. langchain_core/runnables/router.py +9 -8
  77. langchain_core/runnables/schema.py +2 -0
  78. langchain_core/runnables/utils.py +51 -89
  79. langchain_core/stores.py +13 -25
  80. langchain_core/sys_info.py +9 -8
  81. langchain_core/tools/base.py +30 -23
  82. langchain_core/tools/convert.py +24 -13
  83. langchain_core/tools/simple.py +35 -3
  84. langchain_core/tools/structured.py +25 -2
  85. langchain_core/tracers/base.py +2 -2
  86. langchain_core/tracers/context.py +5 -1
  87. langchain_core/tracers/core.py +109 -39
  88. langchain_core/tracers/evaluation.py +22 -26
  89. langchain_core/tracers/event_stream.py +40 -27
  90. langchain_core/tracers/langchain.py +12 -3
  91. langchain_core/tracers/langchain_v1.py +10 -2
  92. langchain_core/tracers/log_stream.py +56 -17
  93. langchain_core/tracers/root_listeners.py +4 -20
  94. langchain_core/tracers/run_collector.py +6 -16
  95. langchain_core/tracers/schemas.py +5 -1
  96. langchain_core/utils/aiter.py +14 -6
  97. langchain_core/utils/env.py +3 -0
  98. langchain_core/utils/function_calling.py +37 -20
  99. langchain_core/utils/interactive_env.py +6 -2
  100. langchain_core/utils/iter.py +11 -3
  101. langchain_core/utils/json.py +5 -2
  102. langchain_core/utils/json_schema.py +15 -5
  103. langchain_core/utils/loading.py +5 -1
  104. langchain_core/utils/mustache.py +24 -15
  105. langchain_core/utils/pydantic.py +32 -4
  106. langchain_core/utils/utils.py +24 -8
  107. langchain_core/vectorstores/base.py +7 -20
  108. langchain_core/vectorstores/in_memory.py +18 -12
  109. langchain_core/vectorstores/utils.py +18 -12
  110. langchain_core/version.py +1 -1
  111. langchain_core-0.3.76.dist-info/METADATA +77 -0
  112. langchain_core-0.3.76.dist-info/RECORD +174 -0
  113. langchain_core-0.3.75.dist-info/METADATA +0 -106
  114. langchain_core-0.3.75.dist-info/RECORD +0 -174
  115. {langchain_core-0.3.75.dist-info → langchain_core-0.3.76.dist-info}/WHEEL +0 -0
  116. {langchain_core-0.3.75.dist-info → langchain_core-0.3.76.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:
@@ -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
 
@@ -344,8 +344,7 @@ class Context:
344
344
  chain = (
345
345
  Context.setter("input")
346
346
  | {
347
- "context": RunnablePassthrough()
348
- | Context.setter("context"),
347
+ "context": RunnablePassthrough() | Context.setter("context"),
349
348
  "question": RunnablePassthrough(),
350
349
  }
351
350
  | PromptTemplate.from_template("{context} {question}")
@@ -922,7 +922,7 @@ class BaseCallbackManager(CallbackManagerMixin):
922
922
  self.inheritable_metadata = inheritable_metadata or {}
923
923
 
924
924
  def copy(self) -> Self:
925
- """Copy the callback manager."""
925
+ """Return a copy of the callback manager."""
926
926
  return self.__class__(
927
927
  handlers=self.handlers.copy(),
928
928
  inheritable_handlers=self.inheritable_handlers.copy(),
@@ -947,11 +947,18 @@ class BaseCallbackManager(CallbackManagerMixin):
947
947
 
948
948
  .. code-block:: python
949
949
 
950
- from langchain_core.callbacks.manager import CallbackManager, trace_as_chain_group
950
+ from langchain_core.callbacks.manager import (
951
+ CallbackManager,
952
+ trace_as_chain_group,
953
+ )
951
954
  from langchain_core.callbacks.stdout import StdOutCallbackHandler
952
955
 
953
- manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
954
- with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
956
+ manager = CallbackManager(
957
+ handlers=[StdOutCallbackHandler()], tags=["tag2"]
958
+ )
959
+ with trace_as_chain_group(
960
+ "My Group Name", tags=["tag1"]
961
+ ) as group_manager:
955
962
  merged_manager = group_manager.merge(manager)
956
963
  print(merged_manager.handlers)
957
964
  # [
@@ -28,8 +28,18 @@ from langchain_core.callbacks.base import (
28
28
  ToolManagerMixin,
29
29
  )
30
30
  from langchain_core.callbacks.stdout import StdOutCallbackHandler
31
+ from langchain_core.globals import get_debug
31
32
  from langchain_core.messages import BaseMessage, get_buffer_string
33
+ from langchain_core.tracers.context import (
34
+ _configure_hooks,
35
+ _get_trace_callbacks,
36
+ _get_tracer_project,
37
+ _tracing_v2_is_enabled,
38
+ tracing_v2_callback_var,
39
+ )
40
+ from langchain_core.tracers.langchain import LangChainTracer
32
41
  from langchain_core.tracers.schemas import Run
42
+ from langchain_core.tracers.stdout import ConsoleCallbackHandler
33
43
  from langchain_core.utils.env import env_var_is_set
34
44
 
35
45
  if TYPE_CHECKING:
@@ -46,8 +56,6 @@ logger = logging.getLogger(__name__)
46
56
 
47
57
 
48
58
  def _get_debug() -> bool:
49
- from langchain_core.globals import get_debug
50
-
51
59
  return get_debug()
52
60
 
53
61
 
@@ -85,23 +93,24 @@ def trace_as_chain_group(
85
93
  Defaults to None.
86
94
 
87
95
  .. note:
88
- Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in LangSmith.
96
+ Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in
97
+ LangSmith.
89
98
 
90
- Returns:
91
- CallbackManagerForChainGroup: The callback manager for the chain group.
99
+ Yields:
100
+ The callback manager for the chain group.
92
101
 
93
102
  Example:
94
103
  .. code-block:: python
95
104
 
96
105
  llm_input = "Foo"
97
- with trace_as_chain_group("group_name", inputs={"input": llm_input}) as manager:
106
+ with trace_as_chain_group(
107
+ "group_name", inputs={"input": llm_input}
108
+ ) as manager:
98
109
  # Use the callback manager for the chain group
99
110
  res = llm.invoke(llm_input, {"callbacks": manager})
100
111
  manager.on_chain_end({"output": res})
101
112
 
102
- """ # noqa: E501
103
- from langchain_core.tracers.context import _get_trace_callbacks
104
-
113
+ """
105
114
  cb = _get_trace_callbacks(
106
115
  project_name, example_id, callback_manager=callback_manager
107
116
  )
@@ -153,8 +162,8 @@ async def atrace_as_chain_group(
153
162
 
154
163
  Args:
155
164
  group_name (str): The name of the chain group.
156
- callback_manager (AsyncCallbackManager, optional): The async callback manager to use,
157
- which manages tracing and other callback behavior. Defaults to None.
165
+ callback_manager (AsyncCallbackManager, optional): The async callback manager
166
+ to use, which manages tracing and other callback behavior. Defaults to None.
158
167
  inputs (dict[str, Any], optional): The inputs to the chain group.
159
168
  Defaults to None.
160
169
  project_name (str, optional): The name of the project.
@@ -167,24 +176,25 @@ async def atrace_as_chain_group(
167
176
  metadata (dict[str, Any], optional): The metadata to apply to all runs.
168
177
  Defaults to None.
169
178
 
170
- Returns:
171
- AsyncCallbackManager: The async callback manager for the chain group.
179
+ Yields:
180
+ The async callback manager for the chain group.
172
181
 
173
182
  .. note:
174
- Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in LangSmith.
183
+ Must have ``LANGCHAIN_TRACING_V2`` env var set to true to see the trace in
184
+ LangSmith.
175
185
 
176
186
  Example:
177
187
  .. code-block:: python
178
188
 
179
189
  llm_input = "Foo"
180
- async with atrace_as_chain_group("group_name", inputs={"input": llm_input}) as manager:
190
+ async with atrace_as_chain_group(
191
+ "group_name", inputs={"input": llm_input}
192
+ ) as manager:
181
193
  # Use the async callback manager for the chain group
182
194
  res = await llm.ainvoke(llm_input, {"callbacks": manager})
183
195
  await manager.on_chain_end({"output": res})
184
196
 
185
- """ # noqa: E501
186
- from langchain_core.tracers.context import _get_trace_callbacks
187
-
197
+ """
188
198
  cb = _get_trace_callbacks(
189
199
  project_name, example_id, callback_manager=callback_manager
190
200
  )
@@ -513,15 +523,12 @@ class RunManager(BaseRunManager):
513
523
  self,
514
524
  text: str,
515
525
  **kwargs: Any,
516
- ) -> Any:
526
+ ) -> None:
517
527
  """Run when a text is received.
518
528
 
519
529
  Args:
520
530
  text (str): The received text.
521
531
  **kwargs (Any): Additional keyword arguments.
522
-
523
- Returns:
524
- Any: The result of the callback.
525
532
  """
526
533
  if not self.handlers:
527
534
  return
@@ -601,16 +608,12 @@ class AsyncRunManager(BaseRunManager, ABC):
601
608
  self,
602
609
  text: str,
603
610
  **kwargs: Any,
604
- ) -> Any:
611
+ ) -> None:
605
612
  """Run when a text is received.
606
613
 
607
614
  Args:
608
615
  text (str): The received text.
609
616
  **kwargs (Any): Additional keyword arguments.
610
-
611
- Returns:
612
- Any: The result of the callback.
613
-
614
617
  """
615
618
  if not self.handlers:
616
619
  return
@@ -908,16 +911,12 @@ class CallbackManagerForChainRun(ParentRunManager, ChainManagerMixin):
908
911
  **kwargs,
909
912
  )
910
913
 
911
- def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
914
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
912
915
  """Run when agent action is received.
913
916
 
914
917
  Args:
915
918
  action (AgentAction): The agent action.
916
919
  **kwargs (Any): Additional keyword arguments.
917
-
918
- Returns:
919
- Any: The result of the callback.
920
-
921
920
  """
922
921
  if not self.handlers:
923
922
  return
@@ -932,16 +931,12 @@ class CallbackManagerForChainRun(ParentRunManager, ChainManagerMixin):
932
931
  **kwargs,
933
932
  )
934
933
 
935
- def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:
934
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
936
935
  """Run when agent finish is received.
937
936
 
938
937
  Args:
939
938
  finish (AgentFinish): The agent finish.
940
939
  **kwargs (Any): Additional keyword arguments.
941
-
942
- Returns:
943
- Any: The result of the callback.
944
-
945
940
  """
946
941
  if not self.handlers:
947
942
  return
@@ -1027,16 +1022,12 @@ class AsyncCallbackManagerForChainRun(AsyncParentRunManager, ChainManagerMixin):
1027
1022
  **kwargs,
1028
1023
  )
1029
1024
 
1030
- async def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
1025
+ async def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
1031
1026
  """Run when agent action is received.
1032
1027
 
1033
1028
  Args:
1034
1029
  action (AgentAction): The agent action.
1035
1030
  **kwargs (Any): Additional keyword arguments.
1036
-
1037
- Returns:
1038
- Any: The result of the callback.
1039
-
1040
1031
  """
1041
1032
  if not self.handlers:
1042
1033
  return
@@ -1051,16 +1042,12 @@ class AsyncCallbackManagerForChainRun(AsyncParentRunManager, ChainManagerMixin):
1051
1042
  **kwargs,
1052
1043
  )
1053
1044
 
1054
- async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:
1045
+ async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
1055
1046
  """Run when agent finish is received.
1056
1047
 
1057
1048
  Args:
1058
1049
  finish (AgentFinish): The agent finish.
1059
1050
  **kwargs (Any): Additional keyword arguments.
1060
-
1061
- Returns:
1062
- Any: The result of the callback.
1063
-
1064
1051
  """
1065
1052
  if not self.handlers:
1066
1053
  return
@@ -1556,6 +1543,8 @@ class CallbackManager(BaseCallbackManager):
1556
1543
  parent_run_id (UUID, optional): The ID of the parent run. Defaults to None.
1557
1544
  **kwargs (Any): Additional keyword arguments.
1558
1545
 
1546
+ Returns:
1547
+ The callback manager for the retriever run.
1559
1548
  """
1560
1549
  if run_id is None:
1561
1550
  run_id = uuid.uuid4()
@@ -1602,6 +1591,9 @@ class CallbackManager(BaseCallbackManager):
1602
1591
  data: The data for the adhoc event.
1603
1592
  run_id: The ID of the run. Defaults to None.
1604
1593
 
1594
+ Raises:
1595
+ ValueError: If additional keyword arguments are passed.
1596
+
1605
1597
  .. versionadded:: 0.2.14
1606
1598
 
1607
1599
  """
@@ -1704,8 +1696,8 @@ class CallbackManagerForChainGroup(CallbackManager):
1704
1696
  self.parent_run_manager = parent_run_manager
1705
1697
  self.ended = False
1706
1698
 
1699
+ @override
1707
1700
  def copy(self) -> CallbackManagerForChainGroup:
1708
- """Copy the callback manager."""
1709
1701
  return self.__class__(
1710
1702
  handlers=self.handlers.copy(),
1711
1703
  inheritable_handlers=self.inheritable_handlers.copy(),
@@ -1734,11 +1726,18 @@ class CallbackManagerForChainGroup(CallbackManager):
1734
1726
 
1735
1727
  .. code-block:: python
1736
1728
 
1737
- from langchain_core.callbacks.manager import CallbackManager, trace_as_chain_group
1729
+ from langchain_core.callbacks.manager import (
1730
+ CallbackManager,
1731
+ trace_as_chain_group,
1732
+ )
1738
1733
  from langchain_core.callbacks.stdout import StdOutCallbackHandler
1739
1734
 
1740
- manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
1741
- with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
1735
+ manager = CallbackManager(
1736
+ handlers=[StdOutCallbackHandler()], tags=["tag2"]
1737
+ )
1738
+ with trace_as_chain_group(
1739
+ "My Group Name", tags=["tag1"]
1740
+ ) as group_manager:
1742
1741
  merged_manager = group_manager.merge(manager)
1743
1742
  print(type(merged_manager))
1744
1743
  # <class 'langchain_core.callbacks.manager.CallbackManagerForChainGroup'>
@@ -2086,6 +2085,9 @@ class AsyncCallbackManager(BaseCallbackManager):
2086
2085
  data: The data for the adhoc event.
2087
2086
  run_id: The ID of the run. Defaults to None.
2088
2087
 
2088
+ Raises:
2089
+ ValueError: If additional keyword arguments are passed.
2090
+
2089
2091
  .. versionadded:: 0.2.14
2090
2092
  """
2091
2093
  if not self.handlers:
@@ -2236,7 +2238,7 @@ class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):
2236
2238
  self.ended = False
2237
2239
 
2238
2240
  def copy(self) -> AsyncCallbackManagerForChainGroup:
2239
- """Copy the async callback manager."""
2241
+ """Return a copy the async callback manager."""
2240
2242
  return self.__class__(
2241
2243
  handlers=self.handlers.copy(),
2242
2244
  inheritable_handlers=self.inheritable_handlers.copy(),
@@ -2258,18 +2260,25 @@ class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):
2258
2260
  from the current object.
2259
2261
 
2260
2262
  Returns:
2261
- AsyncCallbackManagerForChainGroup: A copy of the current AsyncCallbackManagerForChainGroup
2262
- with the handlers, tags, etc. of the other callback manager merged in.
2263
+ A copy of the current AsyncCallbackManagerForChainGroup
2264
+ with the handlers, tags, etc. of the other callback manager merged in.
2263
2265
 
2264
2266
  Example: Merging two callback managers.
2265
2267
 
2266
2268
  .. code-block:: python
2267
2269
 
2268
- from langchain_core.callbacks.manager import CallbackManager, atrace_as_chain_group
2270
+ from langchain_core.callbacks.manager import (
2271
+ CallbackManager,
2272
+ atrace_as_chain_group,
2273
+ )
2269
2274
  from langchain_core.callbacks.stdout import StdOutCallbackHandler
2270
2275
 
2271
- manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
2272
- async with atrace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
2276
+ manager = CallbackManager(
2277
+ handlers=[StdOutCallbackHandler()], tags=["tag2"]
2278
+ )
2279
+ async with atrace_as_chain_group(
2280
+ "My Group Name", tags=["tag1"]
2281
+ ) as group_manager:
2273
2282
  merged_manager = group_manager.merge(manager)
2274
2283
  print(type(merged_manager))
2275
2284
  # <class 'langchain_core.callbacks.manager.AsyncCallbackManagerForChainGroup'>
@@ -2365,16 +2374,12 @@ def _configure(
2365
2374
  local_metadata (Optional[dict[str, Any]], optional): The local metadata.
2366
2375
  Defaults to None.
2367
2376
 
2377
+ Raises:
2378
+ RuntimeError: If `LANGCHAIN_TRACING` is set but `LANGCHAIN_TRACING_V2` is not.
2379
+
2368
2380
  Returns:
2369
2381
  T: The configured callback manager.
2370
2382
  """
2371
- from langchain_core.tracers.context import (
2372
- _configure_hooks,
2373
- _get_tracer_project,
2374
- _tracing_v2_is_enabled,
2375
- tracing_v2_callback_var,
2376
- )
2377
-
2378
2383
  tracing_context = get_tracing_context()
2379
2384
  tracing_metadata = tracing_context["metadata"]
2380
2385
  tracing_tags = tracing_context["tags"]
@@ -2451,9 +2456,6 @@ def _configure(
2451
2456
  tracer_project = _get_tracer_project()
2452
2457
  debug = _get_debug()
2453
2458
  if verbose or debug or tracing_v2_enabled_:
2454
- from langchain_core.tracers.langchain import LangChainTracer
2455
- from langchain_core.tracers.stdout import ConsoleCallbackHandler
2456
-
2457
2459
  if verbose and not any(
2458
2460
  isinstance(handler, StdOutCallbackHandler)
2459
2461
  for handler in callback_manager.handlers
@@ -2537,6 +2539,10 @@ async def adispatch_custom_event(
2537
2539
  this is not enforced.
2538
2540
  config: Optional config object. Mirrors the async API but not strictly needed.
2539
2541
 
2542
+ Raises:
2543
+ RuntimeError: If there is no parent run ID available to associate
2544
+ the event with.
2545
+
2540
2546
  Example:
2541
2547
 
2542
2548
  .. code-block:: python
@@ -2618,7 +2624,8 @@ async def adispatch_custom_event(
2618
2624
  .. versionadded:: 0.2.15
2619
2625
 
2620
2626
  """
2621
- from langchain_core.runnables.config import (
2627
+ # Import locally to prevent circular imports.
2628
+ from langchain_core.runnables.config import ( # noqa: PLC0415
2622
2629
  ensure_config,
2623
2630
  get_async_callback_manager_for_config,
2624
2631
  )
@@ -2658,6 +2665,10 @@ def dispatch_custom_event(
2658
2665
  this is not enforced.
2659
2666
  config: Optional config object. Mirrors the async API but not strictly needed.
2660
2667
 
2668
+ Raises:
2669
+ RuntimeError: If there is no parent run ID available to associate
2670
+ the event with.
2671
+
2661
2672
  Example:
2662
2673
 
2663
2674
  .. code-block:: python
@@ -2689,7 +2700,8 @@ def dispatch_custom_event(
2689
2700
  .. versionadded:: 0.2.15
2690
2701
 
2691
2702
  """
2692
- from langchain_core.runnables.config import (
2703
+ # Import locally to prevent circular imports.
2704
+ from langchain_core.runnables.config import ( # noqa: PLC0415
2693
2705
  ensure_config,
2694
2706
  get_callback_manager_for_config,
2695
2707
  )