langchain-core 0.4.0.dev0__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 (172) hide show
  1. langchain_core/__init__.py +1 -1
  2. langchain_core/_api/__init__.py +3 -4
  3. langchain_core/_api/beta_decorator.py +45 -70
  4. langchain_core/_api/deprecation.py +80 -80
  5. langchain_core/_api/path.py +22 -8
  6. langchain_core/_import_utils.py +10 -4
  7. langchain_core/agents.py +25 -21
  8. langchain_core/caches.py +53 -63
  9. langchain_core/callbacks/__init__.py +1 -8
  10. langchain_core/callbacks/base.py +341 -348
  11. langchain_core/callbacks/file.py +55 -44
  12. langchain_core/callbacks/manager.py +546 -683
  13. langchain_core/callbacks/stdout.py +29 -30
  14. langchain_core/callbacks/streaming_stdout.py +35 -36
  15. langchain_core/callbacks/usage.py +65 -70
  16. langchain_core/chat_history.py +48 -55
  17. langchain_core/document_loaders/base.py +46 -21
  18. langchain_core/document_loaders/langsmith.py +39 -36
  19. langchain_core/documents/__init__.py +0 -1
  20. langchain_core/documents/base.py +96 -74
  21. langchain_core/documents/compressor.py +12 -9
  22. langchain_core/documents/transformers.py +29 -28
  23. langchain_core/embeddings/fake.py +56 -57
  24. langchain_core/env.py +2 -3
  25. langchain_core/example_selectors/base.py +12 -0
  26. langchain_core/example_selectors/length_based.py +1 -1
  27. langchain_core/example_selectors/semantic_similarity.py +21 -25
  28. langchain_core/exceptions.py +15 -9
  29. langchain_core/globals.py +4 -163
  30. langchain_core/indexing/api.py +132 -125
  31. langchain_core/indexing/base.py +64 -67
  32. langchain_core/indexing/in_memory.py +26 -6
  33. langchain_core/language_models/__init__.py +15 -27
  34. langchain_core/language_models/_utils.py +267 -117
  35. langchain_core/language_models/base.py +92 -177
  36. langchain_core/language_models/chat_models.py +547 -407
  37. langchain_core/language_models/fake.py +11 -11
  38. langchain_core/language_models/fake_chat_models.py +72 -118
  39. langchain_core/language_models/llms.py +168 -242
  40. langchain_core/load/dump.py +8 -11
  41. langchain_core/load/load.py +32 -28
  42. langchain_core/load/mapping.py +2 -4
  43. langchain_core/load/serializable.py +50 -56
  44. langchain_core/messages/__init__.py +36 -51
  45. langchain_core/messages/ai.py +377 -150
  46. langchain_core/messages/base.py +239 -47
  47. langchain_core/messages/block_translators/__init__.py +111 -0
  48. langchain_core/messages/block_translators/anthropic.py +470 -0
  49. langchain_core/messages/block_translators/bedrock.py +94 -0
  50. langchain_core/messages/block_translators/bedrock_converse.py +297 -0
  51. langchain_core/messages/block_translators/google_genai.py +530 -0
  52. langchain_core/messages/block_translators/google_vertexai.py +21 -0
  53. langchain_core/messages/block_translators/groq.py +143 -0
  54. langchain_core/messages/block_translators/langchain_v0.py +301 -0
  55. langchain_core/messages/block_translators/openai.py +1010 -0
  56. langchain_core/messages/chat.py +2 -3
  57. langchain_core/messages/content.py +1423 -0
  58. langchain_core/messages/function.py +7 -7
  59. langchain_core/messages/human.py +44 -38
  60. langchain_core/messages/modifier.py +3 -2
  61. langchain_core/messages/system.py +40 -27
  62. langchain_core/messages/tool.py +160 -58
  63. langchain_core/messages/utils.py +527 -638
  64. langchain_core/output_parsers/__init__.py +1 -14
  65. langchain_core/output_parsers/base.py +68 -104
  66. langchain_core/output_parsers/json.py +13 -17
  67. langchain_core/output_parsers/list.py +11 -33
  68. langchain_core/output_parsers/openai_functions.py +56 -74
  69. langchain_core/output_parsers/openai_tools.py +68 -109
  70. langchain_core/output_parsers/pydantic.py +15 -13
  71. langchain_core/output_parsers/string.py +6 -2
  72. langchain_core/output_parsers/transform.py +17 -60
  73. langchain_core/output_parsers/xml.py +34 -44
  74. langchain_core/outputs/__init__.py +1 -1
  75. langchain_core/outputs/chat_generation.py +26 -11
  76. langchain_core/outputs/chat_result.py +1 -3
  77. langchain_core/outputs/generation.py +17 -6
  78. langchain_core/outputs/llm_result.py +15 -8
  79. langchain_core/prompt_values.py +29 -123
  80. langchain_core/prompts/__init__.py +3 -27
  81. langchain_core/prompts/base.py +48 -63
  82. langchain_core/prompts/chat.py +259 -288
  83. langchain_core/prompts/dict.py +19 -11
  84. langchain_core/prompts/few_shot.py +84 -90
  85. langchain_core/prompts/few_shot_with_templates.py +14 -12
  86. langchain_core/prompts/image.py +19 -14
  87. langchain_core/prompts/loading.py +6 -8
  88. langchain_core/prompts/message.py +7 -8
  89. langchain_core/prompts/prompt.py +42 -43
  90. langchain_core/prompts/string.py +37 -16
  91. langchain_core/prompts/structured.py +43 -46
  92. langchain_core/rate_limiters.py +51 -60
  93. langchain_core/retrievers.py +52 -192
  94. langchain_core/runnables/base.py +1727 -1683
  95. langchain_core/runnables/branch.py +52 -73
  96. langchain_core/runnables/config.py +89 -103
  97. langchain_core/runnables/configurable.py +128 -130
  98. langchain_core/runnables/fallbacks.py +93 -82
  99. langchain_core/runnables/graph.py +127 -127
  100. langchain_core/runnables/graph_ascii.py +63 -41
  101. langchain_core/runnables/graph_mermaid.py +87 -70
  102. langchain_core/runnables/graph_png.py +31 -36
  103. langchain_core/runnables/history.py +145 -161
  104. langchain_core/runnables/passthrough.py +141 -144
  105. langchain_core/runnables/retry.py +84 -68
  106. langchain_core/runnables/router.py +33 -37
  107. langchain_core/runnables/schema.py +79 -72
  108. langchain_core/runnables/utils.py +95 -139
  109. langchain_core/stores.py +85 -131
  110. langchain_core/structured_query.py +11 -15
  111. langchain_core/sys_info.py +31 -32
  112. langchain_core/tools/__init__.py +1 -14
  113. langchain_core/tools/base.py +221 -247
  114. langchain_core/tools/convert.py +144 -161
  115. langchain_core/tools/render.py +10 -10
  116. langchain_core/tools/retriever.py +12 -19
  117. langchain_core/tools/simple.py +52 -29
  118. langchain_core/tools/structured.py +56 -60
  119. langchain_core/tracers/__init__.py +1 -9
  120. langchain_core/tracers/_streaming.py +6 -7
  121. langchain_core/tracers/base.py +103 -112
  122. langchain_core/tracers/context.py +29 -48
  123. langchain_core/tracers/core.py +142 -105
  124. langchain_core/tracers/evaluation.py +30 -34
  125. langchain_core/tracers/event_stream.py +162 -117
  126. langchain_core/tracers/langchain.py +34 -36
  127. langchain_core/tracers/log_stream.py +87 -49
  128. langchain_core/tracers/memory_stream.py +3 -3
  129. langchain_core/tracers/root_listeners.py +18 -34
  130. langchain_core/tracers/run_collector.py +8 -20
  131. langchain_core/tracers/schemas.py +0 -125
  132. langchain_core/tracers/stdout.py +3 -3
  133. langchain_core/utils/__init__.py +1 -4
  134. langchain_core/utils/_merge.py +47 -9
  135. langchain_core/utils/aiter.py +70 -66
  136. langchain_core/utils/env.py +12 -9
  137. langchain_core/utils/function_calling.py +139 -206
  138. langchain_core/utils/html.py +7 -8
  139. langchain_core/utils/input.py +6 -6
  140. langchain_core/utils/interactive_env.py +6 -2
  141. langchain_core/utils/iter.py +48 -45
  142. langchain_core/utils/json.py +14 -4
  143. langchain_core/utils/json_schema.py +159 -43
  144. langchain_core/utils/mustache.py +32 -25
  145. langchain_core/utils/pydantic.py +67 -40
  146. langchain_core/utils/strings.py +5 -5
  147. langchain_core/utils/usage.py +1 -1
  148. langchain_core/utils/utils.py +104 -62
  149. langchain_core/vectorstores/base.py +131 -179
  150. langchain_core/vectorstores/in_memory.py +113 -182
  151. langchain_core/vectorstores/utils.py +23 -17
  152. langchain_core/version.py +1 -1
  153. langchain_core-1.0.0.dist-info/METADATA +68 -0
  154. langchain_core-1.0.0.dist-info/RECORD +172 -0
  155. {langchain_core-0.4.0.dev0.dist-info → langchain_core-1.0.0.dist-info}/WHEEL +1 -1
  156. langchain_core/beta/__init__.py +0 -1
  157. langchain_core/beta/runnables/__init__.py +0 -1
  158. langchain_core/beta/runnables/context.py +0 -448
  159. langchain_core/memory.py +0 -116
  160. langchain_core/messages/content_blocks.py +0 -1435
  161. langchain_core/prompts/pipeline.py +0 -133
  162. langchain_core/pydantic_v1/__init__.py +0 -30
  163. langchain_core/pydantic_v1/dataclasses.py +0 -23
  164. langchain_core/pydantic_v1/main.py +0 -23
  165. langchain_core/tracers/langchain_v1.py +0 -23
  166. langchain_core/utils/loading.py +0 -31
  167. langchain_core/v1/__init__.py +0 -1
  168. langchain_core/v1/chat_models.py +0 -1047
  169. langchain_core/v1/messages.py +0 -755
  170. langchain_core-0.4.0.dev0.dist-info/METADATA +0 -108
  171. langchain_core-0.4.0.dev0.dist-info/RECORD +0 -177
  172. langchain_core-0.4.0.dev0.dist-info/entry_points.txt +0 -4
@@ -2,7 +2,7 @@
2
2
 
3
3
  import warnings
4
4
  from functools import cached_property
5
- from typing import Any, Literal, Optional
5
+ from typing import Any, Literal
6
6
 
7
7
  from typing_extensions import override
8
8
 
@@ -31,18 +31,25 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
31
31
  return _get_input_variables(self.template, self.template_format)
32
32
 
33
33
  def format(self, **kwargs: Any) -> dict[str, Any]:
34
- """Format the prompt with the inputs."""
34
+ """Format the prompt with the inputs.
35
+
36
+ Returns:
37
+ A formatted dict.
38
+ """
35
39
  return _insert_input_variables(self.template, kwargs, self.template_format)
36
40
 
37
41
  async def aformat(self, **kwargs: Any) -> dict[str, Any]:
38
- """Format the prompt with the inputs."""
42
+ """Format the prompt with the inputs.
43
+
44
+ Returns:
45
+ A formatted dict.
46
+ """
39
47
  return self.format(**kwargs)
40
48
 
41
49
  @override
42
50
  def invoke(
43
- self, input: dict, config: Optional[RunnableConfig] = None, **kwargs: Any
51
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
44
52
  ) -> dict:
45
- """Invoke the prompt."""
46
53
  return self._call_with_config(
47
54
  lambda x: self.format(**x),
48
55
  input,
@@ -62,22 +69,23 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
62
69
 
63
70
  @classmethod
64
71
  def is_lc_serializable(cls) -> bool:
65
- """Return whether or not the class is serializable.
66
-
67
- Returns: True.
68
- """
72
+ """Return True as this class is serializable."""
69
73
  return True
70
74
 
71
75
  @classmethod
72
76
  def get_lc_namespace(cls) -> list[str]:
73
- """Serialization namespace."""
77
+ """Get the namespace of the LangChain object.
78
+
79
+ Returns:
80
+ `["langchain_core", "prompts", "dict"]`
81
+ """
74
82
  return ["langchain_core", "prompts", "dict"]
75
83
 
76
84
  def pretty_repr(self, *, html: bool = False) -> str:
77
85
  """Human-readable representation.
78
86
 
79
87
  Args:
80
- html: Whether to format as HTML. Defaults to False.
88
+ html: Whether to format as HTML.
81
89
 
82
90
  Returns:
83
91
  Human-readable representation.
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, Any, Literal, Optional, Union
5
+ from typing import TYPE_CHECKING, Any, Literal
6
6
 
7
7
  from pydantic import (
8
8
  BaseModel,
@@ -33,11 +33,11 @@ if TYPE_CHECKING:
33
33
  class _FewShotPromptTemplateMixin(BaseModel):
34
34
  """Prompt template that contains few shot examples."""
35
35
 
36
- examples: Optional[list[dict]] = None
36
+ examples: list[dict] | None = None
37
37
  """Examples to format into the prompt.
38
38
  Either this or example_selector should be provided."""
39
39
 
40
- example_selector: Optional[BaseExampleSelector] = None
40
+ example_selector: BaseExampleSelector | None = None
41
41
  """ExampleSelector to choose the examples to format into the prompt.
42
42
  Either this or examples should be provided."""
43
43
 
@@ -117,7 +117,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
117
117
 
118
118
  @classmethod
119
119
  def is_lc_serializable(cls) -> bool:
120
- """Return whether or not the class is serializable."""
120
+ """Return False as this class is not serializable."""
121
121
  return False
122
122
 
123
123
  validate_template: bool = False
@@ -153,7 +153,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
153
153
  self.template_format,
154
154
  self.input_variables + list(self.partial_variables),
155
155
  )
156
- elif self.template_format or None:
156
+ elif self.template_format:
157
157
  self.input_variables = [
158
158
  var
159
159
  for var in get_template_variables(
@@ -229,7 +229,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
229
229
  """Return the prompt type key."""
230
230
  return "few_shot"
231
231
 
232
- def save(self, file_path: Union[Path, str]) -> None:
232
+ def save(self, file_path: Path | str) -> None:
233
233
  """Save the prompt template to a file.
234
234
 
235
235
  Args:
@@ -268,108 +268,102 @@ class FewShotChatMessagePromptTemplate(
268
268
  Prompt template with a fixed list of examples (matching the sample
269
269
  conversation above):
270
270
 
271
- .. code-block:: python
271
+ ```python
272
+ from langchain_core.prompts import (
273
+ FewShotChatMessagePromptTemplate,
274
+ ChatPromptTemplate,
275
+ )
272
276
 
273
- from langchain_core.prompts import (
274
- FewShotChatMessagePromptTemplate,
275
- ChatPromptTemplate
276
- )
277
+ examples = [
278
+ {"input": "2+2", "output": "4"},
279
+ {"input": "2+3", "output": "5"},
280
+ ]
277
281
 
278
- examples = [
279
- {"input": "2+2", "output": "4"},
280
- {"input": "2+3", "output": "5"},
282
+ example_prompt = ChatPromptTemplate.from_messages(
283
+ [
284
+ ("human", "What is {input}?"),
285
+ ("ai", "{output}"),
281
286
  ]
282
-
283
- example_prompt = ChatPromptTemplate.from_messages(
284
- [('human', 'What is {input}?'), ('ai', '{output}')]
285
- )
286
-
287
- few_shot_prompt = FewShotChatMessagePromptTemplate(
288
- examples=examples,
289
- # This is a prompt template used to format each individual example.
290
- example_prompt=example_prompt,
291
- )
292
-
293
- final_prompt = ChatPromptTemplate.from_messages(
294
- [
295
- ('system', 'You are a helpful AI Assistant'),
296
- few_shot_prompt,
297
- ('human', '{input}'),
298
- ]
299
- )
300
- final_prompt.format(input="What is 4+4?")
301
-
302
- Prompt template with dynamically selected examples:
303
-
304
- .. code-block:: python
305
-
306
- from langchain_core.prompts import SemanticSimilarityExampleSelector
307
- from langchain_core.embeddings import OpenAIEmbeddings
308
- from langchain_core.vectorstores import Chroma
309
-
310
- examples = [
311
- {"input": "2+2", "output": "4"},
312
- {"input": "2+3", "output": "5"},
313
- {"input": "2+4", "output": "6"},
314
- # ...
287
+ )
288
+
289
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
290
+ examples=examples,
291
+ # This is a prompt template used to format each individual example.
292
+ example_prompt=example_prompt,
293
+ )
294
+
295
+ final_prompt = ChatPromptTemplate.from_messages(
296
+ [
297
+ ("system", "You are a helpful AI Assistant"),
298
+ few_shot_prompt,
299
+ ("human", "{input}"),
315
300
  ]
301
+ )
302
+ final_prompt.format(input="What is 4+4?")
303
+ ```
316
304
 
317
- to_vectorize = [
318
- " ".join(example.values())
319
- for example in examples
320
- ]
321
- embeddings = OpenAIEmbeddings()
322
- vectorstore = Chroma.from_texts(
323
- to_vectorize, embeddings, metadatas=examples
324
- )
325
- example_selector = SemanticSimilarityExampleSelector(
326
- vectorstore=vectorstore
327
- )
305
+ Prompt template with dynamically selected examples:
328
306
 
329
- from langchain_core import SystemMessage
330
- from langchain_core.prompts import HumanMessagePromptTemplate
331
- from langchain_core.prompts.few_shot import FewShotChatMessagePromptTemplate
332
-
333
- few_shot_prompt = FewShotChatMessagePromptTemplate(
334
- # Which variable(s) will be passed to the example selector.
335
- input_variables=["input"],
336
- example_selector=example_selector,
337
- # Define how each example will be formatted.
338
- # In this case, each example will become 2 messages:
339
- # 1 human, and 1 AI
340
- example_prompt=(
341
- HumanMessagePromptTemplate.from_template("{input}")
342
- + AIMessagePromptTemplate.from_template("{output}")
343
- ),
344
- )
345
- # Define the overall prompt.
346
- final_prompt = (
347
- SystemMessagePromptTemplate.from_template(
348
- "You are a helpful AI Assistant"
349
- )
350
- + few_shot_prompt
351
- + HumanMessagePromptTemplate.from_template("{input}")
352
- )
353
- # Show the prompt
354
- print(final_prompt.format_messages(input="What's 3+3?")) # noqa: T201
307
+ ```python
308
+ from langchain_core.prompts import SemanticSimilarityExampleSelector
309
+ from langchain_core.embeddings import OpenAIEmbeddings
310
+ from langchain_core.vectorstores import Chroma
355
311
 
356
- # Use within an LLM
357
- from langchain_core.chat_models import ChatAnthropic
358
- chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
359
- chain.invoke({"input": "What's 3+3?"})
312
+ examples = [
313
+ {"input": "2+2", "output": "4"},
314
+ {"input": "2+3", "output": "5"},
315
+ {"input": "2+4", "output": "6"},
316
+ # ...
317
+ ]
360
318
 
319
+ to_vectorize = [" ".join(example.values()) for example in examples]
320
+ embeddings = OpenAIEmbeddings()
321
+ vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
322
+ example_selector = SemanticSimilarityExampleSelector(vectorstore=vectorstore)
323
+
324
+ from langchain_core import SystemMessage
325
+ from langchain_core.prompts import HumanMessagePromptTemplate
326
+ from langchain_core.prompts.few_shot import FewShotChatMessagePromptTemplate
327
+
328
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
329
+ # Which variable(s) will be passed to the example selector.
330
+ input_variables=["input"],
331
+ example_selector=example_selector,
332
+ # Define how each example will be formatted.
333
+ # In this case, each example will become 2 messages:
334
+ # 1 human, and 1 AI
335
+ example_prompt=(
336
+ HumanMessagePromptTemplate.from_template("{input}")
337
+ + AIMessagePromptTemplate.from_template("{output}")
338
+ ),
339
+ )
340
+ # Define the overall prompt.
341
+ final_prompt = (
342
+ SystemMessagePromptTemplate.from_template("You are a helpful AI Assistant")
343
+ + few_shot_prompt
344
+ + HumanMessagePromptTemplate.from_template("{input}")
345
+ )
346
+ # Show the prompt
347
+ print(final_prompt.format_messages(input="What's 3+3?")) # noqa: T201
348
+
349
+ # Use within an LLM
350
+ from langchain_core.chat_models import ChatAnthropic
351
+
352
+ chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
353
+ chain.invoke({"input": "What's 3+3?"})
354
+ ```
361
355
  """
362
356
 
363
357
  input_variables: list[str] = Field(default_factory=list)
364
358
  """A list of the names of the variables the prompt template will use
365
359
  to pass to the example_selector, if provided."""
366
360
 
367
- example_prompt: Union[BaseMessagePromptTemplate, BaseChatPromptTemplate]
361
+ example_prompt: BaseMessagePromptTemplate | BaseChatPromptTemplate
368
362
  """The class to format each example."""
369
363
 
370
364
  @classmethod
371
365
  def is_lc_serializable(cls) -> bool:
372
- """Return whether or not the class is serializable."""
366
+ """Return False as this class is not serializable."""
373
367
  return False
374
368
 
375
369
  model_config = ConfigDict(
@@ -1,7 +1,7 @@
1
1
  """Prompt template that contains few shot examples."""
2
2
 
3
3
  from pathlib import Path
4
- from typing import Any, Optional, Union
4
+ from typing import Any
5
5
 
6
6
  from pydantic import ConfigDict, model_validator
7
7
  from typing_extensions import Self
@@ -17,7 +17,7 @@ from langchain_core.prompts.string import (
17
17
  class FewShotPromptWithTemplates(StringPromptTemplate):
18
18
  """Prompt template that contains few shot examples."""
19
19
 
20
- examples: Optional[list[dict]] = None
20
+ examples: list[dict] | None = None
21
21
  """Examples to format into the prompt.
22
22
  Either this or example_selector should be provided."""
23
23
 
@@ -34,7 +34,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
34
34
  example_separator: str = "\n\n"
35
35
  """String separator used to join the prefix, the examples, and suffix."""
36
36
 
37
- prefix: Optional[StringPromptTemplate] = None
37
+ prefix: StringPromptTemplate | None = None
38
38
  """A PromptTemplate to put before the examples."""
39
39
 
40
40
  template_format: PromptTemplateFormat = "f-string"
@@ -46,7 +46,11 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
46
46
 
47
47
  @classmethod
48
48
  def get_lc_namespace(cls) -> list[str]:
49
- """Get the namespace of the langchain object."""
49
+ """Get the namespace of the LangChain object.
50
+
51
+ Returns:
52
+ `["langchain", "prompts", "few_shot_with_templates"]`
53
+ """
50
54
  return ["langchain", "prompts", "few_shot_with_templates"]
51
55
 
52
56
  @model_validator(mode="before")
@@ -112,17 +116,15 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
112
116
  """Format the prompt with the inputs.
113
117
 
114
118
  Args:
115
- kwargs: Any arguments to be passed to the prompt template.
119
+ **kwargs: Any arguments to be passed to the prompt template.
116
120
 
117
121
  Returns:
118
122
  A formatted string.
119
123
 
120
124
  Example:
121
-
122
- .. code-block:: python
123
-
124
- prompt.format(variable1="foo")
125
-
125
+ ```python
126
+ prompt.format(variable1="foo")
127
+ ```
126
128
  """
127
129
  kwargs = self._merge_partial_and_user_variables(**kwargs)
128
130
  # Get the examples to use.
@@ -161,7 +163,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
161
163
  """Async format the prompt with the inputs.
162
164
 
163
165
  Args:
164
- kwargs: Any arguments to be passed to the prompt template.
166
+ **kwargs: Any arguments to be passed to the prompt template.
165
167
 
166
168
  Returns:
167
169
  A formatted string.
@@ -206,7 +208,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
206
208
  """Return the prompt type key."""
207
209
  return "few_shot_with_templates"
208
210
 
209
- def save(self, file_path: Union[Path, str]) -> None:
211
+ def save(self, file_path: Path | str) -> None:
210
212
  """Save the prompt to a file.
211
213
 
212
214
  Args:
@@ -23,7 +23,12 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
23
23
  Options are: 'f-string', 'mustache', 'jinja2'."""
24
24
 
25
25
  def __init__(self, **kwargs: Any) -> None:
26
- """Create an image prompt template."""
26
+ """Create an image prompt template.
27
+
28
+ Raises:
29
+ ValueError: If the input variables contain `'url'`, `'path'`, or
30
+ `'detail'`.
31
+ """
27
32
  if "input_variables" not in kwargs:
28
33
  kwargs["input_variables"] = []
29
34
 
@@ -44,14 +49,18 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
44
49
 
45
50
  @classmethod
46
51
  def get_lc_namespace(cls) -> list[str]:
47
- """Get the namespace of the langchain object."""
52
+ """Get the namespace of the LangChain object.
53
+
54
+ Returns:
55
+ `["langchain", "prompts", "image"]`
56
+ """
48
57
  return ["langchain", "prompts", "image"]
49
58
 
50
59
  def format_prompt(self, **kwargs: Any) -> PromptValue:
51
60
  """Format the prompt with the inputs.
52
61
 
53
62
  Args:
54
- kwargs: Any arguments to be passed to the prompt template.
63
+ **kwargs: Any arguments to be passed to the prompt template.
55
64
 
56
65
  Returns:
57
66
  A formatted string.
@@ -62,7 +71,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
62
71
  """Async format the prompt with the inputs.
63
72
 
64
73
  Args:
65
- kwargs: Any arguments to be passed to the prompt template.
74
+ **kwargs: Any arguments to be passed to the prompt template.
66
75
 
67
76
  Returns:
68
77
  A formatted string.
@@ -76,7 +85,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
76
85
  """Format the prompt with the inputs.
77
86
 
78
87
  Args:
79
- kwargs: Any arguments to be passed to the prompt template.
88
+ **kwargs: Any arguments to be passed to the prompt template.
80
89
 
81
90
  Returns:
82
91
  A formatted string.
@@ -84,13 +93,12 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
84
93
  Raises:
85
94
  ValueError: If the url is not provided.
86
95
  ValueError: If the url is not a string.
96
+ ValueError: If `'path'` is provided in the template or kwargs.
87
97
 
88
98
  Example:
89
-
90
- .. code-block:: python
91
-
92
- prompt.format(variable1="foo")
93
-
99
+ ```python
100
+ prompt.format(variable1="foo")
101
+ ```
94
102
  """
95
103
  formatted = {}
96
104
  for k, v in self.template.items():
@@ -124,13 +132,10 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
124
132
  """Async format the prompt with the inputs.
125
133
 
126
134
  Args:
127
- kwargs: Any arguments to be passed to the prompt template.
135
+ **kwargs: Any arguments to be passed to the prompt template.
128
136
 
129
137
  Returns:
130
138
  A formatted string.
131
-
132
- Raises:
133
- ValueError: If the path or url is not a string.
134
139
  """
135
140
  return await run_in_executor(None, self.format, **kwargs)
136
141
 
@@ -2,8 +2,8 @@
2
2
 
3
3
  import json
4
4
  import logging
5
+ from collections.abc import Callable
5
6
  from pathlib import Path
6
- from typing import Callable, Optional, Union
7
7
 
8
8
  import yaml
9
9
 
@@ -53,7 +53,7 @@ def _load_template(var_name: str, config: dict) -> dict:
53
53
  template_path = Path(config.pop(f"{var_name}_path"))
54
54
  # Load the template.
55
55
  if template_path.suffix == ".txt":
56
- template = template_path.read_text()
56
+ template = template_path.read_text(encoding="utf-8")
57
57
  else:
58
58
  raise ValueError
59
59
  # Set the template variable to the extracted variable.
@@ -67,7 +67,7 @@ def _load_examples(config: dict) -> dict:
67
67
  pass
68
68
  elif isinstance(config["examples"], str):
69
69
  path = Path(config["examples"])
70
- with path.open() as f:
70
+ with path.open(encoding="utf-8") as f:
71
71
  if path.suffix == ".json":
72
72
  examples = json.load(f)
73
73
  elif path.suffix in {".yaml", ".yml"}:
@@ -134,14 +134,12 @@ def _load_prompt(config: dict) -> PromptTemplate:
134
134
  return PromptTemplate(**config)
135
135
 
136
136
 
137
- def load_prompt(
138
- path: Union[str, Path], encoding: Optional[str] = None
139
- ) -> BasePromptTemplate:
137
+ def load_prompt(path: str | Path, encoding: str | None = None) -> BasePromptTemplate:
140
138
  """Unified method for loading a prompt from LangChainHub or local fs.
141
139
 
142
140
  Args:
143
141
  path: Path to the prompt file.
144
- encoding: Encoding of the file. Defaults to None.
142
+ encoding: Encoding of the file.
145
143
 
146
144
  Returns:
147
145
  A PromptTemplate object.
@@ -160,7 +158,7 @@ def load_prompt(
160
158
 
161
159
 
162
160
  def _load_prompt_from_file(
163
- file: Union[str, Path], encoding: Optional[str] = None
161
+ file: str | Path, encoding: str | None = None
164
162
  ) -> BasePromptTemplate:
165
163
  """Load prompt from file."""
166
164
  # Convert file to a Path object.
@@ -18,17 +18,15 @@ class BaseMessagePromptTemplate(Serializable, ABC):
18
18
 
19
19
  @classmethod
20
20
  def is_lc_serializable(cls) -> bool:
21
- """Return whether or not the class is serializable.
22
-
23
- Returns: True.
24
- """
21
+ """Return True as this class is serializable."""
25
22
  return True
26
23
 
27
24
  @classmethod
28
25
  def get_lc_namespace(cls) -> list[str]:
29
- """Get the namespace of the langchain object.
26
+ """Get the namespace of the LangChain object.
30
27
 
31
- Default namespace is ["langchain", "prompts", "chat"].
28
+ Returns:
29
+ `["langchain", "prompts", "chat"]`
32
30
  """
33
31
  return ["langchain", "prompts", "chat"]
34
32
 
@@ -70,7 +68,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
70
68
  """Human-readable representation.
71
69
 
72
70
  Args:
73
- html: Whether to format as HTML. Defaults to False.
71
+ html: Whether to format as HTML.
74
72
 
75
73
  Returns:
76
74
  Human-readable representation.
@@ -90,7 +88,8 @@ class BaseMessagePromptTemplate(Serializable, ABC):
90
88
  Returns:
91
89
  Combined prompt template.
92
90
  """
93
- from langchain_core.prompts.chat import ChatPromptTemplate
91
+ # Import locally to avoid circular import.
92
+ from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
94
93
 
95
94
  prompt = ChatPromptTemplate(messages=[self])
96
95
  return prompt + other