langchain-core 0.4.0.dev0__py3-none-any.whl → 1.0.0a2__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 (74) hide show
  1. langchain_core/_api/beta_decorator.py +2 -2
  2. langchain_core/_api/deprecation.py +1 -1
  3. langchain_core/beta/runnables/context.py +1 -1
  4. langchain_core/callbacks/base.py +14 -23
  5. langchain_core/callbacks/file.py +13 -2
  6. langchain_core/callbacks/manager.py +74 -157
  7. langchain_core/callbacks/streaming_stdout.py +3 -4
  8. langchain_core/callbacks/usage.py +2 -12
  9. langchain_core/chat_history.py +6 -6
  10. langchain_core/documents/base.py +1 -1
  11. langchain_core/documents/compressor.py +9 -6
  12. langchain_core/indexing/base.py +2 -2
  13. langchain_core/language_models/_utils.py +232 -101
  14. langchain_core/language_models/base.py +35 -23
  15. langchain_core/language_models/chat_models.py +248 -54
  16. langchain_core/language_models/fake_chat_models.py +28 -81
  17. langchain_core/load/dump.py +3 -4
  18. langchain_core/messages/__init__.py +30 -24
  19. langchain_core/messages/ai.py +188 -30
  20. langchain_core/messages/base.py +164 -25
  21. langchain_core/messages/block_translators/__init__.py +89 -0
  22. langchain_core/messages/block_translators/anthropic.py +451 -0
  23. langchain_core/messages/block_translators/bedrock.py +45 -0
  24. langchain_core/messages/block_translators/bedrock_converse.py +47 -0
  25. langchain_core/messages/block_translators/google_genai.py +45 -0
  26. langchain_core/messages/block_translators/google_vertexai.py +47 -0
  27. langchain_core/messages/block_translators/groq.py +45 -0
  28. langchain_core/messages/block_translators/langchain_v0.py +164 -0
  29. langchain_core/messages/block_translators/ollama.py +45 -0
  30. langchain_core/messages/block_translators/openai.py +798 -0
  31. langchain_core/messages/{content_blocks.py → content.py} +303 -278
  32. langchain_core/messages/human.py +29 -9
  33. langchain_core/messages/system.py +29 -9
  34. langchain_core/messages/tool.py +94 -13
  35. langchain_core/messages/utils.py +34 -234
  36. langchain_core/output_parsers/base.py +14 -50
  37. langchain_core/output_parsers/json.py +2 -5
  38. langchain_core/output_parsers/list.py +2 -7
  39. langchain_core/output_parsers/openai_functions.py +5 -28
  40. langchain_core/output_parsers/openai_tools.py +49 -90
  41. langchain_core/output_parsers/pydantic.py +2 -3
  42. langchain_core/output_parsers/transform.py +12 -53
  43. langchain_core/output_parsers/xml.py +9 -17
  44. langchain_core/prompt_values.py +8 -112
  45. langchain_core/prompts/chat.py +1 -3
  46. langchain_core/runnables/base.py +500 -451
  47. langchain_core/runnables/branch.py +1 -1
  48. langchain_core/runnables/fallbacks.py +4 -4
  49. langchain_core/runnables/history.py +1 -1
  50. langchain_core/runnables/passthrough.py +3 -3
  51. langchain_core/runnables/retry.py +1 -1
  52. langchain_core/runnables/router.py +1 -1
  53. langchain_core/structured_query.py +3 -7
  54. langchain_core/tools/base.py +14 -41
  55. langchain_core/tools/convert.py +2 -22
  56. langchain_core/tools/retriever.py +1 -8
  57. langchain_core/tools/structured.py +2 -10
  58. langchain_core/tracers/_streaming.py +6 -7
  59. langchain_core/tracers/base.py +7 -14
  60. langchain_core/tracers/core.py +4 -27
  61. langchain_core/tracers/event_stream.py +4 -15
  62. langchain_core/tracers/langchain.py +3 -14
  63. langchain_core/tracers/log_stream.py +2 -3
  64. langchain_core/utils/_merge.py +45 -7
  65. langchain_core/utils/function_calling.py +22 -9
  66. langchain_core/utils/utils.py +29 -0
  67. langchain_core/version.py +1 -1
  68. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0a2.dist-info}/METADATA +7 -9
  69. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0a2.dist-info}/RECORD +71 -64
  70. langchain_core/v1/__init__.py +0 -1
  71. langchain_core/v1/chat_models.py +0 -1047
  72. langchain_core/v1/messages.py +0 -755
  73. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0a2.dist-info}/WHEEL +0 -0
  74. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0a2.dist-info}/entry_points.txt +0 -0
@@ -136,7 +136,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
136
136
  super().__init__(
137
137
  branches=branches_,
138
138
  default=default_,
139
- ) # type: ignore[call-arg]
139
+ )
140
140
 
141
141
  model_config = ConfigDict(
142
142
  arbitrary_types_allowed=True,
@@ -5,7 +5,7 @@ import inspect
5
5
  import typing
6
6
  from collections.abc import AsyncIterator, Iterator, Sequence
7
7
  from functools import wraps
8
- from typing import TYPE_CHECKING, Any, Optional, Union
8
+ from typing import TYPE_CHECKING, Any, Optional, Union, cast
9
9
 
10
10
  from pydantic import BaseModel, ConfigDict
11
11
  from typing_extensions import override
@@ -397,7 +397,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
397
397
  )
398
398
  )
399
399
 
400
- to_return = {}
400
+ to_return: dict[int, Union[Output, BaseException]] = {}
401
401
  run_again = dict(enumerate(inputs))
402
402
  handled_exceptions: dict[int, BaseException] = {}
403
403
  first_to_raise = None
@@ -447,7 +447,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
447
447
  if not return_exceptions and sorted_handled_exceptions:
448
448
  raise sorted_handled_exceptions[0][1]
449
449
  to_return.update(handled_exceptions)
450
- return [output for _, output in sorted(to_return.items())] # type: ignore[misc]
450
+ return [cast("Output", output) for _, output in sorted(to_return.items())]
451
451
 
452
452
  @override
453
453
  def stream(
@@ -569,7 +569,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
569
569
  async for chunk in stream:
570
570
  yield chunk
571
571
  try:
572
- output = output + chunk
572
+ output = output + chunk # type: ignore[operator]
573
573
  except TypeError:
574
574
  output = None
575
575
  except BaseException as e:
@@ -38,7 +38,7 @@ MessagesOrDictWithMessages = Union[Sequence["BaseMessage"], dict[str, Any]]
38
38
  GetSessionHistoryCallable = Callable[..., BaseChatMessageHistory]
39
39
 
40
40
 
41
- class RunnableWithMessageHistory(RunnableBindingBase):
41
+ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
42
42
  """Runnable that manages chat message history for another Runnable.
43
43
 
44
44
  A chat message history is a sequence of messages that represent a conversation.
@@ -186,7 +186,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
186
186
  afunc = func
187
187
  func = None
188
188
 
189
- super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs) # type: ignore[call-arg]
189
+ super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs)
190
190
 
191
191
  @classmethod
192
192
  @override
@@ -406,7 +406,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
406
406
  mapper: A ``RunnableParallel`` instance that will be used to transform the
407
407
  input dictionary.
408
408
  """
409
- super().__init__(mapper=mapper, **kwargs) # type: ignore[call-arg]
409
+ super().__init__(mapper=mapper, **kwargs)
410
410
 
411
411
  @classmethod
412
412
  @override
@@ -710,7 +710,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
710
710
  Args:
711
711
  keys: A single key or a list of keys to pick from the input dictionary.
712
712
  """
713
- super().__init__(keys=keys, **kwargs) # type: ignore[call-arg]
713
+ super().__init__(keys=keys, **kwargs)
714
714
 
715
715
  @classmethod
716
716
  @override
@@ -47,7 +47,7 @@ class ExponentialJitterParams(TypedDict, total=False):
47
47
  """Random additional wait sampled from random.uniform(0, jitter)."""
48
48
 
49
49
 
50
- class RunnableRetry(RunnableBindingBase[Input, Output]):
50
+ class RunnableRetry(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
51
51
  """Retry a Runnable if it fails.
52
52
 
53
53
  RunnableRetry can be used to add retry logic to any object
@@ -87,7 +87,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
87
87
  Args:
88
88
  runnables: A mapping of keys to Runnables.
89
89
  """
90
- super().__init__( # type: ignore[call-arg]
90
+ super().__init__(
91
91
  runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}
92
92
  )
93
93
 
@@ -143,7 +143,7 @@ class Comparison(FilterDirective):
143
143
  value: The value to compare to.
144
144
  """
145
145
  # super exists from BaseModel
146
- super().__init__( # type: ignore[call-arg]
146
+ super().__init__(
147
147
  comparator=comparator, attribute=attribute, value=value, **kwargs
148
148
  )
149
149
 
@@ -166,9 +166,7 @@ class Operation(FilterDirective):
166
166
  arguments: The arguments to the operator.
167
167
  """
168
168
  # super exists from BaseModel
169
- super().__init__( # type: ignore[call-arg]
170
- operator=operator, arguments=arguments, **kwargs
171
- )
169
+ super().__init__(operator=operator, arguments=arguments, **kwargs)
172
170
 
173
171
 
174
172
  class StructuredQuery(Expr):
@@ -196,6 +194,4 @@ class StructuredQuery(Expr):
196
194
  limit: The limit on the number of results.
197
195
  """
198
196
  # super exists from BaseModel
199
- super().__init__( # type: ignore[call-arg]
200
- query=query, filter=filter, limit=limit, **kwargs
201
- )
197
+ super().__init__(query=query, filter=filter, limit=limit, **kwargs)
@@ -68,14 +68,20 @@ from langchain_core.utils.pydantic import (
68
68
  is_pydantic_v1_subclass,
69
69
  is_pydantic_v2_subclass,
70
70
  )
71
- from langchain_core.v1.messages import ToolMessage as ToolMessageV1
72
71
 
73
72
  if TYPE_CHECKING:
74
73
  import uuid
75
74
  from collections.abc import Sequence
76
75
 
77
76
  FILTERED_ARGS = ("run_manager", "callbacks")
78
- TOOL_MESSAGE_BLOCK_TYPES = ("text", "image_url", "image", "json", "search_result")
77
+ TOOL_MESSAGE_BLOCK_TYPES = (
78
+ "text",
79
+ "image_url",
80
+ "image",
81
+ "json",
82
+ "search_result",
83
+ "custom_tool_call_output",
84
+ )
79
85
 
80
86
 
81
87
  class SchemaAnnotationError(TypeError):
@@ -499,14 +505,6 @@ class ChildTool(BaseTool):
499
505
  two-tuple corresponding to the (content, artifact) of a ToolMessage.
500
506
  """
501
507
 
502
- message_version: Literal["v0", "v1"] = "v0"
503
- """Version of ToolMessage to return given
504
- :class:`~langchain_core.messages.content_blocks.ToolCall` input.
505
-
506
- If ``"v0"``, output will be a v0 :class:`~langchain_core.messages.tool.ToolMessage`.
507
- If ``"v1"``, output will be a v1 :class:`~langchain_core.messages.v1.ToolMessage`.
508
- """
509
-
510
508
  def __init__(self, **kwargs: Any) -> None:
511
509
  """Initialize the tool."""
512
510
  if (
@@ -844,7 +842,7 @@ class ChildTool(BaseTool):
844
842
 
845
843
  content = None
846
844
  artifact = None
847
- status: Literal["success", "error"] = "success"
845
+ status = "success"
848
846
  error_to_raise: Union[Exception, KeyboardInterrupt, None] = None
849
847
  try:
850
848
  child_config = patch_config(config, callbacks=run_manager.get_child())
@@ -888,14 +886,7 @@ class ChildTool(BaseTool):
888
886
  if error_to_raise:
889
887
  run_manager.on_tool_error(error_to_raise)
890
888
  raise error_to_raise
891
- output = _format_output(
892
- content,
893
- artifact,
894
- tool_call_id,
895
- self.name,
896
- status,
897
- message_version=self.message_version,
898
- )
889
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
899
890
  run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
900
891
  return output
901
892
 
@@ -961,7 +952,7 @@ class ChildTool(BaseTool):
961
952
  )
962
953
  content = None
963
954
  artifact = None
964
- status: Literal["success", "error"] = "success"
955
+ status = "success"
965
956
  error_to_raise: Optional[Union[Exception, KeyboardInterrupt]] = None
966
957
  try:
967
958
  tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input, tool_call_id)
@@ -1009,14 +1000,7 @@ class ChildTool(BaseTool):
1009
1000
  await run_manager.on_tool_error(error_to_raise)
1010
1001
  raise error_to_raise
1011
1002
 
1012
- output = _format_output(
1013
- content,
1014
- artifact,
1015
- tool_call_id,
1016
- self.name,
1017
- status,
1018
- message_version=self.message_version,
1019
- )
1003
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
1020
1004
  await run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
1021
1005
  return output
1022
1006
 
@@ -1154,9 +1138,7 @@ def _format_output(
1154
1138
  artifact: Any,
1155
1139
  tool_call_id: Optional[str],
1156
1140
  name: str,
1157
- status: Literal["success", "error"],
1158
- *,
1159
- message_version: Literal["v0", "v1"] = "v0",
1141
+ status: str,
1160
1142
  ) -> Union[ToolOutputMixin, Any]:
1161
1143
  """Format tool output as a ToolMessage if appropriate.
1162
1144
 
@@ -1166,7 +1148,6 @@ def _format_output(
1166
1148
  tool_call_id: The ID of the tool call.
1167
1149
  name: The name of the tool.
1168
1150
  status: The execution status.
1169
- message_version: The version of the ToolMessage to return.
1170
1151
 
1171
1152
  Returns:
1172
1153
  The formatted output, either as a ToolMessage or the original content.
@@ -1175,15 +1156,7 @@ def _format_output(
1175
1156
  return content
1176
1157
  if not _is_message_content_type(content):
1177
1158
  content = _stringify(content)
1178
- if message_version == "v0":
1179
- return ToolMessage(
1180
- content,
1181
- artifact=artifact,
1182
- tool_call_id=tool_call_id,
1183
- name=name,
1184
- status=status,
1185
- )
1186
- return ToolMessageV1(
1159
+ return ToolMessage(
1187
1160
  content,
1188
1161
  artifact=artifact,
1189
1162
  tool_call_id=tool_call_id,
@@ -22,7 +22,6 @@ def tool(
22
22
  response_format: Literal["content", "content_and_artifact"] = "content",
23
23
  parse_docstring: bool = False,
24
24
  error_on_invalid_docstring: bool = True,
25
- message_version: Literal["v0", "v1"] = "v0",
26
25
  ) -> Callable[[Union[Callable, Runnable]], BaseTool]: ...
27
26
 
28
27
 
@@ -38,7 +37,6 @@ def tool(
38
37
  response_format: Literal["content", "content_and_artifact"] = "content",
39
38
  parse_docstring: bool = False,
40
39
  error_on_invalid_docstring: bool = True,
41
- message_version: Literal["v0", "v1"] = "v0",
42
40
  ) -> BaseTool: ...
43
41
 
44
42
 
@@ -53,7 +51,6 @@ def tool(
53
51
  response_format: Literal["content", "content_and_artifact"] = "content",
54
52
  parse_docstring: bool = False,
55
53
  error_on_invalid_docstring: bool = True,
56
- message_version: Literal["v0", "v1"] = "v0",
57
54
  ) -> BaseTool: ...
58
55
 
59
56
 
@@ -68,7 +65,6 @@ def tool(
68
65
  response_format: Literal["content", "content_and_artifact"] = "content",
69
66
  parse_docstring: bool = False,
70
67
  error_on_invalid_docstring: bool = True,
71
- message_version: Literal["v0", "v1"] = "v0",
72
68
  ) -> Callable[[Union[Callable, Runnable]], BaseTool]: ...
73
69
 
74
70
 
@@ -83,7 +79,6 @@ def tool(
83
79
  response_format: Literal["content", "content_and_artifact"] = "content",
84
80
  parse_docstring: bool = False,
85
81
  error_on_invalid_docstring: bool = True,
86
- message_version: Literal["v0", "v1"] = "v0",
87
82
  ) -> Union[
88
83
  BaseTool,
89
84
  Callable[[Union[Callable, Runnable]], BaseTool],
@@ -123,11 +118,6 @@ def tool(
123
118
  error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
124
119
  whether to raise ValueError on invalid Google Style docstrings.
125
120
  Defaults to True.
126
- message_version: Version of ToolMessage to return given
127
- :class:`~langchain_core.messages.content_blocks.ToolCall` input.
128
-
129
- If ``"v0"``, output will be a v0 :class:`~langchain_core.messages.tool.ToolMessage`.
130
- If ``"v1"``, output will be a v1 :class:`~langchain_core.messages.v1.ToolMessage`.
131
121
 
132
122
  Returns:
133
123
  The tool.
@@ -226,7 +216,7 @@ def tool(
226
216
  \"\"\"
227
217
  return bar
228
218
 
229
- """ # noqa: D214, D410, D411, E501
219
+ """ # noqa: D214, D410, D411
230
220
 
231
221
  def _create_tool_factory(
232
222
  tool_name: str,
@@ -284,7 +274,6 @@ def tool(
284
274
  response_format=response_format,
285
275
  parse_docstring=parse_docstring,
286
276
  error_on_invalid_docstring=error_on_invalid_docstring,
287
- message_version=message_version,
288
277
  )
289
278
  # If someone doesn't want a schema applied, we must treat it as
290
279
  # a simple string->string function
@@ -301,7 +290,6 @@ def tool(
301
290
  return_direct=return_direct,
302
291
  coroutine=coroutine,
303
292
  response_format=response_format,
304
- message_version=message_version,
305
293
  )
306
294
 
307
295
  return _tool_factory
@@ -395,7 +383,6 @@ def convert_runnable_to_tool(
395
383
  name: Optional[str] = None,
396
384
  description: Optional[str] = None,
397
385
  arg_types: Optional[dict[str, type]] = None,
398
- message_version: Literal["v0", "v1"] = "v0",
399
386
  ) -> BaseTool:
400
387
  """Convert a Runnable into a BaseTool.
401
388
 
@@ -405,15 +392,10 @@ def convert_runnable_to_tool(
405
392
  name: The name of the tool. Defaults to None.
406
393
  description: The description of the tool. Defaults to None.
407
394
  arg_types: The types of the arguments. Defaults to None.
408
- message_version: Version of ToolMessage to return given
409
- :class:`~langchain_core.messages.content_blocks.ToolCall` input.
410
-
411
- If ``"v0"``, output will be a v0 :class:`~langchain_core.messages.tool.ToolMessage`.
412
- If ``"v1"``, output will be a v1 :class:`~langchain_core.messages.v1.ToolMessage`.
413
395
 
414
396
  Returns:
415
397
  The tool.
416
- """ # noqa: E501
398
+ """
417
399
  if args_schema:
418
400
  runnable = runnable.with_types(input_type=args_schema)
419
401
  description = description or _get_description_from_runnable(runnable)
@@ -426,7 +408,6 @@ def convert_runnable_to_tool(
426
408
  func=runnable.invoke,
427
409
  coroutine=runnable.ainvoke,
428
410
  description=description,
429
- message_version=message_version,
430
411
  )
431
412
 
432
413
  async def ainvoke_wrapper(
@@ -454,5 +435,4 @@ def convert_runnable_to_tool(
454
435
  coroutine=ainvoke_wrapper,
455
436
  description=description,
456
437
  args_schema=args_schema,
457
- message_version=message_version,
458
438
  )
@@ -72,7 +72,6 @@ def create_retriever_tool(
72
72
  document_prompt: Optional[BasePromptTemplate] = None,
73
73
  document_separator: str = "\n\n",
74
74
  response_format: Literal["content", "content_and_artifact"] = "content",
75
- message_version: Literal["v0", "v1"] = "v1",
76
75
  ) -> Tool:
77
76
  r"""Create a tool to do retrieval of documents.
78
77
 
@@ -89,15 +88,10 @@ def create_retriever_tool(
89
88
  "content_and_artifact" then the output is expected to be a two-tuple
90
89
  corresponding to the (content, artifact) of a ToolMessage (artifact
91
90
  being a list of documents in this case). Defaults to "content".
92
- message_version: Version of ToolMessage to return given
93
- :class:`~langchain_core.messages.content_blocks.ToolCall` input.
94
-
95
- If ``"v0"``, output will be a v0 :class:`~langchain_core.messages.tool.ToolMessage`.
96
- If ``"v1"``, output will be a v1 :class:`~langchain_core.messages.v1.ToolMessage`.
97
91
 
98
92
  Returns:
99
93
  Tool class to pass to an agent.
100
- """ # noqa: E501
94
+ """
101
95
  document_prompt = document_prompt or PromptTemplate.from_template("{page_content}")
102
96
  func = partial(
103
97
  _get_relevant_documents,
@@ -120,5 +114,4 @@ def create_retriever_tool(
120
114
  coroutine=afunc,
121
115
  args_schema=RetrieverInput,
122
116
  response_format=response_format,
123
- message_version=message_version,
124
117
  )
@@ -129,7 +129,6 @@ class StructuredTool(BaseTool):
129
129
  response_format: Literal["content", "content_and_artifact"] = "content",
130
130
  parse_docstring: bool = False,
131
131
  error_on_invalid_docstring: bool = False,
132
- message_version: Literal["v0", "v1"] = "v0",
133
132
  **kwargs: Any,
134
133
  ) -> StructuredTool:
135
134
  """Create tool from a given function.
@@ -158,12 +157,6 @@ class StructuredTool(BaseTool):
158
157
  error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
159
158
  whether to raise ValueError on invalid Google Style docstrings.
160
159
  Defaults to False.
161
- message_version: Version of ToolMessage to return given
162
- :class:`~langchain_core.messages.content_blocks.ToolCall` input.
163
-
164
- If ``"v0"``, output will be a v0 :class:`~langchain_core.messages.tool.ToolMessage`.
165
- If ``"v1"``, output will be a v1 :class:`~langchain_core.messages.v1.ToolMessage`.
166
-
167
160
  kwargs: Additional arguments to pass to the tool
168
161
 
169
162
  Returns:
@@ -182,7 +175,7 @@ class StructuredTool(BaseTool):
182
175
  tool = StructuredTool.from_function(add)
183
176
  tool.run(1, 2) # 3
184
177
 
185
- """ # noqa: E501
178
+ """
186
179
  if func is not None:
187
180
  source_function = func
188
181
  elif coroutine is not None:
@@ -235,11 +228,10 @@ class StructuredTool(BaseTool):
235
228
  name=name,
236
229
  func=func,
237
230
  coroutine=coroutine,
238
- args_schema=args_schema, # type: ignore[arg-type]
231
+ args_schema=args_schema,
239
232
  description=description_,
240
233
  return_direct=return_direct,
241
234
  response_format=response_format,
242
- message_version=message_version,
243
235
  **kwargs,
244
236
  )
245
237
 
@@ -1,15 +1,16 @@
1
1
  """Internal tracers used for stream_log and astream events implementations."""
2
2
 
3
- import abc
3
+ import typing
4
4
  from collections.abc import AsyncIterator, Iterator
5
- from typing import TypeVar
6
5
  from uuid import UUID
7
6
 
8
- T = TypeVar("T")
7
+ T = typing.TypeVar("T")
9
8
 
10
9
 
11
- class _StreamingCallbackHandler(abc.ABC):
12
- """For internal use.
10
+ # THIS IS USED IN LANGGRAPH.
11
+ @typing.runtime_checkable
12
+ class _StreamingCallbackHandler(typing.Protocol[T]):
13
+ """Types for streaming callback handlers.
13
14
 
14
15
  This is a common mixin that the callback handlers
15
16
  for both astream events and astream log inherit from.
@@ -18,13 +19,11 @@ class _StreamingCallbackHandler(abc.ABC):
18
19
  to produce callbacks for intermediate results.
19
20
  """
20
21
 
21
- @abc.abstractmethod
22
22
  def tap_output_aiter(
23
23
  self, run_id: UUID, output: AsyncIterator[T]
24
24
  ) -> AsyncIterator[T]:
25
25
  """Used for internal astream_log and astream events implementations."""
26
26
 
27
- @abc.abstractmethod
28
27
  def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
29
28
  """Used for internal astream_log and astream events implementations."""
30
29
 
@@ -17,7 +17,6 @@ from typing_extensions import override
17
17
  from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandler
18
18
  from langchain_core.exceptions import TracerException # noqa: F401
19
19
  from langchain_core.tracers.core import _TracerCore
20
- from langchain_core.v1.messages import AIMessage, AIMessageChunk, MessageV1
21
20
 
22
21
  if TYPE_CHECKING:
23
22
  from collections.abc import Sequence
@@ -55,7 +54,7 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC):
55
54
  def on_chat_model_start(
56
55
  self,
57
56
  serialized: dict[str, Any],
58
- messages: Union[list[list[BaseMessage]], list[MessageV1]],
57
+ messages: list[list[BaseMessage]],
59
58
  *,
60
59
  run_id: UUID,
61
60
  tags: Optional[list[str]] = None,
@@ -139,9 +138,7 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC):
139
138
  self,
140
139
  token: str,
141
140
  *,
142
- chunk: Optional[
143
- Union[GenerationChunk, ChatGenerationChunk, AIMessageChunk]
144
- ] = None,
141
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
145
142
  run_id: UUID,
146
143
  parent_run_id: Optional[UUID] = None,
147
144
  **kwargs: Any,
@@ -193,9 +190,7 @@ class BaseTracer(_TracerCore, BaseCallbackHandler, ABC):
193
190
  )
194
191
 
195
192
  @override
196
- def on_llm_end(
197
- self, response: Union[LLMResult, AIMessage], *, run_id: UUID, **kwargs: Any
198
- ) -> Run:
193
+ def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any) -> Run:
199
194
  """End a trace for an LLM run.
200
195
 
201
196
  Args:
@@ -567,7 +562,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
567
562
  async def on_chat_model_start(
568
563
  self,
569
564
  serialized: dict[str, Any],
570
- messages: Union[list[list[BaseMessage]], list[MessageV1]],
565
+ messages: list[list[BaseMessage]],
571
566
  *,
572
567
  run_id: UUID,
573
568
  parent_run_id: Optional[UUID] = None,
@@ -622,9 +617,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
622
617
  self,
623
618
  token: str,
624
619
  *,
625
- chunk: Optional[
626
- Union[GenerationChunk, ChatGenerationChunk, AIMessageChunk]
627
- ] = None,
620
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
628
621
  run_id: UUID,
629
622
  parent_run_id: Optional[UUID] = None,
630
623
  **kwargs: Any,
@@ -653,7 +646,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
653
646
  @override
654
647
  async def on_llm_end(
655
648
  self,
656
- response: Union[LLMResult, AIMessage],
649
+ response: LLMResult,
657
650
  *,
658
651
  run_id: UUID,
659
652
  parent_run_id: Optional[UUID] = None,
@@ -889,7 +882,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
889
882
  self,
890
883
  run: Run,
891
884
  token: str,
892
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk, AIMessageChunk]],
885
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]],
893
886
  ) -> None:
894
887
  """Process new LLM token."""
895
888
 
@@ -18,7 +18,6 @@ from typing import (
18
18
 
19
19
  from langchain_core.exceptions import TracerException
20
20
  from langchain_core.load import dumpd
21
- from langchain_core.messages.utils import convert_from_v1_message
22
21
  from langchain_core.outputs import (
23
22
  ChatGeneration,
24
23
  ChatGenerationChunk,
@@ -26,12 +25,6 @@ from langchain_core.outputs import (
26
25
  LLMResult,
27
26
  )
28
27
  from langchain_core.tracers.schemas import Run
29
- from langchain_core.v1.messages import (
30
- AIMessage,
31
- AIMessageChunk,
32
- MessageV1,
33
- MessageV1Types,
34
- )
35
28
 
36
29
  if TYPE_CHECKING:
37
30
  from collections.abc import Coroutine, Sequence
@@ -163,7 +156,7 @@ class _TracerCore(ABC):
163
156
  def _create_chat_model_run(
164
157
  self,
165
158
  serialized: dict[str, Any],
166
- messages: Union[list[list[BaseMessage]], list[MessageV1]],
159
+ messages: list[list[BaseMessage]],
167
160
  run_id: UUID,
168
161
  tags: Optional[list[str]] = None,
169
162
  parent_run_id: Optional[UUID] = None,
@@ -188,12 +181,6 @@ class _TracerCore(ABC):
188
181
  start_time = datetime.now(timezone.utc)
189
182
  if metadata:
190
183
  kwargs.update({"metadata": metadata})
191
- if isinstance(messages[0], MessageV1Types):
192
- # Convert from v1 messages to BaseMessage
193
- messages = [
194
- [convert_from_v1_message(msg) for msg in messages] # type: ignore[arg-type]
195
- ]
196
- messages = cast("list[list[BaseMessage]]", messages)
197
184
  return Run(
198
185
  id=run_id,
199
186
  parent_run_id=parent_run_id,
@@ -243,9 +230,7 @@ class _TracerCore(ABC):
243
230
  self,
244
231
  token: str,
245
232
  run_id: UUID,
246
- chunk: Optional[
247
- Union[GenerationChunk, ChatGenerationChunk, AIMessageChunk]
248
- ] = None,
233
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
249
234
  parent_run_id: Optional[UUID] = None, # noqa: ARG002
250
235
  ) -> Run:
251
236
  """Append token event to LLM run and return the run."""
@@ -291,15 +276,7 @@ class _TracerCore(ABC):
291
276
  )
292
277
  return llm_run
293
278
 
294
- def _complete_llm_run(
295
- self, response: Union[LLMResult, AIMessage], run_id: UUID
296
- ) -> Run:
297
- if isinstance(response, AIMessage):
298
- response = LLMResult(
299
- generations=[
300
- [ChatGeneration(message=convert_from_v1_message(response))]
301
- ]
302
- )
279
+ def _complete_llm_run(self, response: LLMResult, run_id: UUID) -> Run:
303
280
  llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
304
281
  if getattr(llm_run, "outputs", None) is None:
305
282
  llm_run.outputs = {}
@@ -581,7 +558,7 @@ class _TracerCore(ABC):
581
558
  self,
582
559
  run: Run, # noqa: ARG002
583
560
  token: str, # noqa: ARG002
584
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk, AIMessageChunk]], # noqa: ARG002
561
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]], # noqa: ARG002
585
562
  ) -> Union[None, Coroutine[Any, Any, None]]:
586
563
  """Process new LLM token."""
587
564
  return None