langchain-core 0.3.79__py3-none-any.whl → 1.0.0__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 (165) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +23 -26
  4. langchain_core/_api/deprecation.py +52 -65
  5. langchain_core/_api/path.py +3 -6
  6. langchain_core/_import_utils.py +3 -4
  7. langchain_core/agents.py +19 -19
  8. langchain_core/caches.py +53 -63
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +323 -334
  11. langchain_core/callbacks/file.py +44 -44
  12. langchain_core/callbacks/manager.py +441 -507
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +32 -32
  15. langchain_core/callbacks/usage.py +60 -57
  16. langchain_core/chat_history.py +48 -63
  17. langchain_core/document_loaders/base.py +23 -23
  18. langchain_core/document_loaders/langsmith.py +37 -37
  19. langchain_core/documents/__init__.py +0 -1
  20. langchain_core/documents/base.py +62 -65
  21. langchain_core/documents/compressor.py +4 -4
  22. langchain_core/documents/transformers.py +28 -29
  23. langchain_core/embeddings/fake.py +50 -54
  24. langchain_core/example_selectors/length_based.py +1 -1
  25. langchain_core/example_selectors/semantic_similarity.py +21 -25
  26. langchain_core/exceptions.py +10 -11
  27. langchain_core/globals.py +3 -151
  28. langchain_core/indexing/api.py +61 -66
  29. langchain_core/indexing/base.py +58 -58
  30. langchain_core/indexing/in_memory.py +3 -3
  31. langchain_core/language_models/__init__.py +14 -27
  32. langchain_core/language_models/_utils.py +270 -84
  33. langchain_core/language_models/base.py +55 -162
  34. langchain_core/language_models/chat_models.py +442 -402
  35. langchain_core/language_models/fake.py +11 -11
  36. langchain_core/language_models/fake_chat_models.py +61 -39
  37. langchain_core/language_models/llms.py +123 -231
  38. langchain_core/load/dump.py +4 -5
  39. langchain_core/load/load.py +18 -28
  40. langchain_core/load/mapping.py +2 -4
  41. langchain_core/load/serializable.py +39 -40
  42. langchain_core/messages/__init__.py +61 -22
  43. langchain_core/messages/ai.py +368 -163
  44. langchain_core/messages/base.py +214 -43
  45. langchain_core/messages/block_translators/__init__.py +111 -0
  46. langchain_core/messages/block_translators/anthropic.py +470 -0
  47. langchain_core/messages/block_translators/bedrock.py +94 -0
  48. langchain_core/messages/block_translators/bedrock_converse.py +297 -0
  49. langchain_core/messages/block_translators/google_genai.py +530 -0
  50. langchain_core/messages/block_translators/google_vertexai.py +21 -0
  51. langchain_core/messages/block_translators/groq.py +143 -0
  52. langchain_core/messages/block_translators/langchain_v0.py +301 -0
  53. langchain_core/messages/block_translators/openai.py +1010 -0
  54. langchain_core/messages/chat.py +2 -6
  55. langchain_core/messages/content.py +1423 -0
  56. langchain_core/messages/function.py +6 -10
  57. langchain_core/messages/human.py +41 -38
  58. langchain_core/messages/modifier.py +2 -2
  59. langchain_core/messages/system.py +38 -28
  60. langchain_core/messages/tool.py +96 -103
  61. langchain_core/messages/utils.py +478 -504
  62. langchain_core/output_parsers/__init__.py +1 -14
  63. langchain_core/output_parsers/base.py +58 -61
  64. langchain_core/output_parsers/json.py +7 -8
  65. langchain_core/output_parsers/list.py +5 -7
  66. langchain_core/output_parsers/openai_functions.py +49 -47
  67. langchain_core/output_parsers/openai_tools.py +14 -19
  68. langchain_core/output_parsers/pydantic.py +12 -13
  69. langchain_core/output_parsers/string.py +2 -2
  70. langchain_core/output_parsers/transform.py +15 -17
  71. langchain_core/output_parsers/xml.py +8 -10
  72. langchain_core/outputs/__init__.py +1 -1
  73. langchain_core/outputs/chat_generation.py +18 -18
  74. langchain_core/outputs/chat_result.py +1 -3
  75. langchain_core/outputs/generation.py +8 -8
  76. langchain_core/outputs/llm_result.py +10 -10
  77. langchain_core/prompt_values.py +12 -12
  78. langchain_core/prompts/__init__.py +3 -27
  79. langchain_core/prompts/base.py +45 -55
  80. langchain_core/prompts/chat.py +254 -313
  81. langchain_core/prompts/dict.py +5 -5
  82. langchain_core/prompts/few_shot.py +81 -88
  83. langchain_core/prompts/few_shot_with_templates.py +11 -13
  84. langchain_core/prompts/image.py +12 -14
  85. langchain_core/prompts/loading.py +6 -8
  86. langchain_core/prompts/message.py +3 -3
  87. langchain_core/prompts/prompt.py +24 -39
  88. langchain_core/prompts/string.py +4 -4
  89. langchain_core/prompts/structured.py +42 -50
  90. langchain_core/rate_limiters.py +51 -60
  91. langchain_core/retrievers.py +49 -190
  92. langchain_core/runnables/base.py +1484 -1709
  93. langchain_core/runnables/branch.py +45 -61
  94. langchain_core/runnables/config.py +80 -88
  95. langchain_core/runnables/configurable.py +117 -134
  96. langchain_core/runnables/fallbacks.py +83 -79
  97. langchain_core/runnables/graph.py +85 -95
  98. langchain_core/runnables/graph_ascii.py +27 -28
  99. langchain_core/runnables/graph_mermaid.py +38 -50
  100. langchain_core/runnables/graph_png.py +15 -16
  101. langchain_core/runnables/history.py +135 -148
  102. langchain_core/runnables/passthrough.py +124 -150
  103. langchain_core/runnables/retry.py +46 -51
  104. langchain_core/runnables/router.py +25 -30
  105. langchain_core/runnables/schema.py +79 -74
  106. langchain_core/runnables/utils.py +62 -68
  107. langchain_core/stores.py +81 -115
  108. langchain_core/structured_query.py +8 -8
  109. langchain_core/sys_info.py +27 -29
  110. langchain_core/tools/__init__.py +1 -14
  111. langchain_core/tools/base.py +179 -187
  112. langchain_core/tools/convert.py +131 -139
  113. langchain_core/tools/render.py +10 -10
  114. langchain_core/tools/retriever.py +11 -11
  115. langchain_core/tools/simple.py +19 -24
  116. langchain_core/tools/structured.py +30 -39
  117. langchain_core/tracers/__init__.py +1 -9
  118. langchain_core/tracers/base.py +97 -99
  119. langchain_core/tracers/context.py +29 -52
  120. langchain_core/tracers/core.py +50 -60
  121. langchain_core/tracers/evaluation.py +11 -11
  122. langchain_core/tracers/event_stream.py +115 -70
  123. langchain_core/tracers/langchain.py +21 -21
  124. langchain_core/tracers/log_stream.py +43 -43
  125. langchain_core/tracers/memory_stream.py +3 -3
  126. langchain_core/tracers/root_listeners.py +16 -16
  127. langchain_core/tracers/run_collector.py +2 -4
  128. langchain_core/tracers/schemas.py +0 -129
  129. langchain_core/tracers/stdout.py +3 -3
  130. langchain_core/utils/__init__.py +1 -4
  131. langchain_core/utils/_merge.py +46 -8
  132. langchain_core/utils/aiter.py +57 -61
  133. langchain_core/utils/env.py +9 -9
  134. langchain_core/utils/function_calling.py +89 -191
  135. langchain_core/utils/html.py +7 -8
  136. langchain_core/utils/input.py +6 -6
  137. langchain_core/utils/interactive_env.py +1 -1
  138. langchain_core/utils/iter.py +37 -42
  139. langchain_core/utils/json.py +4 -3
  140. langchain_core/utils/json_schema.py +8 -8
  141. langchain_core/utils/mustache.py +9 -11
  142. langchain_core/utils/pydantic.py +33 -35
  143. langchain_core/utils/strings.py +5 -5
  144. langchain_core/utils/usage.py +1 -1
  145. langchain_core/utils/utils.py +80 -54
  146. langchain_core/vectorstores/base.py +129 -164
  147. langchain_core/vectorstores/in_memory.py +99 -174
  148. langchain_core/vectorstores/utils.py +5 -5
  149. langchain_core/version.py +1 -1
  150. {langchain_core-0.3.79.dist-info → langchain_core-1.0.0.dist-info}/METADATA +28 -27
  151. langchain_core-1.0.0.dist-info/RECORD +172 -0
  152. {langchain_core-0.3.79.dist-info → langchain_core-1.0.0.dist-info}/WHEEL +1 -1
  153. langchain_core/beta/__init__.py +0 -1
  154. langchain_core/beta/runnables/__init__.py +0 -1
  155. langchain_core/beta/runnables/context.py +0 -447
  156. langchain_core/memory.py +0 -120
  157. langchain_core/messages/content_blocks.py +0 -176
  158. langchain_core/prompts/pipeline.py +0 -138
  159. langchain_core/pydantic_v1/__init__.py +0 -30
  160. langchain_core/pydantic_v1/dataclasses.py +0 -23
  161. langchain_core/pydantic_v1/main.py +0 -23
  162. langchain_core/tracers/langchain_v1.py +0 -31
  163. langchain_core/utils/loading.py +0 -35
  164. langchain_core-0.3.79.dist-info/RECORD +0 -174
  165. langchain_core-0.3.79.dist-info/entry_points.txt +0 -4
@@ -8,10 +8,8 @@ from typing import (
8
8
  TYPE_CHECKING,
9
9
  Annotated,
10
10
  Any,
11
- Optional,
12
11
  TypedDict,
13
12
  TypeVar,
14
- Union,
15
13
  cast,
16
14
  overload,
17
15
  )
@@ -24,7 +22,6 @@ from pydantic import (
24
22
  )
25
23
  from typing_extensions import Self, override
26
24
 
27
- from langchain_core._api import deprecated
28
25
  from langchain_core.messages import (
29
26
  AIMessage,
30
27
  AnyMessage,
@@ -62,84 +59,83 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
62
59
 
63
60
  Direct usage:
64
61
 
65
- .. code-block:: python
62
+ ```python
63
+ from langchain_core.prompts import MessagesPlaceholder
66
64
 
67
- from langchain_core.prompts import MessagesPlaceholder
65
+ prompt = MessagesPlaceholder("history")
66
+ prompt.format_messages() # raises KeyError
68
67
 
69
- prompt = MessagesPlaceholder("history")
70
- prompt.format_messages() # raises KeyError
68
+ prompt = MessagesPlaceholder("history", optional=True)
69
+ prompt.format_messages() # returns empty list []
71
70
 
72
- prompt = MessagesPlaceholder("history", optional=True)
73
- prompt.format_messages() # returns empty list []
74
-
75
- prompt.format_messages(
76
- history=[
77
- ("system", "You are an AI assistant."),
78
- ("human", "Hello!"),
79
- ]
80
- )
81
- # -> [
82
- # SystemMessage(content="You are an AI assistant."),
83
- # HumanMessage(content="Hello!"),
84
- # ]
71
+ prompt.format_messages(
72
+ history=[
73
+ ("system", "You are an AI assistant."),
74
+ ("human", "Hello!"),
75
+ ]
76
+ )
77
+ # -> [
78
+ # SystemMessage(content="You are an AI assistant."),
79
+ # HumanMessage(content="Hello!"),
80
+ # ]
81
+ ```
85
82
 
86
83
  Building a prompt with chat history:
87
84
 
88
- .. code-block:: python
89
-
90
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
85
+ ```python
86
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
91
87
 
92
- prompt = ChatPromptTemplate.from_messages(
93
- [
94
- ("system", "You are a helpful assistant."),
95
- MessagesPlaceholder("history"),
96
- ("human", "{question}"),
97
- ]
98
- )
99
- prompt.invoke(
100
- {
101
- "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
102
- "question": "now multiply that by 4",
103
- }
104
- )
105
- # -> ChatPromptValue(messages=[
106
- # SystemMessage(content="You are a helpful assistant."),
107
- # HumanMessage(content="what's 5 + 2"),
108
- # AIMessage(content="5 + 2 is 7"),
109
- # HumanMessage(content="now multiply that by 4"),
110
- # ])
88
+ prompt = ChatPromptTemplate.from_messages(
89
+ [
90
+ ("system", "You are a helpful assistant."),
91
+ MessagesPlaceholder("history"),
92
+ ("human", "{question}"),
93
+ ]
94
+ )
95
+ prompt.invoke(
96
+ {
97
+ "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
98
+ "question": "now multiply that by 4",
99
+ }
100
+ )
101
+ # -> ChatPromptValue(messages=[
102
+ # SystemMessage(content="You are a helpful assistant."),
103
+ # HumanMessage(content="what's 5 + 2"),
104
+ # AIMessage(content="5 + 2 is 7"),
105
+ # HumanMessage(content="now multiply that by 4"),
106
+ # ])
107
+ ```
111
108
 
112
109
  Limiting the number of messages:
113
110
 
114
- .. code-block:: python
115
-
116
- from langchain_core.prompts import MessagesPlaceholder
111
+ ```python
112
+ from langchain_core.prompts import MessagesPlaceholder
117
113
 
118
- prompt = MessagesPlaceholder("history", n_messages=1)
119
-
120
- prompt.format_messages(
121
- history=[
122
- ("system", "You are an AI assistant."),
123
- ("human", "Hello!"),
124
- ]
125
- )
126
- # -> [
127
- # HumanMessage(content="Hello!"),
128
- # ]
114
+ prompt = MessagesPlaceholder("history", n_messages=1)
129
115
 
116
+ prompt.format_messages(
117
+ history=[
118
+ ("system", "You are an AI assistant."),
119
+ ("human", "Hello!"),
120
+ ]
121
+ )
122
+ # -> [
123
+ # HumanMessage(content="Hello!"),
124
+ # ]
125
+ ```
130
126
  """
131
127
 
132
128
  variable_name: str
133
129
  """Name of variable to use as messages."""
134
130
 
135
131
  optional: bool = False
136
- """If True format_messages can be called with no arguments and will return an empty
137
- list. If False then a named argument with name `variable_name` must be passed
138
- in, even if the value is an empty list."""
132
+ """If `True` format_messages can be called with no arguments and will return an
133
+ empty list. If `False` then a named argument with name `variable_name` must be
134
+ passed in, even if the value is an empty list."""
139
135
 
140
- n_messages: Optional[PositiveInt] = None
141
- """Maximum number of messages to include. If None, then will include all.
142
- Defaults to None."""
136
+ n_messages: PositiveInt | None = None
137
+ """Maximum number of messages to include. If `None`, then will include all.
138
+ """
143
139
 
144
140
  def __init__(
145
141
  self, variable_name: str, *, optional: bool = False, **kwargs: Any
@@ -148,10 +144,9 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
148
144
 
149
145
  Args:
150
146
  variable_name: Name of variable to use as messages.
151
- optional: If True format_messages can be called with no arguments and will
152
- return an empty list. If False then a named argument with name
147
+ optional: If `True` format_messages can be called with no arguments and will
148
+ return an empty list. If `False` then a named argument with name
153
149
  `variable_name` must be passed in, even if the value is an empty list.
154
- Defaults to False.]
155
150
  """
156
151
  # mypy can't detect the init which is defined in the parent class
157
152
  # b/c these are BaseModel classes.
@@ -199,7 +194,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
199
194
  """Human-readable representation.
200
195
 
201
196
  Args:
202
- html: Whether to format as HTML. Defaults to False.
197
+ html: Whether to format as HTML.
203
198
 
204
199
  Returns:
205
200
  Human-readable representation.
@@ -232,20 +227,20 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
232
227
  cls,
233
228
  template: str,
234
229
  template_format: PromptTemplateFormat = "f-string",
235
- partial_variables: Optional[dict[str, Any]] = None,
230
+ partial_variables: dict[str, Any] | None = None,
236
231
  **kwargs: Any,
237
232
  ) -> Self:
238
233
  """Create a class from a string template.
239
234
 
240
235
  Args:
241
236
  template: a template.
242
- template_format: format of the template. Defaults to "f-string".
237
+ template_format: format of the template.
243
238
  partial_variables: A dictionary of variables that can be used to partially
244
- fill in the template. For example, if the template is
245
- `"{variable1} {variable2}"`, and `partial_variables` is
246
- `{"variable1": "foo"}`, then the final prompt will be
247
- `"foo {variable2}"`.
248
- Defaults to None.
239
+ fill in the template. For example, if the template is
240
+ `"{variable1} {variable2}"`, and `partial_variables` is
241
+ `{"variable1": "foo"}`, then the final prompt will be
242
+ `"foo {variable2}"`.
243
+
249
244
  **kwargs: keyword arguments to pass to the constructor.
250
245
 
251
246
  Returns:
@@ -261,15 +256,13 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
261
256
  @classmethod
262
257
  def from_template_file(
263
258
  cls,
264
- template_file: Union[str, Path],
265
- input_variables: list[str], # noqa: ARG003 # Deprecated
259
+ template_file: str | Path,
266
260
  **kwargs: Any,
267
261
  ) -> Self:
268
262
  """Create a class from a template file.
269
263
 
270
264
  Args:
271
265
  template_file: path to a template file. String or Path.
272
- input_variables: list of input variables.
273
266
  **kwargs: keyword arguments to pass to the constructor.
274
267
 
275
268
  Returns:
@@ -336,7 +329,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
336
329
  """Human-readable representation.
337
330
 
338
331
  Args:
339
- html: Whether to format as HTML. Defaults to False.
332
+ html: Whether to format as HTML.
340
333
 
341
334
  Returns:
342
335
  Human-readable representation.
@@ -383,20 +376,20 @@ class ChatMessagePromptTemplate(BaseStringMessagePromptTemplate):
383
376
 
384
377
 
385
378
  class _TextTemplateParam(TypedDict, total=False):
386
- text: Union[str, dict]
379
+ text: str | dict
387
380
 
388
381
 
389
382
  class _ImageTemplateParam(TypedDict, total=False):
390
- image_url: Union[str, dict]
383
+ image_url: str | dict
391
384
 
392
385
 
393
386
  class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
394
387
  """Human message prompt template. This is a message sent from the user."""
395
388
 
396
- prompt: Union[
397
- StringPromptTemplate,
398
- list[Union[StringPromptTemplate, ImagePromptTemplate, DictPromptTemplate]],
399
- ]
389
+ prompt: (
390
+ StringPromptTemplate
391
+ | list[StringPromptTemplate | ImagePromptTemplate | DictPromptTemplate]
392
+ )
400
393
  """Prompt template."""
401
394
  additional_kwargs: dict = Field(default_factory=dict)
402
395
  """Additional keyword arguments to pass to the prompt template."""
@@ -406,13 +399,11 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
406
399
  @classmethod
407
400
  def from_template(
408
401
  cls: type[Self],
409
- template: Union[
410
- str,
411
- list[Union[str, _TextTemplateParam, _ImageTemplateParam, dict[str, Any]]],
412
- ],
402
+ template: str
403
+ | list[str | _TextTemplateParam | _ImageTemplateParam | dict[str, Any]],
413
404
  template_format: PromptTemplateFormat = "f-string",
414
405
  *,
415
- partial_variables: Optional[dict[str, Any]] = None,
406
+ partial_variables: dict[str, Any] | None = None,
416
407
  **kwargs: Any,
417
408
  ) -> Self:
418
409
  """Create a class from a string template.
@@ -420,9 +411,9 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
420
411
  Args:
421
412
  template: a template.
422
413
  template_format: format of the template.
423
- Options are: 'f-string', 'mustache', 'jinja2'. Defaults to "f-string".
414
+ Options are: 'f-string', 'mustache', 'jinja2'.
424
415
  partial_variables: A dictionary of variables that can be used too partially.
425
- Defaults to None.
416
+
426
417
  **kwargs: keyword arguments to pass to the constructor.
427
418
 
428
419
  Returns:
@@ -432,7 +423,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
432
423
  ValueError: If the template is not a string or list of strings.
433
424
  """
434
425
  if isinstance(template, str):
435
- prompt: Union[StringPromptTemplate, list] = PromptTemplate.from_template(
426
+ prompt: StringPromptTemplate | list = PromptTemplate.from_template(
436
427
  template,
437
428
  template_format=template_format,
438
429
  partial_variables=partial_variables,
@@ -529,7 +520,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
529
520
  @classmethod
530
521
  def from_template_file(
531
522
  cls: type[Self],
532
- template_file: Union[str, Path],
523
+ template_file: str | Path,
533
524
  input_variables: list[str],
534
525
  **kwargs: Any,
535
526
  ) -> Self:
@@ -543,8 +534,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
543
534
  Returns:
544
535
  A new instance of this class.
545
536
  """
546
- template = Path(template_file).read_text()
547
- # TODO: .read_text(encoding="utf-8") for v0.4
537
+ template = Path(template_file).read_text(encoding="utf-8")
548
538
  return cls.from_template(template, input_variables=input_variables, **kwargs)
549
539
 
550
540
  def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
@@ -597,9 +587,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
597
587
  for prompt in self.prompt:
598
588
  inputs = {var: kwargs[var] for var in prompt.input_variables}
599
589
  if isinstance(prompt, StringPromptTemplate):
600
- formatted: Union[str, ImageURL, dict[str, Any]] = prompt.format(
601
- **inputs
602
- )
590
+ formatted: str | ImageURL | dict[str, Any] = prompt.format(**inputs)
603
591
  content.append({"type": "text", "text": formatted})
604
592
  elif isinstance(prompt, ImagePromptTemplate):
605
593
  formatted = prompt.format(**inputs)
@@ -629,7 +617,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
629
617
  for prompt in self.prompt:
630
618
  inputs = {var: kwargs[var] for var in prompt.input_variables}
631
619
  if isinstance(prompt, StringPromptTemplate):
632
- formatted: Union[str, ImageURL, dict[str, Any]] = await prompt.aformat(
620
+ formatted: str | ImageURL | dict[str, Any] = await prompt.aformat(
633
621
  **inputs
634
622
  )
635
623
  content.append({"type": "text", "text": formatted})
@@ -648,7 +636,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
648
636
  """Human-readable representation.
649
637
 
650
638
  Args:
651
- html: Whether to format as HTML. Defaults to False.
639
+ html: Whether to format as HTML.
652
640
 
653
641
  Returns:
654
642
  Human-readable representation.
@@ -695,7 +683,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
695
683
 
696
684
  Args:
697
685
  **kwargs: keyword arguments to use for filling in template variables
698
- in all the template messages in this chat template.
686
+ in all the template messages in this chat template.
699
687
 
700
688
  Returns:
701
689
  formatted string.
@@ -707,7 +695,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
707
695
 
708
696
  Args:
709
697
  **kwargs: keyword arguments to use for filling in template variables
710
- in all the template messages in this chat template.
698
+ in all the template messages in this chat template.
711
699
 
712
700
  Returns:
713
701
  formatted string.
@@ -761,7 +749,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
761
749
  """Human-readable representation.
762
750
 
763
751
  Args:
764
- html: Whether to format as HTML. Defaults to False.
752
+ html: Whether to format as HTML.
765
753
 
766
754
  Returns:
767
755
  Human-readable representation.
@@ -773,17 +761,14 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
773
761
  print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
774
762
 
775
763
 
776
- MessageLike = Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate]
764
+ MessageLike = BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate
777
765
 
778
- MessageLikeRepresentation = Union[
779
- MessageLike,
780
- tuple[
781
- Union[str, type],
782
- Union[str, list[dict], list[object]],
783
- ],
784
- str,
785
- dict[str, Any],
786
- ]
766
+ MessageLikeRepresentation = (
767
+ MessageLike
768
+ | tuple[str | type, str | list[dict] | list[object]]
769
+ | str
770
+ | dict[str, Any]
771
+ )
787
772
 
788
773
 
789
774
  class ChatPromptTemplate(BaseChatPromptTemplate):
@@ -792,82 +777,80 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
792
777
  Use to create flexible templated prompts for chat models.
793
778
 
794
779
  Examples:
795
-
796
- .. versionchanged:: 0.2.24
797
-
780
+ !!! warning "Behavior changed in 0.2.24"
798
781
  You can pass any Message-like formats supported by
799
- ``ChatPromptTemplate.from_messages()`` directly to ``ChatPromptTemplate()``
782
+ `ChatPromptTemplate.from_messages()` directly to `ChatPromptTemplate()`
800
783
  init.
801
784
 
802
- .. code-block:: python
785
+ ```python
786
+ from langchain_core.prompts import ChatPromptTemplate
803
787
 
804
- from langchain_core.prompts import ChatPromptTemplate
805
-
806
- template = ChatPromptTemplate(
807
- [
808
- ("system", "You are a helpful AI bot. Your name is {name}."),
809
- ("human", "Hello, how are you doing?"),
810
- ("ai", "I'm doing well, thanks!"),
811
- ("human", "{user_input}"),
812
- ]
813
- )
788
+ template = ChatPromptTemplate(
789
+ [
790
+ ("system", "You are a helpful AI bot. Your name is {name}."),
791
+ ("human", "Hello, how are you doing?"),
792
+ ("ai", "I'm doing well, thanks!"),
793
+ ("human", "{user_input}"),
794
+ ]
795
+ )
814
796
 
815
- prompt_value = template.invoke(
816
- {
817
- "name": "Bob",
818
- "user_input": "What is your name?",
819
- }
820
- )
821
- # Output:
822
- # ChatPromptValue(
823
- # messages=[
824
- # SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
825
- # HumanMessage(content='Hello, how are you doing?'),
826
- # AIMessage(content="I'm doing well, thanks!"),
827
- # HumanMessage(content='What is your name?')
828
- # ]
829
- # )
797
+ prompt_value = template.invoke(
798
+ {
799
+ "name": "Bob",
800
+ "user_input": "What is your name?",
801
+ }
802
+ )
803
+ # Output:
804
+ # ChatPromptValue(
805
+ # messages=[
806
+ # SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
807
+ # HumanMessage(content='Hello, how are you doing?'),
808
+ # AIMessage(content="I'm doing well, thanks!"),
809
+ # HumanMessage(content='What is your name?')
810
+ # ]
811
+ # )
812
+ ```
830
813
 
831
814
  Messages Placeholder:
832
815
 
833
- .. code-block:: python
834
-
835
- # In addition to Human/AI/Tool/Function messages,
836
- # you can initialize the template with a MessagesPlaceholder
837
- # either using the class directly or with the shorthand tuple syntax:
816
+ ```python
817
+ # In addition to Human/AI/Tool/Function messages,
818
+ # you can initialize the template with a MessagesPlaceholder
819
+ # either using the class directly or with the shorthand tuple syntax:
820
+
821
+ template = ChatPromptTemplate(
822
+ [
823
+ ("system", "You are a helpful AI bot."),
824
+ # Means the template will receive an optional list of messages under
825
+ # the "conversation" key
826
+ ("placeholder", "{conversation}"),
827
+ # Equivalently:
828
+ # MessagesPlaceholder(variable_name="conversation", optional=True)
829
+ ]
830
+ )
838
831
 
839
- template = ChatPromptTemplate(
840
- [
841
- ("system", "You are a helpful AI bot."),
842
- # Means the template will receive an optional list of messages under
843
- # the "conversation" key
844
- ("placeholder", "{conversation}"),
845
- # Equivalently:
846
- # MessagesPlaceholder(variable_name="conversation", optional=True)
832
+ prompt_value = template.invoke(
833
+ {
834
+ "conversation": [
835
+ ("human", "Hi!"),
836
+ ("ai", "How can I assist you today?"),
837
+ ("human", "Can you make me an ice cream sundae?"),
838
+ ("ai", "No."),
847
839
  ]
848
- )
849
-
850
- prompt_value = template.invoke(
851
- {
852
- "conversation": [
853
- ("human", "Hi!"),
854
- ("ai", "How can I assist you today?"),
855
- ("human", "Can you make me an ice cream sundae?"),
856
- ("ai", "No."),
857
- ]
858
- }
859
- )
840
+ }
841
+ )
860
842
 
861
- # Output:
862
- # ChatPromptValue(
863
- # messages=[
864
- # SystemMessage(content='You are a helpful AI bot.'),
865
- # HumanMessage(content='Hi!'),
866
- # AIMessage(content='How can I assist you today?'),
867
- # HumanMessage(content='Can you make me an ice cream sundae?'),
868
- # AIMessage(content='No.'),
869
- # ]
870
- # )
843
+ # Output:
844
+ # ChatPromptValue(
845
+ # messages=[
846
+ # SystemMessage(content='You are a helpful AI bot.'),
847
+ # HumanMessage(content='Hi!'),
848
+ # AIMessage(content='How can I assist you today?'),
849
+ # HumanMessage(content='Can you make me an ice cream sundae?'),
850
+ # AIMessage(content='No.'),
851
+ # ]
852
+ # )
853
+ ```
871
854
 
872
855
  Single-variable template:
873
856
 
@@ -876,29 +859,28 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
876
859
  inject the provided argument into that variable location.
877
860
 
878
861
 
879
- .. code-block:: python
880
-
881
- from langchain_core.prompts import ChatPromptTemplate
882
-
883
- template = ChatPromptTemplate(
884
- [
885
- ("system", "You are a helpful AI bot. Your name is Carl."),
886
- ("human", "{user_input}"),
887
- ]
888
- )
889
-
890
- prompt_value = template.invoke("Hello, there!")
891
- # Equivalent to
892
- # prompt_value = template.invoke({"user_input": "Hello, there!"})
862
+ ```python
863
+ from langchain_core.prompts import ChatPromptTemplate
893
864
 
894
- # Output:
895
- # ChatPromptValue(
896
- # messages=[
897
- # SystemMessage(content='You are a helpful AI bot. Your name is Carl.'),
898
- # HumanMessage(content='Hello, there!'),
899
- # ]
900
- # )
865
+ template = ChatPromptTemplate(
866
+ [
867
+ ("system", "You are a helpful AI bot. Your name is Carl."),
868
+ ("human", "{user_input}"),
869
+ ]
870
+ )
901
871
 
872
+ prompt_value = template.invoke("Hello, there!")
873
+ # Equivalent to
874
+ # prompt_value = template.invoke({"user_input": "Hello, there!"})
875
+
876
+ # Output:
877
+ # ChatPromptValue(
878
+ # messages=[
879
+ # SystemMessage(content='You are a helpful AI bot. Your name is Carl.'),
880
+ # HumanMessage(content='Hello, there!'),
881
+ # ]
882
+ # )
883
+ ```
902
884
  """ # noqa: E501
903
885
 
904
886
  messages: Annotated[list[MessageLike], SkipValidation()]
@@ -917,12 +899,12 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
917
899
 
918
900
  Args:
919
901
  messages: sequence of message representations.
920
- A message can be represented using the following formats:
921
- (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
922
- (message type, template); e.g., ("human", "{user_input}"),
923
- (4) 2-tuple of (message class, template), (5) a string which is
924
- shorthand for ("human", template); e.g., "{user_input}".
925
- template_format: format of the template. Defaults to "f-string".
902
+ A message can be represented using the following formats:
903
+ (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
904
+ (message type, template); e.g., ("human", "{user_input}"),
905
+ (4) 2-tuple of (message class, template), (5) a string which is
906
+ shorthand for ("human", template); e.g., "{user_input}".
907
+ template_format: format of the template.
926
908
  input_variables: A list of the names of the variables whose values are
927
909
  required as inputs to the prompt.
928
910
  optional_variables: A list of the names of the variables for placeholder
@@ -939,27 +921,26 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
939
921
  Examples:
940
922
  Instantiation from a list of message templates:
941
923
 
942
- .. code-block:: python
943
-
944
- template = ChatPromptTemplate(
945
- [
946
- ("human", "Hello, how are you?"),
947
- ("ai", "I'm doing well, thanks!"),
948
- ("human", "That's good to hear."),
949
- ]
950
- )
924
+ ```python
925
+ template = ChatPromptTemplate(
926
+ [
927
+ ("human", "Hello, how are you?"),
928
+ ("ai", "I'm doing well, thanks!"),
929
+ ("human", "That's good to hear."),
930
+ ]
931
+ )
932
+ ```
951
933
 
952
934
  Instantiation from mixed message formats:
953
935
 
954
- .. code-block:: python
955
-
956
- template = ChatPromptTemplate(
957
- [
958
- SystemMessage(content="hello"),
959
- ("human", "Hello, how are you?"),
960
- ]
961
- )
962
-
936
+ ```python
937
+ template = ChatPromptTemplate(
938
+ [
939
+ SystemMessage(content="hello"),
940
+ ("human", "Hello, how are you?"),
941
+ ]
942
+ )
943
+ ```
963
944
  """
964
945
  messages_ = [
965
946
  _convert_to_message_template(message, template_format)
@@ -989,10 +970,10 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
989
970
 
990
971
  @classmethod
991
972
  def get_lc_namespace(cls) -> list[str]:
992
- """Get the namespace of the langchain object.
973
+ """Get the namespace of the LangChain object.
993
974
 
994
975
  Returns:
995
- ``["langchain", "prompts", "chat"]``
976
+ `["langchain", "prompts", "chat"]`
996
977
  """
997
978
  return ["langchain", "prompts", "chat"]
998
979
 
@@ -1108,41 +1089,6 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1108
1089
  message = HumanMessagePromptTemplate(prompt=prompt_template)
1109
1090
  return cls.from_messages([message])
1110
1091
 
1111
- @classmethod
1112
- @deprecated("0.0.1", alternative="from_messages", pending=True)
1113
- def from_role_strings(
1114
- cls, string_messages: list[tuple[str, str]]
1115
- ) -> ChatPromptTemplate:
1116
- """Create a chat prompt template from a list of (role, template) tuples.
1117
-
1118
- Args:
1119
- string_messages: list of (role, template) tuples.
1120
-
1121
- Returns:
1122
- a chat prompt template.
1123
- """
1124
- return cls(
1125
- messages=[
1126
- ChatMessagePromptTemplate.from_template(template, role=role)
1127
- for role, template in string_messages
1128
- ]
1129
- )
1130
-
1131
- @classmethod
1132
- @deprecated("0.0.1", alternative="from_messages", pending=True)
1133
- def from_strings(
1134
- cls, string_messages: list[tuple[type[BaseMessagePromptTemplate], str]]
1135
- ) -> ChatPromptTemplate:
1136
- """Create a chat prompt template from a list of (role class, template) tuples.
1137
-
1138
- Args:
1139
- string_messages: list of (role class, template) tuples.
1140
-
1141
- Returns:
1142
- a chat prompt template.
1143
- """
1144
- return cls.from_messages(string_messages)
1145
-
1146
1092
  @classmethod
1147
1093
  def from_messages(
1148
1094
  cls,
@@ -1154,35 +1100,34 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1154
1100
  Examples:
1155
1101
  Instantiation from a list of message templates:
1156
1102
 
1157
- .. code-block:: python
1158
-
1159
- template = ChatPromptTemplate.from_messages(
1160
- [
1161
- ("human", "Hello, how are you?"),
1162
- ("ai", "I'm doing well, thanks!"),
1163
- ("human", "That's good to hear."),
1164
- ]
1165
- )
1103
+ ```python
1104
+ template = ChatPromptTemplate.from_messages(
1105
+ [
1106
+ ("human", "Hello, how are you?"),
1107
+ ("ai", "I'm doing well, thanks!"),
1108
+ ("human", "That's good to hear."),
1109
+ ]
1110
+ )
1111
+ ```
1166
1112
 
1167
1113
  Instantiation from mixed message formats:
1168
1114
 
1169
- .. code-block:: python
1170
-
1171
- template = ChatPromptTemplate.from_messages(
1172
- [
1173
- SystemMessage(content="hello"),
1174
- ("human", "Hello, how are you?"),
1175
- ]
1176
- )
1177
-
1115
+ ```python
1116
+ template = ChatPromptTemplate.from_messages(
1117
+ [
1118
+ SystemMessage(content="hello"),
1119
+ ("human", "Hello, how are you?"),
1120
+ ]
1121
+ )
1122
+ ```
1178
1123
  Args:
1179
1124
  messages: sequence of message representations.
1180
- A message can be represented using the following formats:
1181
- (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
1182
- (message type, template); e.g., ("human", "{user_input}"),
1183
- (4) 2-tuple of (message class, template), (5) a string which is
1184
- shorthand for ("human", template); e.g., "{user_input}".
1185
- template_format: format of the template. Defaults to "f-string".
1125
+ A message can be represented using the following formats:
1126
+ (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
1127
+ (message type, template); e.g., ("human", "{user_input}"),
1128
+ (4) 2-tuple of (message class, template), (5) a string which is
1129
+ shorthand for ("human", template); e.g., "{user_input}".
1130
+ template_format: format of the template.
1186
1131
 
1187
1132
  Returns:
1188
1133
  a chat prompt template.
@@ -1195,7 +1140,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1195
1140
 
1196
1141
  Args:
1197
1142
  **kwargs: keyword arguments to use for filling in template variables
1198
- in all the template messages in this chat template.
1143
+ in all the template messages in this chat template.
1199
1144
 
1200
1145
  Raises:
1201
1146
  ValueError: if messages are of unexpected types.
@@ -1223,7 +1168,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1223
1168
 
1224
1169
  Args:
1225
1170
  **kwargs: keyword arguments to use for filling in template variables
1226
- in all the template messages in this chat template.
1171
+ in all the template messages in this chat template.
1227
1172
 
1228
1173
  Returns:
1229
1174
  list of formatted messages.
@@ -1258,23 +1203,21 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1258
1203
 
1259
1204
 
1260
1205
  Example:
1206
+ ```python
1207
+ from langchain_core.prompts import ChatPromptTemplate
1261
1208
 
1262
- .. code-block:: python
1263
-
1264
- from langchain_core.prompts import ChatPromptTemplate
1265
-
1266
- template = ChatPromptTemplate.from_messages(
1267
- [
1268
- ("system", "You are an AI assistant named {name}."),
1269
- ("human", "Hi I'm {user}"),
1270
- ("ai", "Hi there, {user}, I'm {name}."),
1271
- ("human", "{input}"),
1272
- ]
1273
- )
1274
- template2 = template.partial(user="Lucy", name="R2D2")
1275
-
1276
- template2.format_messages(input="hello")
1209
+ template = ChatPromptTemplate.from_messages(
1210
+ [
1211
+ ("system", "You are an AI assistant named {name}."),
1212
+ ("human", "Hi I'm {user}"),
1213
+ ("ai", "Hi there, {user}, I'm {name}."),
1214
+ ("human", "{input}"),
1215
+ ]
1216
+ )
1217
+ template2 = template.partial(user="Lucy", name="R2D2")
1277
1218
 
1219
+ template2.format_messages(input="hello")
1220
+ ```
1278
1221
  """
1279
1222
  prompt_dict = self.__dict__.copy()
1280
1223
  prompt_dict["input_variables"] = list(
@@ -1307,14 +1250,12 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1307
1250
  @overload
1308
1251
  def __getitem__(self, index: slice) -> ChatPromptTemplate: ...
1309
1252
 
1310
- def __getitem__(
1311
- self, index: Union[int, slice]
1312
- ) -> Union[MessageLike, ChatPromptTemplate]:
1253
+ def __getitem__(self, index: int | slice) -> MessageLike | ChatPromptTemplate:
1313
1254
  """Use to index into the chat template.
1314
1255
 
1315
1256
  Returns:
1316
1257
  If index is an int, returns the message at that index.
1317
- If index is a slice, returns a new ``ChatPromptTemplate``
1258
+ If index is a slice, returns a new `ChatPromptTemplate`
1318
1259
  containing the messages in that slice.
1319
1260
  """
1320
1261
  if isinstance(index, slice):
@@ -1332,7 +1273,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1332
1273
  """Name of prompt type. Used for serialization."""
1333
1274
  return "chat"
1334
1275
 
1335
- def save(self, file_path: Union[Path, str]) -> None:
1276
+ def save(self, file_path: Path | str) -> None:
1336
1277
  """Save prompt to file.
1337
1278
 
1338
1279
  Args:
@@ -1345,7 +1286,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1345
1286
  """Human-readable representation.
1346
1287
 
1347
1288
  Args:
1348
- html: Whether to format as HTML. Defaults to False.
1289
+ html: Whether to format as HTML.
1349
1290
 
1350
1291
  Returns:
1351
1292
  Human-readable representation.
@@ -1356,7 +1297,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
1356
1297
 
1357
1298
  def _create_template_from_message_type(
1358
1299
  message_type: str,
1359
- template: Union[str, list],
1300
+ template: str | list,
1360
1301
  template_format: PromptTemplateFormat = "f-string",
1361
1302
  ) -> BaseMessagePromptTemplate:
1362
1303
  """Create a message prompt template from a message type and template string.
@@ -1364,7 +1305,7 @@ def _create_template_from_message_type(
1364
1305
  Args:
1365
1306
  message_type: str the type of the message template (e.g., "human", "ai", etc.)
1366
1307
  template: str the template string.
1367
- template_format: format of the template. Defaults to "f-string".
1308
+ template_format: format of the template.
1368
1309
 
1369
1310
  Returns:
1370
1311
  a message prompt template of the appropriate type.
@@ -1428,7 +1369,7 @@ def _create_template_from_message_type(
1428
1369
  def _convert_to_message_template(
1429
1370
  message: MessageLikeRepresentation,
1430
1371
  template_format: PromptTemplateFormat = "f-string",
1431
- ) -> Union[BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate]:
1372
+ ) -> BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate:
1432
1373
  """Instantiate a message from a variety of message formats.
1433
1374
 
1434
1375
  The message format can be one of the following:
@@ -1441,7 +1382,7 @@ def _convert_to_message_template(
1441
1382
 
1442
1383
  Args:
1443
1384
  message: a representation of a message in one of the supported formats.
1444
- template_format: format of the template. Defaults to "f-string".
1385
+ template_format: format of the template.
1445
1386
 
1446
1387
  Returns:
1447
1388
  an instance of a message or a message template.
@@ -1451,9 +1392,9 @@ def _convert_to_message_template(
1451
1392
  ValueError: If 2-tuple does not have 2 elements.
1452
1393
  """
1453
1394
  if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):
1454
- message_: Union[
1455
- BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate
1456
- ] = message
1395
+ message_: BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate = (
1396
+ message
1397
+ )
1457
1398
  elif isinstance(message, BaseMessage):
1458
1399
  message_ = message
1459
1400
  elif isinstance(message, str):