langchain-core 1.0.0a8__py3-none-any.whl → 1.0.0rc2__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 (142) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +0 -1
  3. langchain_core/_api/beta_decorator.py +17 -20
  4. langchain_core/_api/deprecation.py +30 -35
  5. langchain_core/_import_utils.py +1 -1
  6. langchain_core/agents.py +10 -9
  7. langchain_core/caches.py +46 -56
  8. langchain_core/callbacks/__init__.py +1 -8
  9. langchain_core/callbacks/base.py +232 -243
  10. langchain_core/callbacks/file.py +33 -33
  11. langchain_core/callbacks/manager.py +353 -416
  12. langchain_core/callbacks/stdout.py +21 -22
  13. langchain_core/callbacks/streaming_stdout.py +32 -32
  14. langchain_core/callbacks/usage.py +54 -51
  15. langchain_core/chat_history.py +43 -58
  16. langchain_core/document_loaders/base.py +21 -21
  17. langchain_core/document_loaders/langsmith.py +22 -22
  18. langchain_core/documents/__init__.py +0 -1
  19. langchain_core/documents/base.py +46 -49
  20. langchain_core/documents/transformers.py +28 -29
  21. langchain_core/embeddings/fake.py +50 -54
  22. langchain_core/example_selectors/semantic_similarity.py +4 -6
  23. langchain_core/exceptions.py +7 -8
  24. langchain_core/indexing/api.py +19 -25
  25. langchain_core/indexing/base.py +24 -24
  26. langchain_core/language_models/__init__.py +11 -27
  27. langchain_core/language_models/_utils.py +53 -54
  28. langchain_core/language_models/base.py +30 -24
  29. langchain_core/language_models/chat_models.py +123 -148
  30. langchain_core/language_models/fake_chat_models.py +7 -7
  31. langchain_core/language_models/llms.py +14 -16
  32. langchain_core/load/dump.py +3 -4
  33. langchain_core/load/load.py +7 -16
  34. langchain_core/load/serializable.py +37 -36
  35. langchain_core/messages/__init__.py +1 -16
  36. langchain_core/messages/ai.py +122 -123
  37. langchain_core/messages/base.py +31 -31
  38. langchain_core/messages/block_translators/__init__.py +17 -17
  39. langchain_core/messages/block_translators/anthropic.py +3 -3
  40. langchain_core/messages/block_translators/bedrock_converse.py +3 -3
  41. langchain_core/messages/block_translators/google_genai.py +5 -4
  42. langchain_core/messages/block_translators/google_vertexai.py +4 -32
  43. langchain_core/messages/block_translators/groq.py +117 -21
  44. langchain_core/messages/block_translators/langchain_v0.py +3 -3
  45. langchain_core/messages/block_translators/openai.py +5 -5
  46. langchain_core/messages/chat.py +2 -6
  47. langchain_core/messages/content.py +222 -209
  48. langchain_core/messages/function.py +6 -10
  49. langchain_core/messages/human.py +17 -24
  50. langchain_core/messages/modifier.py +2 -2
  51. langchain_core/messages/system.py +12 -22
  52. langchain_core/messages/tool.py +53 -69
  53. langchain_core/messages/utils.py +399 -417
  54. langchain_core/output_parsers/__init__.py +1 -14
  55. langchain_core/output_parsers/base.py +46 -47
  56. langchain_core/output_parsers/json.py +3 -4
  57. langchain_core/output_parsers/list.py +2 -2
  58. langchain_core/output_parsers/openai_functions.py +46 -44
  59. langchain_core/output_parsers/openai_tools.py +11 -16
  60. langchain_core/output_parsers/pydantic.py +10 -11
  61. langchain_core/output_parsers/string.py +2 -2
  62. langchain_core/output_parsers/transform.py +2 -2
  63. langchain_core/output_parsers/xml.py +1 -1
  64. langchain_core/outputs/__init__.py +1 -1
  65. langchain_core/outputs/chat_generation.py +14 -14
  66. langchain_core/outputs/generation.py +6 -6
  67. langchain_core/outputs/llm_result.py +5 -5
  68. langchain_core/prompt_values.py +11 -11
  69. langchain_core/prompts/__init__.py +3 -23
  70. langchain_core/prompts/base.py +33 -38
  71. langchain_core/prompts/chat.py +222 -229
  72. langchain_core/prompts/dict.py +3 -3
  73. langchain_core/prompts/few_shot.py +76 -83
  74. langchain_core/prompts/few_shot_with_templates.py +7 -9
  75. langchain_core/prompts/image.py +12 -14
  76. langchain_core/prompts/loading.py +1 -1
  77. langchain_core/prompts/message.py +3 -3
  78. langchain_core/prompts/prompt.py +20 -23
  79. langchain_core/prompts/string.py +20 -8
  80. langchain_core/prompts/structured.py +26 -27
  81. langchain_core/rate_limiters.py +50 -58
  82. langchain_core/retrievers.py +41 -182
  83. langchain_core/runnables/base.py +565 -597
  84. langchain_core/runnables/branch.py +8 -8
  85. langchain_core/runnables/config.py +37 -44
  86. langchain_core/runnables/configurable.py +9 -10
  87. langchain_core/runnables/fallbacks.py +9 -9
  88. langchain_core/runnables/graph.py +46 -50
  89. langchain_core/runnables/graph_ascii.py +19 -18
  90. langchain_core/runnables/graph_mermaid.py +20 -31
  91. langchain_core/runnables/graph_png.py +7 -7
  92. langchain_core/runnables/history.py +22 -22
  93. langchain_core/runnables/passthrough.py +11 -11
  94. langchain_core/runnables/retry.py +3 -3
  95. langchain_core/runnables/router.py +2 -2
  96. langchain_core/runnables/schema.py +33 -33
  97. langchain_core/runnables/utils.py +30 -34
  98. langchain_core/stores.py +72 -102
  99. langchain_core/sys_info.py +27 -29
  100. langchain_core/tools/__init__.py +1 -14
  101. langchain_core/tools/base.py +70 -71
  102. langchain_core/tools/convert.py +100 -104
  103. langchain_core/tools/render.py +9 -9
  104. langchain_core/tools/retriever.py +7 -7
  105. langchain_core/tools/simple.py +6 -7
  106. langchain_core/tools/structured.py +18 -24
  107. langchain_core/tracers/__init__.py +1 -9
  108. langchain_core/tracers/base.py +35 -35
  109. langchain_core/tracers/context.py +12 -17
  110. langchain_core/tracers/event_stream.py +3 -3
  111. langchain_core/tracers/langchain.py +8 -8
  112. langchain_core/tracers/log_stream.py +17 -18
  113. langchain_core/tracers/memory_stream.py +3 -3
  114. langchain_core/tracers/root_listeners.py +2 -2
  115. langchain_core/tracers/schemas.py +0 -129
  116. langchain_core/tracers/stdout.py +1 -2
  117. langchain_core/utils/__init__.py +1 -1
  118. langchain_core/utils/aiter.py +32 -32
  119. langchain_core/utils/env.py +5 -5
  120. langchain_core/utils/function_calling.py +59 -154
  121. langchain_core/utils/html.py +4 -4
  122. langchain_core/utils/input.py +3 -3
  123. langchain_core/utils/interactive_env.py +1 -1
  124. langchain_core/utils/iter.py +20 -20
  125. langchain_core/utils/json.py +1 -1
  126. langchain_core/utils/json_schema.py +2 -2
  127. langchain_core/utils/mustache.py +5 -5
  128. langchain_core/utils/pydantic.py +17 -17
  129. langchain_core/utils/strings.py +5 -5
  130. langchain_core/utils/utils.py +25 -28
  131. langchain_core/vectorstores/base.py +55 -87
  132. langchain_core/vectorstores/in_memory.py +83 -85
  133. langchain_core/vectorstores/utils.py +2 -2
  134. langchain_core/version.py +1 -1
  135. {langchain_core-1.0.0a8.dist-info → langchain_core-1.0.0rc2.dist-info}/METADATA +23 -11
  136. langchain_core-1.0.0rc2.dist-info/RECORD +172 -0
  137. langchain_core/memory.py +0 -120
  138. langchain_core/pydantic_v1/__init__.py +0 -30
  139. langchain_core/pydantic_v1/dataclasses.py +0 -23
  140. langchain_core/pydantic_v1/main.py +0 -23
  141. langchain_core-1.0.0a8.dist-info/RECORD +0 -176
  142. {langchain_core-1.0.0a8.dist-info → langchain_core-1.0.0rc2.dist-info}/WHEEL +0 -0
@@ -20,7 +20,7 @@ class StdOutCallbackHandler(BaseCallbackHandler):
20
20
  """Initialize callback handler.
21
21
 
22
22
  Args:
23
- color: The color to use for the text. Defaults to None.
23
+ color: The color to use for the text.
24
24
  """
25
25
  self.color = color
26
26
 
@@ -31,9 +31,9 @@ class StdOutCallbackHandler(BaseCallbackHandler):
31
31
  """Print out that we are entering a chain.
32
32
 
33
33
  Args:
34
- serialized (dict[str, Any]): The serialized chain.
35
- inputs (dict[str, Any]): The inputs to the chain.
36
- **kwargs (Any): Additional keyword arguments.
34
+ serialized: The serialized chain.
35
+ inputs: The inputs to the chain.
36
+ **kwargs: Additional keyword arguments.
37
37
  """
38
38
  if "name" in kwargs:
39
39
  name = kwargs["name"]
@@ -48,8 +48,8 @@ class StdOutCallbackHandler(BaseCallbackHandler):
48
48
  """Print out that we finished a chain.
49
49
 
50
50
  Args:
51
- outputs (dict[str, Any]): The outputs of the chain.
52
- **kwargs (Any): Additional keyword arguments.
51
+ outputs: The outputs of the chain.
52
+ **kwargs: Additional keyword arguments.
53
53
  """
54
54
  print("\n\033[1m> Finished chain.\033[0m") # noqa: T201
55
55
 
@@ -60,9 +60,9 @@ class StdOutCallbackHandler(BaseCallbackHandler):
60
60
  """Run on agent action.
61
61
 
62
62
  Args:
63
- action (AgentAction): The agent action.
64
- color (Optional[str]): The color to use for the text. Defaults to None.
65
- **kwargs (Any): Additional keyword arguments.
63
+ action: The agent action.
64
+ color: The color to use for the text.
65
+ **kwargs: Additional keyword arguments.
66
66
  """
67
67
  print_text(action.log, color=color or self.color)
68
68
 
@@ -78,12 +78,11 @@ class StdOutCallbackHandler(BaseCallbackHandler):
78
78
  """If not the final action, print out observation.
79
79
 
80
80
  Args:
81
- output (Any): The output to print.
82
- color (Optional[str]): The color to use for the text. Defaults to None.
83
- observation_prefix (Optional[str]): The observation prefix.
84
- Defaults to None.
85
- llm_prefix (Optional[str]): The LLM prefix. Defaults to None.
86
- **kwargs (Any): Additional keyword arguments.
81
+ output: The output to print.
82
+ color: The color to use for the text.
83
+ observation_prefix: The observation prefix.
84
+ llm_prefix: The LLM prefix.
85
+ **kwargs: Additional keyword arguments.
87
86
  """
88
87
  output = str(output)
89
88
  if observation_prefix is not None:
@@ -103,10 +102,10 @@ class StdOutCallbackHandler(BaseCallbackHandler):
103
102
  """Run when the agent ends.
104
103
 
105
104
  Args:
106
- text (str): The text to print.
107
- color (Optional[str]): The color to use for the text. Defaults to None.
108
- end (str): The end character to use. Defaults to "".
109
- **kwargs (Any): Additional keyword arguments.
105
+ text: The text to print.
106
+ color: The color to use for the text.
107
+ end: The end character to use.
108
+ **kwargs: Additional keyword arguments.
110
109
  """
111
110
  print_text(text, color=color or self.color, end=end)
112
111
 
@@ -117,8 +116,8 @@ class StdOutCallbackHandler(BaseCallbackHandler):
117
116
  """Run on the agent end.
118
117
 
119
118
  Args:
120
- finish (AgentFinish): The agent finish.
121
- color (Optional[str]): The color to use for the text. Defaults to None.
122
- **kwargs (Any): Additional keyword arguments.
119
+ finish: The agent finish.
120
+ color: The color to use for the text.
121
+ **kwargs: Additional keyword arguments.
123
122
  """
124
123
  print_text(finish.log, color=color or self.color, end="\n")
@@ -24,9 +24,9 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
24
24
  """Run when LLM starts running.
25
25
 
26
26
  Args:
27
- serialized (dict[str, Any]): The serialized LLM.
28
- prompts (list[str]): The prompts to run.
29
- **kwargs (Any): Additional keyword arguments.
27
+ serialized: The serialized LLM.
28
+ prompts: The prompts to run.
29
+ **kwargs: Additional keyword arguments.
30
30
  """
31
31
 
32
32
  def on_chat_model_start(
@@ -38,9 +38,9 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
38
38
  """Run when LLM starts running.
39
39
 
40
40
  Args:
41
- serialized (dict[str, Any]): The serialized LLM.
42
- messages (list[list[BaseMessage]]): The messages to run.
43
- **kwargs (Any): Additional keyword arguments.
41
+ serialized: The serialized LLM.
42
+ messages: The messages to run.
43
+ **kwargs: Additional keyword arguments.
44
44
  """
45
45
 
46
46
  @override
@@ -48,8 +48,8 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
48
48
  """Run on new LLM token. Only available when streaming is enabled.
49
49
 
50
50
  Args:
51
- token (str): The new token.
52
- **kwargs (Any): Additional keyword arguments.
51
+ token: The new token.
52
+ **kwargs: Additional keyword arguments.
53
53
  """
54
54
  sys.stdout.write(token)
55
55
  sys.stdout.flush()
@@ -58,16 +58,16 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
58
58
  """Run when LLM ends running.
59
59
 
60
60
  Args:
61
- response (LLMResult): The response from the LLM.
62
- **kwargs (Any): Additional keyword arguments.
61
+ response: The response from the LLM.
62
+ **kwargs: Additional keyword arguments.
63
63
  """
64
64
 
65
65
  def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
66
66
  """Run when LLM errors.
67
67
 
68
68
  Args:
69
- error (BaseException): The error that occurred.
70
- **kwargs (Any): Additional keyword arguments.
69
+ error: The error that occurred.
70
+ **kwargs: Additional keyword arguments.
71
71
  """
72
72
 
73
73
  def on_chain_start(
@@ -76,25 +76,25 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
76
76
  """Run when a chain starts running.
77
77
 
78
78
  Args:
79
- serialized (dict[str, Any]): The serialized chain.
80
- inputs (dict[str, Any]): The inputs to the chain.
81
- **kwargs (Any): Additional keyword arguments.
79
+ serialized: The serialized chain.
80
+ inputs: The inputs to the chain.
81
+ **kwargs: Additional keyword arguments.
82
82
  """
83
83
 
84
84
  def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
85
85
  """Run when a chain ends running.
86
86
 
87
87
  Args:
88
- outputs (dict[str, Any]): The outputs of the chain.
89
- **kwargs (Any): Additional keyword arguments.
88
+ outputs: The outputs of the chain.
89
+ **kwargs: Additional keyword arguments.
90
90
  """
91
91
 
92
92
  def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
93
93
  """Run when chain errors.
94
94
 
95
95
  Args:
96
- error (BaseException): The error that occurred.
97
- **kwargs (Any): Additional keyword arguments.
96
+ error: The error that occurred.
97
+ **kwargs: Additional keyword arguments.
98
98
  """
99
99
 
100
100
  def on_tool_start(
@@ -103,47 +103,47 @@ class StreamingStdOutCallbackHandler(BaseCallbackHandler):
103
103
  """Run when the tool starts running.
104
104
 
105
105
  Args:
106
- serialized (dict[str, Any]): The serialized tool.
107
- input_str (str): The input string.
108
- **kwargs (Any): Additional keyword arguments.
106
+ serialized: The serialized tool.
107
+ input_str: The input string.
108
+ **kwargs: Additional keyword arguments.
109
109
  """
110
110
 
111
111
  def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
112
112
  """Run on agent action.
113
113
 
114
114
  Args:
115
- action (AgentAction): The agent action.
116
- **kwargs (Any): Additional keyword arguments.
115
+ action: The agent action.
116
+ **kwargs: Additional keyword arguments.
117
117
  """
118
118
 
119
119
  def on_tool_end(self, output: Any, **kwargs: Any) -> None:
120
120
  """Run when tool ends running.
121
121
 
122
122
  Args:
123
- output (Any): The output of the tool.
124
- **kwargs (Any): Additional keyword arguments.
123
+ output: The output of the tool.
124
+ **kwargs: Additional keyword arguments.
125
125
  """
126
126
 
127
127
  def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
128
128
  """Run when tool errors.
129
129
 
130
130
  Args:
131
- error (BaseException): The error that occurred.
132
- **kwargs (Any): Additional keyword arguments.
131
+ error: The error that occurred.
132
+ **kwargs: Additional keyword arguments.
133
133
  """
134
134
 
135
135
  def on_text(self, text: str, **kwargs: Any) -> None:
136
136
  """Run on an arbitrary text.
137
137
 
138
138
  Args:
139
- text (str): The text to print.
140
- **kwargs (Any): Additional keyword arguments.
139
+ text: The text to print.
140
+ **kwargs: Additional keyword arguments.
141
141
  """
142
142
 
143
143
  def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
144
144
  """Run on the agent end.
145
145
 
146
146
  Args:
147
- finish (AgentFinish): The agent finish.
148
- **kwargs (Any): Additional keyword arguments.
147
+ finish: The agent finish.
148
+ **kwargs: Additional keyword arguments.
149
149
  """
@@ -19,30 +19,29 @@ class UsageMetadataCallbackHandler(BaseCallbackHandler):
19
19
  """Callback Handler that tracks AIMessage.usage_metadata.
20
20
 
21
21
  Example:
22
- .. code-block:: python
23
-
24
- from langchain.chat_models import init_chat_model
25
- from langchain_core.callbacks import UsageMetadataCallbackHandler
26
-
27
- llm_1 = init_chat_model(model="openai:gpt-4o-mini")
28
- llm_2 = init_chat_model(model="anthropic:claude-3-5-haiku-latest")
29
-
30
- callback = UsageMetadataCallbackHandler()
31
- result_1 = llm_1.invoke("Hello", config={"callbacks": [callback]})
32
- result_2 = llm_2.invoke("Hello", config={"callbacks": [callback]})
33
- callback.usage_metadata
34
-
35
- .. code-block::
36
-
37
- {'gpt-4o-mini-2024-07-18': {'input_tokens': 8,
38
- 'output_tokens': 10,
39
- 'total_tokens': 18,
40
- 'input_token_details': {'audio': 0, 'cache_read': 0},
41
- 'output_token_details': {'audio': 0, 'reasoning': 0}},
42
- 'claude-3-5-haiku-20241022': {'input_tokens': 8,
43
- 'output_tokens': 21,
44
- 'total_tokens': 29,
45
- 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
22
+ ```python
23
+ from langchain.chat_models import init_chat_model
24
+ from langchain_core.callbacks import UsageMetadataCallbackHandler
25
+
26
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
27
+ llm_2 = init_chat_model(model="anthropic:claude-3-5-haiku-latest")
28
+
29
+ callback = UsageMetadataCallbackHandler()
30
+ result_1 = llm_1.invoke("Hello", config={"callbacks": [callback]})
31
+ result_2 = llm_2.invoke("Hello", config={"callbacks": [callback]})
32
+ callback.usage_metadata
33
+ ```
34
+ ```txt
35
+ {'gpt-4o-mini-2024-07-18': {'input_tokens': 8,
36
+ 'output_tokens': 10,
37
+ 'total_tokens': 18,
38
+ 'input_token_details': {'audio': 0, 'cache_read': 0},
39
+ 'output_token_details': {'audio': 0, 'reasoning': 0}},
40
+ 'claude-3-5-haiku-20241022': {'input_tokens': 8,
41
+ 'output_tokens': 21,
42
+ 'total_tokens': 29,
43
+ 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
44
+ ```
46
45
 
47
46
  !!! version-added "Added in version 0.3.49"
48
47
 
@@ -96,40 +95,44 @@ def get_usage_metadata_callback(
96
95
  """Get usage metadata callback.
97
96
 
98
97
  Get context manager for tracking usage metadata across chat model calls using
99
- ``AIMessage.usage_metadata``.
98
+ `AIMessage.usage_metadata`.
100
99
 
101
100
  Args:
102
- name (str): The name of the context variable. Defaults to
103
- ``'usage_metadata_callback'``.
101
+ name: The name of the context variable.
104
102
 
105
103
  Yields:
106
104
  The usage metadata callback.
107
105
 
108
106
  Example:
109
- .. code-block:: python
110
-
111
- from langchain.chat_models import init_chat_model
112
- from langchain_core.callbacks import get_usage_metadata_callback
113
-
114
- llm_1 = init_chat_model(model="openai:gpt-4o-mini")
115
- llm_2 = init_chat_model(model="anthropic:claude-3-5-haiku-latest")
116
-
117
- with get_usage_metadata_callback() as cb:
118
- llm_1.invoke("Hello")
119
- llm_2.invoke("Hello")
120
- print(cb.usage_metadata)
121
-
122
- .. code-block::
123
-
124
- {'gpt-4o-mini-2024-07-18': {'input_tokens': 8,
125
- 'output_tokens': 10,
126
- 'total_tokens': 18,
127
- 'input_token_details': {'audio': 0, 'cache_read': 0},
128
- 'output_token_details': {'audio': 0, 'reasoning': 0}},
129
- 'claude-3-5-haiku-20241022': {'input_tokens': 8,
130
- 'output_tokens': 21,
131
- 'total_tokens': 29,
132
- 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
107
+ ```python
108
+ from langchain.chat_models import init_chat_model
109
+ from langchain_core.callbacks import get_usage_metadata_callback
110
+
111
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
112
+ llm_2 = init_chat_model(model="anthropic:claude-3-5-haiku-latest")
113
+
114
+ with get_usage_metadata_callback() as cb:
115
+ llm_1.invoke("Hello")
116
+ llm_2.invoke("Hello")
117
+ print(cb.usage_metadata)
118
+ ```
119
+ ```txt
120
+ {
121
+ "gpt-4o-mini-2024-07-18": {
122
+ "input_tokens": 8,
123
+ "output_tokens": 10,
124
+ "total_tokens": 18,
125
+ "input_token_details": {"audio": 0, "cache_read": 0},
126
+ "output_token_details": {"audio": 0, "reasoning": 0},
127
+ },
128
+ "claude-3-5-haiku-20241022": {
129
+ "input_tokens": 8,
130
+ "output_tokens": 21,
131
+ "total_tokens": 29,
132
+ "input_token_details": {"cache_read": 0, "cache_creation": 0},
133
+ },
134
+ }
135
+ ```
133
136
 
134
137
  !!! version-added "Added in version 0.3.49"
135
138
 
@@ -1,18 +1,4 @@
1
- """**Chat message history** stores a history of the message interactions in a chat.
2
-
3
- **Class hierarchy:**
4
-
5
- .. code-block::
6
-
7
- BaseChatMessageHistory --> <name>ChatMessageHistory # Examples: FileChatMessageHistory, PostgresChatMessageHistory
8
-
9
- **Main helpers:**
10
-
11
- .. code-block::
12
-
13
- AIMessage, HumanMessage, BaseMessage
14
-
15
- """ # noqa: E501
1
+ """**Chat message history** stores a history of the message interactions in a chat."""
16
2
 
17
3
  from __future__ import annotations
18
4
 
@@ -63,46 +49,45 @@ class BaseChatMessageHistory(ABC):
63
49
 
64
50
  Example: Shows a default implementation.
65
51
 
66
- .. code-block:: python
67
-
68
- import json
69
- import os
70
- from langchain_core.messages import messages_from_dict, message_to_dict
71
-
72
-
73
- class FileChatMessageHistory(BaseChatMessageHistory):
74
- storage_path: str
75
- session_id: str
76
-
77
- @property
78
- def messages(self) -> list[BaseMessage]:
79
- try:
80
- with open(
81
- os.path.join(self.storage_path, self.session_id),
82
- "r",
83
- encoding="utf-8",
84
- ) as f:
85
- messages_data = json.load(f)
86
- return messages_from_dict(messages_data)
87
- except FileNotFoundError:
88
- return []
89
-
90
- def add_messages(self, messages: Sequence[BaseMessage]) -> None:
91
- all_messages = list(self.messages) # Existing messages
92
- all_messages.extend(messages) # Add new messages
93
-
94
- serialized = [message_to_dict(message) for message in all_messages]
95
- file_path = os.path.join(self.storage_path, self.session_id)
96
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
97
- with open(file_path, "w", encoding="utf-8") as f:
98
- json.dump(serialized, f)
99
-
100
- def clear(self) -> None:
101
- file_path = os.path.join(self.storage_path, self.session_id)
102
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
103
- with open(file_path, "w", encoding="utf-8") as f:
104
- json.dump([], f)
105
-
52
+ ```python
53
+ import json
54
+ import os
55
+ from langchain_core.messages import messages_from_dict, message_to_dict
56
+
57
+
58
+ class FileChatMessageHistory(BaseChatMessageHistory):
59
+ storage_path: str
60
+ session_id: str
61
+
62
+ @property
63
+ def messages(self) -> list[BaseMessage]:
64
+ try:
65
+ with open(
66
+ os.path.join(self.storage_path, self.session_id),
67
+ "r",
68
+ encoding="utf-8",
69
+ ) as f:
70
+ messages_data = json.load(f)
71
+ return messages_from_dict(messages_data)
72
+ except FileNotFoundError:
73
+ return []
74
+
75
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
76
+ all_messages = list(self.messages) # Existing messages
77
+ all_messages.extend(messages) # Add new messages
78
+
79
+ serialized = [message_to_dict(message) for message in all_messages]
80
+ file_path = os.path.join(self.storage_path, self.session_id)
81
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
82
+ with open(file_path, "w", encoding="utf-8") as f:
83
+ json.dump(serialized, f)
84
+
85
+ def clear(self) -> None:
86
+ file_path = os.path.join(self.storage_path, self.session_id)
87
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
88
+ with open(file_path, "w", encoding="utf-8") as f:
89
+ json.dump([], f)
90
+ ```
106
91
  """
107
92
 
108
93
  messages: list[BaseMessage]
@@ -130,7 +115,7 @@ class BaseChatMessageHistory(ABC):
130
115
  """Convenience method for adding a human message string to the store.
131
116
 
132
117
  !!! note
133
- This is a convenience method. Code should favor the bulk ``add_messages``
118
+ This is a convenience method. Code should favor the bulk `add_messages`
134
119
  interface instead to save on round-trips to the persistence layer.
135
120
 
136
121
  This method may be deprecated in a future release.
@@ -147,7 +132,7 @@ class BaseChatMessageHistory(ABC):
147
132
  """Convenience method for adding an AI message string to the store.
148
133
 
149
134
  !!! note
150
- This is a convenience method. Code should favor the bulk ``add_messages``
135
+ This is a convenience method. Code should favor the bulk `add_messages`
151
136
  interface instead to save on round-trips to the persistence layer.
152
137
 
153
138
  This method may be deprecated in a future release.
@@ -168,7 +153,7 @@ class BaseChatMessageHistory(ABC):
168
153
 
169
154
  Raises:
170
155
  NotImplementedError: If the sub-class has not implemented an efficient
171
- add_messages method.
156
+ `add_messages` method.
172
157
  """
173
158
  if type(self).add_messages != BaseChatMessageHistory.add_messages:
174
159
  # This means that the sub-class has implemented an efficient add_messages
@@ -35,38 +35,38 @@ class BaseLoader(ABC): # noqa: B024
35
35
  # Sub-classes should not implement this method directly. Instead, they
36
36
  # should implement the lazy load method.
37
37
  def load(self) -> list[Document]:
38
- """Load data into Document objects.
38
+ """Load data into `Document` objects.
39
39
 
40
40
  Returns:
41
- the documents.
41
+ The documents.
42
42
  """
43
43
  return list(self.lazy_load())
44
44
 
45
45
  async def aload(self) -> list[Document]:
46
- """Load data into Document objects.
46
+ """Load data into `Document` objects.
47
47
 
48
48
  Returns:
49
- the documents.
49
+ The documents.
50
50
  """
51
51
  return [document async for document in self.alazy_load()]
52
52
 
53
53
  def load_and_split(
54
54
  self, text_splitter: TextSplitter | None = None
55
55
  ) -> list[Document]:
56
- """Load Documents and split into chunks. Chunks are returned as Documents.
56
+ """Load Documents and split into chunks. Chunks are returned as `Document`.
57
57
 
58
58
  Do not override this method. It should be considered to be deprecated!
59
59
 
60
60
  Args:
61
- text_splitter: TextSplitter instance to use for splitting documents.
62
- Defaults to RecursiveCharacterTextSplitter.
61
+ text_splitter: `TextSplitter` instance to use for splitting documents.
62
+ Defaults to `RecursiveCharacterTextSplitter`.
63
63
 
64
64
  Raises:
65
- ImportError: If langchain-text-splitters is not installed
66
- and no text_splitter is provided.
65
+ ImportError: If `langchain-text-splitters` is not installed
66
+ and no `text_splitter` is provided.
67
67
 
68
68
  Returns:
69
- List of Documents.
69
+ List of `Document`.
70
70
  """
71
71
  if text_splitter is None:
72
72
  if not _HAS_TEXT_SPLITTERS:
@@ -86,10 +86,10 @@ class BaseLoader(ABC): # noqa: B024
86
86
  # Attention: This method will be upgraded into an abstractmethod once it's
87
87
  # implemented in all the existing subclasses.
88
88
  def lazy_load(self) -> Iterator[Document]:
89
- """A lazy loader for Documents.
89
+ """A lazy loader for `Document`.
90
90
 
91
91
  Yields:
92
- the documents.
92
+ The `Document` objects.
93
93
  """
94
94
  if type(self).load != BaseLoader.load:
95
95
  return iter(self.load())
@@ -97,10 +97,10 @@ class BaseLoader(ABC): # noqa: B024
97
97
  raise NotImplementedError(msg)
98
98
 
99
99
  async def alazy_load(self) -> AsyncIterator[Document]:
100
- """A lazy loader for Documents.
100
+ """A lazy loader for `Document`.
101
101
 
102
102
  Yields:
103
- the documents.
103
+ The `Document` objects.
104
104
  """
105
105
  iterator = await run_in_executor(None, self.lazy_load)
106
106
  done = object()
@@ -115,7 +115,7 @@ class BaseBlobParser(ABC):
115
115
  """Abstract interface for blob parsers.
116
116
 
117
117
  A blob parser provides a way to parse raw data stored in a blob into one
118
- or more documents.
118
+ or more `Document` objects.
119
119
 
120
120
  The parser can be composed with blob loaders, making it easy to reuse
121
121
  a parser independent of how the blob was originally loaded.
@@ -128,25 +128,25 @@ class BaseBlobParser(ABC):
128
128
  Subclasses are required to implement this method.
129
129
 
130
130
  Args:
131
- blob: Blob instance
131
+ blob: `Blob` instance
132
132
 
133
133
  Returns:
134
- Generator of documents
134
+ Generator of `Document` objects
135
135
  """
136
136
 
137
137
  def parse(self, blob: Blob) -> list[Document]:
138
- """Eagerly parse the blob into a document or documents.
138
+ """Eagerly parse the blob into a `Document` or `Document` objects.
139
139
 
140
140
  This is a convenience method for interactive development environment.
141
141
 
142
- Production applications should favor the lazy_parse method instead.
142
+ Production applications should favor the `lazy_parse` method instead.
143
143
 
144
144
  Subclasses should generally not over-ride this parse method.
145
145
 
146
146
  Args:
147
- blob: Blob instance
147
+ blob: `Blob` instance
148
148
 
149
149
  Returns:
150
- List of documents
150
+ List of `Document` objects
151
151
  """
152
152
  return list(self.lazy_parse(blob))