langchain-core 1.0.3__py3-none-any.whl → 1.0.5__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 (53) hide show
  1. langchain_core/agents.py +36 -27
  2. langchain_core/callbacks/base.py +1 -2
  3. langchain_core/callbacks/manager.py +19 -2
  4. langchain_core/callbacks/usage.py +2 -2
  5. langchain_core/documents/base.py +6 -6
  6. langchain_core/example_selectors/length_based.py +1 -1
  7. langchain_core/indexing/api.py +17 -14
  8. langchain_core/language_models/_utils.py +1 -1
  9. langchain_core/language_models/base.py +50 -20
  10. langchain_core/language_models/chat_models.py +48 -29
  11. langchain_core/language_models/llms.py +66 -36
  12. langchain_core/load/load.py +15 -9
  13. langchain_core/messages/ai.py +3 -3
  14. langchain_core/messages/base.py +4 -3
  15. langchain_core/messages/block_translators/__init__.py +2 -1
  16. langchain_core/messages/block_translators/openai.py +2 -1
  17. langchain_core/messages/content.py +2 -2
  18. langchain_core/messages/utils.py +12 -8
  19. langchain_core/output_parsers/openai_tools.py +14 -2
  20. langchain_core/outputs/chat_generation.py +4 -2
  21. langchain_core/outputs/generation.py +6 -5
  22. langchain_core/prompt_values.py +2 -2
  23. langchain_core/prompts/base.py +50 -45
  24. langchain_core/prompts/chat.py +35 -28
  25. langchain_core/prompts/dict.py +1 -1
  26. langchain_core/prompts/message.py +5 -5
  27. langchain_core/prompts/string.py +4 -2
  28. langchain_core/runnables/base.py +97 -52
  29. langchain_core/runnables/branch.py +22 -20
  30. langchain_core/runnables/configurable.py +30 -29
  31. langchain_core/runnables/fallbacks.py +22 -20
  32. langchain_core/runnables/graph.py +1 -2
  33. langchain_core/runnables/graph_ascii.py +2 -1
  34. langchain_core/runnables/graph_mermaid.py +4 -1
  35. langchain_core/runnables/graph_png.py +28 -0
  36. langchain_core/runnables/history.py +43 -32
  37. langchain_core/runnables/passthrough.py +35 -25
  38. langchain_core/runnables/router.py +5 -5
  39. langchain_core/runnables/schema.py +1 -1
  40. langchain_core/runnables/utils.py +3 -2
  41. langchain_core/sys_info.py +4 -2
  42. langchain_core/tools/base.py +22 -16
  43. langchain_core/tracers/core.py +6 -6
  44. langchain_core/utils/function_calling.py +11 -7
  45. langchain_core/utils/input.py +3 -0
  46. langchain_core/utils/json.py +4 -2
  47. langchain_core/utils/pydantic.py +5 -4
  48. langchain_core/vectorstores/base.py +1 -2
  49. langchain_core/vectorstores/in_memory.py +1 -2
  50. langchain_core/version.py +1 -1
  51. {langchain_core-1.0.3.dist-info → langchain_core-1.0.5.dist-info}/METADATA +2 -2
  52. {langchain_core-1.0.3.dist-info → langchain_core-1.0.5.dist-info}/RECORD +53 -53
  53. {langchain_core-1.0.3.dist-info → langchain_core-1.0.5.dist-info}/WHEEL +0 -0
@@ -651,9 +651,12 @@ class BaseLLM(BaseLanguageModel[str], ABC):
651
651
 
652
652
  Args:
653
653
  prompts: The prompts to generate from.
654
- stop: Stop words to use when generating. Model output is cut off at the
655
- first occurrence of any of the stop substrings.
656
- If stop tokens are not supported consider raising NotImplementedError.
654
+ stop: Stop words to use when generating.
655
+
656
+ Model output is cut off at the first occurrence of any of these
657
+ substrings.
658
+
659
+ If stop tokens are not supported consider raising `NotImplementedError`.
657
660
  run_manager: Callback manager for the run.
658
661
 
659
662
  Returns:
@@ -671,9 +674,12 @@ class BaseLLM(BaseLanguageModel[str], ABC):
671
674
 
672
675
  Args:
673
676
  prompts: The prompts to generate from.
674
- stop: Stop words to use when generating. Model output is cut off at the
675
- first occurrence of any of the stop substrings.
676
- If stop tokens are not supported consider raising NotImplementedError.
677
+ stop: Stop words to use when generating.
678
+
679
+ Model output is cut off at the first occurrence of any of these
680
+ substrings.
681
+
682
+ If stop tokens are not supported consider raising `NotImplementedError`.
677
683
  run_manager: Callback manager for the run.
678
684
 
679
685
  Returns:
@@ -705,11 +711,14 @@ class BaseLLM(BaseLanguageModel[str], ABC):
705
711
 
706
712
  Args:
707
713
  prompt: The prompt to generate from.
708
- stop: Stop words to use when generating. Model output is cut off at the
709
- first occurrence of any of these substrings.
714
+ stop: Stop words to use when generating.
715
+
716
+ Model output is cut off at the first occurrence of any of these
717
+ substrings.
710
718
  run_manager: Callback manager for the run.
711
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
712
- to the model provider API call.
719
+ **kwargs: Arbitrary additional keyword arguments.
720
+
721
+ These are usually passed to the model provider API call.
713
722
 
714
723
  Yields:
715
724
  Generation chunks.
@@ -731,11 +740,14 @@ class BaseLLM(BaseLanguageModel[str], ABC):
731
740
 
732
741
  Args:
733
742
  prompt: The prompt to generate from.
734
- stop: Stop words to use when generating. Model output is cut off at the
735
- first occurrence of any of these substrings.
743
+ stop: Stop words to use when generating.
744
+
745
+ Model output is cut off at the first occurrence of any of these
746
+ substrings.
736
747
  run_manager: Callback manager for the run.
737
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
738
- to the model provider API call.
748
+ **kwargs: Arbitrary additional keyword arguments.
749
+
750
+ These are usually passed to the model provider API call.
739
751
 
740
752
  Yields:
741
753
  Generation chunks.
@@ -846,10 +858,14 @@ class BaseLLM(BaseLanguageModel[str], ABC):
846
858
 
847
859
  Args:
848
860
  prompts: List of string prompts.
849
- stop: Stop words to use when generating. Model output is cut off at the
850
- first occurrence of any of these substrings.
851
- callbacks: `Callbacks` to pass through. Used for executing additional
852
- functionality, such as logging or streaming, throughout generation.
861
+ stop: Stop words to use when generating.
862
+
863
+ Model output is cut off at the first occurrence of any of these
864
+ substrings.
865
+ callbacks: `Callbacks` to pass through.
866
+
867
+ Used for executing additional functionality, such as logging or
868
+ streaming, throughout generation.
853
869
  tags: List of tags to associate with each prompt. If provided, the length
854
870
  of the list must match the length of the prompts list.
855
871
  metadata: List of metadata dictionaries to associate with each prompt. If
@@ -859,8 +875,9 @@ class BaseLLM(BaseLanguageModel[str], ABC):
859
875
  length of the list must match the length of the prompts list.
860
876
  run_id: List of run IDs to associate with each prompt. If provided, the
861
877
  length of the list must match the length of the prompts list.
862
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
863
- to the model provider API call.
878
+ **kwargs: Arbitrary additional keyword arguments.
879
+
880
+ These are usually passed to the model provider API call.
864
881
 
865
882
  Raises:
866
883
  ValueError: If prompts is not a list.
@@ -1116,10 +1133,14 @@ class BaseLLM(BaseLanguageModel[str], ABC):
1116
1133
 
1117
1134
  Args:
1118
1135
  prompts: List of string prompts.
1119
- stop: Stop words to use when generating. Model output is cut off at the
1120
- first occurrence of any of these substrings.
1121
- callbacks: `Callbacks` to pass through. Used for executing additional
1122
- functionality, such as logging or streaming, throughout generation.
1136
+ stop: Stop words to use when generating.
1137
+
1138
+ Model output is cut off at the first occurrence of any of these
1139
+ substrings.
1140
+ callbacks: `Callbacks` to pass through.
1141
+
1142
+ Used for executing additional functionality, such as logging or
1143
+ streaming, throughout generation.
1123
1144
  tags: List of tags to associate with each prompt. If provided, the length
1124
1145
  of the list must match the length of the prompts list.
1125
1146
  metadata: List of metadata dictionaries to associate with each prompt. If
@@ -1129,8 +1150,9 @@ class BaseLLM(BaseLanguageModel[str], ABC):
1129
1150
  length of the list must match the length of the prompts list.
1130
1151
  run_id: List of run IDs to associate with each prompt. If provided, the
1131
1152
  length of the list must match the length of the prompts list.
1132
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
1133
- to the model provider API call.
1153
+ **kwargs: Arbitrary additional keyword arguments.
1154
+
1155
+ These are usually passed to the model provider API call.
1134
1156
 
1135
1157
  Raises:
1136
1158
  ValueError: If the length of `callbacks`, `tags`, `metadata`, or
@@ -1410,12 +1432,16 @@ class LLM(BaseLLM):
1410
1432
 
1411
1433
  Args:
1412
1434
  prompt: The prompt to generate from.
1413
- stop: Stop words to use when generating. Model output is cut off at the
1414
- first occurrence of any of the stop substrings.
1415
- If stop tokens are not supported consider raising NotImplementedError.
1435
+ stop: Stop words to use when generating.
1436
+
1437
+ Model output is cut off at the first occurrence of any of these
1438
+ substrings.
1439
+
1440
+ If stop tokens are not supported consider raising `NotImplementedError`.
1416
1441
  run_manager: Callback manager for the run.
1417
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
1418
- to the model provider API call.
1442
+ **kwargs: Arbitrary additional keyword arguments.
1443
+
1444
+ These are usually passed to the model provider API call.
1419
1445
 
1420
1446
  Returns:
1421
1447
  The model output as a string. SHOULD NOT include the prompt.
@@ -1436,12 +1462,16 @@ class LLM(BaseLLM):
1436
1462
 
1437
1463
  Args:
1438
1464
  prompt: The prompt to generate from.
1439
- stop: Stop words to use when generating. Model output is cut off at the
1440
- first occurrence of any of the stop substrings.
1441
- If stop tokens are not supported consider raising NotImplementedError.
1465
+ stop: Stop words to use when generating.
1466
+
1467
+ Model output is cut off at the first occurrence of any of these
1468
+ substrings.
1469
+
1470
+ If stop tokens are not supported consider raising `NotImplementedError`.
1442
1471
  run_manager: Callback manager for the run.
1443
- **kwargs: Arbitrary additional keyword arguments. These are usually passed
1444
- to the model provider API call.
1472
+ **kwargs: Arbitrary additional keyword arguments.
1473
+
1474
+ These are usually passed to the model provider API call.
1445
1475
 
1446
1476
  Returns:
1447
1477
  The model output as a string. SHOULD NOT include the prompt.
@@ -61,13 +61,15 @@ class Reviver:
61
61
  """Initialize the reviver.
62
62
 
63
63
  Args:
64
- secrets_map: A map of secrets to load. If a secret is not found in
65
- the map, it will be loaded from the environment if `secrets_from_env`
66
- is True.
64
+ secrets_map: A map of secrets to load.
65
+
66
+ If a secret is not found in the map, it will be loaded from the
67
+ environment if `secrets_from_env` is `True`.
67
68
  valid_namespaces: A list of additional namespaces (modules)
68
69
  to allow to be deserialized.
69
70
  secrets_from_env: Whether to load secrets from the environment.
70
71
  additional_import_mappings: A dictionary of additional namespace mappings
72
+
71
73
  You can use this to override default mappings or add new mappings.
72
74
  ignore_unserializable_fields: Whether to ignore unserializable fields.
73
75
  """
@@ -195,13 +197,15 @@ def loads(
195
197
 
196
198
  Args:
197
199
  text: The string to load.
198
- secrets_map: A map of secrets to load. If a secret is not found in
199
- the map, it will be loaded from the environment if `secrets_from_env`
200
- is True.
200
+ secrets_map: A map of secrets to load.
201
+
202
+ If a secret is not found in the map, it will be loaded from the environment
203
+ if `secrets_from_env` is `True`.
201
204
  valid_namespaces: A list of additional namespaces (modules)
202
205
  to allow to be deserialized.
203
206
  secrets_from_env: Whether to load secrets from the environment.
204
207
  additional_import_mappings: A dictionary of additional namespace mappings
208
+
205
209
  You can use this to override default mappings or add new mappings.
206
210
  ignore_unserializable_fields: Whether to ignore unserializable fields.
207
211
 
@@ -237,13 +241,15 @@ def load(
237
241
 
238
242
  Args:
239
243
  obj: The object to load.
240
- secrets_map: A map of secrets to load. If a secret is not found in
241
- the map, it will be loaded from the environment if `secrets_from_env`
242
- is True.
244
+ secrets_map: A map of secrets to load.
245
+
246
+ If a secret is not found in the map, it will be loaded from the environment
247
+ if `secrets_from_env` is `True`.
243
248
  valid_namespaces: A list of additional namespaces (modules)
244
249
  to allow to be deserialized.
245
250
  secrets_from_env: Whether to load secrets from the environment.
246
251
  additional_import_mappings: A dictionary of additional namespace mappings
252
+
247
253
  You can use this to override default mappings or add new mappings.
248
254
  ignore_unserializable_fields: Whether to ignore unserializable fields.
249
255
 
@@ -50,7 +50,7 @@ class InputTokenDetails(TypedDict, total=False):
50
50
 
51
51
  May also hold extra provider-specific keys.
52
52
 
53
- !!! version-added "Added in version 0.3.9"
53
+ !!! version-added "Added in `langchain-core` 0.3.9"
54
54
 
55
55
  """
56
56
 
@@ -85,7 +85,7 @@ class OutputTokenDetails(TypedDict, total=False):
85
85
 
86
86
  May also hold extra provider-specific keys.
87
87
 
88
- !!! version-added "Added in version 0.3.9"
88
+ !!! version-added "Added in `langchain-core` 0.3.9"
89
89
 
90
90
  """
91
91
 
@@ -123,7 +123,7 @@ class UsageMetadata(TypedDict):
123
123
  }
124
124
  ```
125
125
 
126
- !!! warning "Behavior changed in 0.3.9"
126
+ !!! warning "Behavior changed in `langchain-core` 0.3.9"
127
127
  Added `input_token_details` and `output_token_details`.
128
128
 
129
129
  !!! note "LangSmith SDK"
@@ -5,11 +5,9 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING, Any, cast, overload
6
6
 
7
7
  from pydantic import ConfigDict, Field
8
- from typing_extensions import Self
9
8
 
10
9
  from langchain_core._api.deprecation import warn_deprecated
11
10
  from langchain_core.load.serializable import Serializable
12
- from langchain_core.messages import content as types
13
11
  from langchain_core.utils import get_bolded_text
14
12
  from langchain_core.utils._merge import merge_dicts, merge_lists
15
13
  from langchain_core.utils.interactive_env import is_interactive_env
@@ -17,6 +15,9 @@ from langchain_core.utils.interactive_env import is_interactive_env
17
15
  if TYPE_CHECKING:
18
16
  from collections.abc import Sequence
19
17
 
18
+ from typing_extensions import Self
19
+
20
+ from langchain_core.messages import content as types
20
21
  from langchain_core.prompts.chat import ChatPromptTemplate
21
22
 
22
23
 
@@ -199,7 +200,7 @@ class BaseMessage(Serializable):
199
200
  def content_blocks(self) -> list[types.ContentBlock]:
200
201
  r"""Load content blocks from the message content.
201
202
 
202
- !!! version-added "Added in version 1.0.0"
203
+ !!! version-added "Added in `langchain-core` 1.0.0"
203
204
 
204
205
  """
205
206
  # Needed here to avoid circular import, as these classes import BaseMessages
@@ -12,10 +12,11 @@ the implementation in `BaseMessage`.
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
- from collections.abc import Callable
16
15
  from typing import TYPE_CHECKING
17
16
 
18
17
  if TYPE_CHECKING:
18
+ from collections.abc import Callable
19
+
19
20
  from langchain_core.messages import AIMessage, AIMessageChunk
20
21
  from langchain_core.messages import content as types
21
22
 
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import warnings
7
- from collections.abc import Iterable
8
7
  from typing import TYPE_CHECKING, Any, Literal, cast
9
8
 
10
9
  from langchain_core.language_models._utils import (
@@ -14,6 +13,8 @@ from langchain_core.language_models._utils import (
14
13
  from langchain_core.messages import content as types
15
14
 
16
15
  if TYPE_CHECKING:
16
+ from collections.abc import Iterable
17
+
17
18
  from langchain_core.messages import AIMessage, AIMessageChunk
18
19
 
19
20
 
@@ -867,7 +867,7 @@ def _get_data_content_block_types() -> tuple[str, ...]:
867
867
  Example: ("image", "video", "audio", "text-plain", "file")
868
868
 
869
869
  Note that old style multimodal blocks type literals with new style blocks.
870
- Speficially, "image", "audio", and "file".
870
+ Specifically, "image", "audio", and "file".
871
871
 
872
872
  See the docstring of `_normalize_messages` in `language_models._utils` for details.
873
873
  """
@@ -906,7 +906,7 @@ def is_data_content_block(block: dict) -> bool:
906
906
 
907
907
  # 'text' is checked to support v0 PlainTextContentBlock types
908
908
  # We must guard against new style TextContentBlock which also has 'text' `type`
909
- # by ensuring the presense of `source_type`
909
+ # by ensuring the presence of `source_type`
910
910
  if block["type"] == "text" and "source_type" not in block: # noqa: SIM103 # This is more readable
911
911
  return False
912
912
 
@@ -328,12 +328,16 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
328
328
  """
329
329
  if isinstance(message, BaseMessage):
330
330
  message_ = message
331
- elif isinstance(message, str):
332
- message_ = _create_message_from_message_type("human", message)
333
- elif isinstance(message, Sequence) and len(message) == 2:
334
- # mypy doesn't realise this can't be a string given the previous branch
335
- message_type_str, template = message # type: ignore[misc]
336
- message_ = _create_message_from_message_type(message_type_str, template)
331
+ elif isinstance(message, Sequence):
332
+ if isinstance(message, str):
333
+ message_ = _create_message_from_message_type("human", message)
334
+ else:
335
+ try:
336
+ message_type_str, template = message
337
+ except ValueError as e:
338
+ msg = "Message as a sequence must be (role string, template)"
339
+ raise NotImplementedError(msg) from e
340
+ message_ = _create_message_from_message_type(message_type_str, template)
337
341
  elif isinstance(message, dict):
338
342
  msg_kwargs = message.copy()
339
343
  try:
@@ -1097,7 +1101,7 @@ def convert_to_openai_messages(
1097
1101
  # ]
1098
1102
  ```
1099
1103
 
1100
- !!! version-added "Added in version 0.3.11"
1104
+ !!! version-added "Added in `langchain-core` 0.3.11"
1101
1105
 
1102
1106
  """ # noqa: E501
1103
1107
  if text_format not in {"string", "block"}:
@@ -1697,7 +1701,7 @@ def count_tokens_approximately(
1697
1701
  Warning:
1698
1702
  This function does not currently support counting image tokens.
1699
1703
 
1700
- !!! version-added "Added in version 0.3.46"
1704
+ !!! version-added "Added in `langchain-core` 0.3.46"
1701
1705
 
1702
1706
  """
1703
1707
  token_count = 0.0
@@ -15,7 +15,11 @@ from langchain_core.messages.tool import tool_call as create_tool_call
15
15
  from langchain_core.output_parsers.transform import BaseCumulativeTransformOutputParser
16
16
  from langchain_core.outputs import ChatGeneration, Generation
17
17
  from langchain_core.utils.json import parse_partial_json
18
- from langchain_core.utils.pydantic import TypeBaseModel
18
+ from langchain_core.utils.pydantic import (
19
+ TypeBaseModel,
20
+ is_pydantic_v1_subclass,
21
+ is_pydantic_v2_subclass,
22
+ )
19
23
 
20
24
  logger = logging.getLogger(__name__)
21
25
 
@@ -323,7 +327,15 @@ class PydanticToolsParser(JsonOutputToolsParser):
323
327
  return None if self.first_tool_only else []
324
328
 
325
329
  json_results = [json_results] if self.first_tool_only else json_results
326
- name_dict = {tool.__name__: tool for tool in self.tools}
330
+ name_dict_v2: dict[str, TypeBaseModel] = {
331
+ tool.model_config.get("title") or tool.__name__: tool
332
+ for tool in self.tools
333
+ if is_pydantic_v2_subclass(tool)
334
+ }
335
+ name_dict_v1: dict[str, TypeBaseModel] = {
336
+ tool.__name__: tool for tool in self.tools if is_pydantic_v1_subclass(tool)
337
+ }
338
+ name_dict: dict[str, TypeBaseModel] = {**name_dict_v2, **name_dict_v1}
327
339
  pydantic_objects = []
328
340
  for res in json_results:
329
341
  if not isinstance(res["args"], dict):
@@ -2,15 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Literal
5
+ from typing import TYPE_CHECKING, Literal
6
6
 
7
7
  from pydantic import model_validator
8
- from typing_extensions import Self
9
8
 
10
9
  from langchain_core.messages import BaseMessage, BaseMessageChunk
11
10
  from langchain_core.outputs.generation import Generation
12
11
  from langchain_core.utils._merge import merge_dicts
13
12
 
13
+ if TYPE_CHECKING:
14
+ from typing_extensions import Self
15
+
14
16
 
15
17
  class ChatGeneration(Generation):
16
18
  """A single chat generation output.
@@ -20,8 +20,7 @@ class Generation(Serializable):
20
20
 
21
21
  LangChain users working with chat models will usually access information via
22
22
  `AIMessage` (returned from runnable interfaces) or `LLMResult` (available
23
- via callbacks). Please refer the `AIMessage` and `LLMResult` schema documentation
24
- for more information.
23
+ via callbacks). Please refer to `AIMessage` and `LLMResult` for more information.
25
24
  """
26
25
 
27
26
  text: str
@@ -34,11 +33,13 @@ class Generation(Serializable):
34
33
  """
35
34
  type: Literal["Generation"] = "Generation"
36
35
  """Type is used exclusively for serialization purposes.
37
- Set to "Generation" for this class."""
36
+
37
+ Set to "Generation" for this class.
38
+ """
38
39
 
39
40
  @classmethod
40
41
  def is_lc_serializable(cls) -> bool:
41
- """Return True as this class is serializable."""
42
+ """Return `True` as this class is serializable."""
42
43
  return True
43
44
 
44
45
  @classmethod
@@ -52,7 +53,7 @@ class Generation(Serializable):
52
53
 
53
54
 
54
55
  class GenerationChunk(Generation):
55
- """Generation chunk, which can be concatenated with other Generation chunks."""
56
+ """`GenerationChunk`, which can be concatenated with other Generation chunks."""
56
57
 
57
58
  def __add__(self, other: GenerationChunk) -> GenerationChunk:
58
59
  """Concatenate two `GenerationChunk`s.
@@ -30,7 +30,7 @@ class PromptValue(Serializable, ABC):
30
30
 
31
31
  @classmethod
32
32
  def is_lc_serializable(cls) -> bool:
33
- """Return True as this class is serializable."""
33
+ """Return `True` as this class is serializable."""
34
34
  return True
35
35
 
36
36
  @classmethod
@@ -48,7 +48,7 @@ class PromptValue(Serializable, ABC):
48
48
 
49
49
  @abstractmethod
50
50
  def to_messages(self) -> list[BaseMessage]:
51
- """Return prompt as a list of Messages."""
51
+ """Return prompt as a list of messages."""
52
52
 
53
53
 
54
54
  class StringPromptValue(PromptValue):