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
@@ -74,10 +74,10 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
74
74
 
75
75
  @classmethod
76
76
  def get_lc_namespace(cls) -> list[str]:
77
- """Get the namespace of the langchain object.
77
+ """Get the namespace of the LangChain object.
78
78
 
79
79
  Returns:
80
- ``["langchain_core", "prompts", "dict"]``
80
+ `["langchain_core", "prompts", "dict"]`
81
81
  """
82
82
  return ["langchain_core", "prompts", "dict"]
83
83
 
@@ -85,7 +85,7 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
85
85
  """Human-readable representation.
86
86
 
87
87
  Args:
88
- html: Whether to format as HTML. Defaults to False.
88
+ html: Whether to format as HTML.
89
89
 
90
90
  Returns:
91
91
  Human-readable representation.
@@ -268,97 +268,90 @@ 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
- [
285
- ("human", "What is {input}?"),
286
- ("ai", "{output}"),
287
- ]
288
- )
289
-
290
- few_shot_prompt = FewShotChatMessagePromptTemplate(
291
- examples=examples,
292
- # This is a prompt template used to format each individual example.
293
- example_prompt=example_prompt,
294
- )
295
-
296
- final_prompt = ChatPromptTemplate.from_messages(
297
- [
298
- ("system", "You are a helpful AI Assistant"),
299
- few_shot_prompt,
300
- ("human", "{input}"),
301
- ]
302
- )
303
- final_prompt.format(input="What is 4+4?")
304
-
305
- Prompt template with dynamically selected examples:
306
-
307
- .. code-block:: python
308
-
309
- from langchain_core.prompts import SemanticSimilarityExampleSelector
310
- from langchain_core.embeddings import OpenAIEmbeddings
311
- from langchain_core.vectorstores import Chroma
312
-
313
- examples = [
314
- {"input": "2+2", "output": "4"},
315
- {"input": "2+3", "output": "5"},
316
- {"input": "2+4", "output": "6"},
317
- # ...
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}"),
318
300
  ]
301
+ )
302
+ final_prompt.format(input="What is 4+4?")
303
+ ```
319
304
 
320
- to_vectorize = [" ".join(example.values()) for example in examples]
321
- embeddings = OpenAIEmbeddings()
322
- vectorstore = Chroma.from_texts(
323
- to_vectorize, embeddings, metadatas=examples
324
- )
325
- example_selector = SemanticSimilarityExampleSelector(
326
- vectorstore=vectorstore
327
- )
328
-
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
305
+ Prompt template with dynamically selected examples:
355
306
 
356
- # Use within an LLM
357
- from langchain_core.chat_models import ChatAnthropic
307
+ ```python
308
+ from langchain_core.prompts import SemanticSimilarityExampleSelector
309
+ from langchain_core.embeddings import OpenAIEmbeddings
310
+ from langchain_core.vectorstores import Chroma
358
311
 
359
- chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
360
- 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
+ ]
361
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
+ ```
362
355
  """
363
356
 
364
357
  input_variables: list[str] = Field(default_factory=list)
@@ -46,10 +46,10 @@ 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
50
 
51
51
  Returns:
52
- ``["langchain", "prompts", "few_shot_with_templates"]``
52
+ `["langchain", "prompts", "few_shot_with_templates"]`
53
53
  """
54
54
  return ["langchain", "prompts", "few_shot_with_templates"]
55
55
 
@@ -116,17 +116,15 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
116
116
  """Format the prompt with the inputs.
117
117
 
118
118
  Args:
119
- kwargs: Any arguments to be passed to the prompt template.
119
+ **kwargs: Any arguments to be passed to the prompt template.
120
120
 
121
121
  Returns:
122
122
  A formatted string.
123
123
 
124
124
  Example:
125
-
126
- .. code-block:: python
127
-
128
- prompt.format(variable1="foo")
129
-
125
+ ```python
126
+ prompt.format(variable1="foo")
127
+ ```
130
128
  """
131
129
  kwargs = self._merge_partial_and_user_variables(**kwargs)
132
130
  # Get the examples to use.
@@ -165,7 +163,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
165
163
  """Async format the prompt with the inputs.
166
164
 
167
165
  Args:
168
- kwargs: Any arguments to be passed to the prompt template.
166
+ **kwargs: Any arguments to be passed to the prompt template.
169
167
 
170
168
  Returns:
171
169
  A formatted string.
@@ -26,8 +26,8 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
26
26
  """Create an image prompt template.
27
27
 
28
28
  Raises:
29
- ValueError: If the input variables contain ``'url'``, ``'path'``, or
30
- ``'detail'``.
29
+ ValueError: If the input variables contain `'url'`, `'path'`, or
30
+ `'detail'`.
31
31
  """
32
32
  if "input_variables" not in kwargs:
33
33
  kwargs["input_variables"] = []
@@ -49,10 +49,10 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
49
49
 
50
50
  @classmethod
51
51
  def get_lc_namespace(cls) -> list[str]:
52
- """Get the namespace of the langchain object.
52
+ """Get the namespace of the LangChain object.
53
53
 
54
54
  Returns:
55
- ``["langchain", "prompts", "image"]``
55
+ `["langchain", "prompts", "image"]`
56
56
  """
57
57
  return ["langchain", "prompts", "image"]
58
58
 
@@ -60,7 +60,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
60
60
  """Format the prompt with the inputs.
61
61
 
62
62
  Args:
63
- kwargs: Any arguments to be passed to the prompt template.
63
+ **kwargs: Any arguments to be passed to the prompt template.
64
64
 
65
65
  Returns:
66
66
  A formatted string.
@@ -71,7 +71,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
71
71
  """Async format the prompt with the inputs.
72
72
 
73
73
  Args:
74
- kwargs: Any arguments to be passed to the prompt template.
74
+ **kwargs: Any arguments to be passed to the prompt template.
75
75
 
76
76
  Returns:
77
77
  A formatted string.
@@ -85,7 +85,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
85
85
  """Format the prompt with the inputs.
86
86
 
87
87
  Args:
88
- kwargs: Any arguments to be passed to the prompt template.
88
+ **kwargs: Any arguments to be passed to the prompt template.
89
89
 
90
90
  Returns:
91
91
  A formatted string.
@@ -93,14 +93,12 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
93
93
  Raises:
94
94
  ValueError: If the url is not provided.
95
95
  ValueError: If the url is not a string.
96
- ValueError: If ``'path'`` is provided in the template or kwargs.
96
+ ValueError: If `'path'` is provided in the template or kwargs.
97
97
 
98
98
  Example:
99
-
100
- .. code-block:: python
101
-
102
- prompt.format(variable1="foo")
103
-
99
+ ```python
100
+ prompt.format(variable1="foo")
101
+ ```
104
102
  """
105
103
  formatted = {}
106
104
  for k, v in self.template.items():
@@ -134,7 +132,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
134
132
  """Async format the prompt with the inputs.
135
133
 
136
134
  Args:
137
- kwargs: Any arguments to be passed to the prompt template.
135
+ **kwargs: Any arguments to be passed to the prompt template.
138
136
 
139
137
  Returns:
140
138
  A formatted string.
@@ -139,7 +139,7 @@ def load_prompt(path: str | Path, encoding: str | None = None) -> BasePromptTemp
139
139
 
140
140
  Args:
141
141
  path: Path to the prompt file.
142
- encoding: Encoding of the file. Defaults to None.
142
+ encoding: Encoding of the file.
143
143
 
144
144
  Returns:
145
145
  A PromptTemplate object.
@@ -23,10 +23,10 @@ class BaseMessagePromptTemplate(Serializable, ABC):
23
23
 
24
24
  @classmethod
25
25
  def get_lc_namespace(cls) -> list[str]:
26
- """Get the namespace of the langchain object.
26
+ """Get the namespace of the LangChain object.
27
27
 
28
28
  Returns:
29
- ``["langchain", "prompts", "chat"]``
29
+ `["langchain", "prompts", "chat"]`
30
30
  """
31
31
  return ["langchain", "prompts", "chat"]
32
32
 
@@ -68,7 +68,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
68
68
  """Human-readable representation.
69
69
 
70
70
  Args:
71
- html: Whether to format as HTML. Defaults to False.
71
+ html: Whether to format as HTML.
72
72
 
73
73
  Returns:
74
74
  Human-readable representation.
@@ -44,18 +44,16 @@ class PromptTemplate(StringPromptTemplate):
44
44
  from untrusted sources.
45
45
 
46
46
  Example:
47
+ ```python
48
+ from langchain_core.prompts import PromptTemplate
47
49
 
48
- .. code-block:: python
49
-
50
- from langchain_core.prompts import PromptTemplate
51
-
52
- # Instantiation using from_template (recommended)
53
- prompt = PromptTemplate.from_template("Say {foo}")
54
- prompt.format(foo="bar")
55
-
56
- # Instantiation using initializer
57
- prompt = PromptTemplate(template="Say {foo}")
50
+ # Instantiation using from_template (recommended)
51
+ prompt = PromptTemplate.from_template("Say {foo}")
52
+ prompt.format(foo="bar")
58
53
 
54
+ # Instantiation using initializer
55
+ prompt = PromptTemplate(template="Say {foo}")
56
+ ```
59
57
  """
60
58
 
61
59
  @property
@@ -68,10 +66,10 @@ class PromptTemplate(StringPromptTemplate):
68
66
  @classmethod
69
67
  @override
70
68
  def get_lc_namespace(cls) -> list[str]:
71
- """Get the namespace of the langchain object.
69
+ """Get the namespace of the LangChain object.
72
70
 
73
71
  Returns:
74
- ``["langchain", "prompts", "prompt"]``
72
+ `["langchain", "prompts", "prompt"]`
75
73
  """
76
74
  return ["langchain", "prompts", "prompt"]
77
75
 
@@ -144,10 +142,10 @@ class PromptTemplate(StringPromptTemplate):
144
142
  Raises:
145
143
  ValueError: If the template formats are not f-string or if there are
146
144
  conflicting partial variables.
147
- NotImplementedError: If the other object is not a ``PromptTemplate`` or str.
145
+ NotImplementedError: If the other object is not a `PromptTemplate` or str.
148
146
 
149
147
  Returns:
150
- A new ``PromptTemplate`` that is the combination of the two.
148
+ A new `PromptTemplate` that is the combination of the two.
151
149
  """
152
150
  # Allow for easy combining
153
151
  if isinstance(other, PromptTemplate):
@@ -191,7 +189,7 @@ class PromptTemplate(StringPromptTemplate):
191
189
  """Format the prompt with the inputs.
192
190
 
193
191
  Args:
194
- kwargs: Any arguments to be passed to the prompt template.
192
+ **kwargs: Any arguments to be passed to the prompt template.
195
193
 
196
194
  Returns:
197
195
  A formatted string.
@@ -222,7 +220,7 @@ class PromptTemplate(StringPromptTemplate):
222
220
  example_separator: The separator to use in between examples. Defaults
223
221
  to two new line characters.
224
222
  prefix: String that should go before any examples. Generally includes
225
- examples. Default to an empty string.
223
+ examples.
226
224
 
227
225
  Returns:
228
226
  The final prompt generated.
@@ -277,14 +275,13 @@ class PromptTemplate(StringPromptTemplate):
277
275
  Args:
278
276
  template: The template to load.
279
277
  template_format: The format of the template. Use `jinja2` for jinja2,
280
- `mustache` for mustache, and `f-string` for f-strings.
281
- Defaults to `f-string`.
278
+ `mustache` for mustache, and `f-string` for f-strings.
282
279
  partial_variables: A dictionary of variables that can be used to partially
283
- fill in the template. For example, if the template is
284
- `"{variable1} {variable2}"`, and `partial_variables` is
285
- `{"variable1": "foo"}`, then the final prompt will be
286
- `"foo {variable2}"`. Defaults to None.
287
- kwargs: Any other arguments to pass to the prompt template.
280
+ fill in the template. For example, if the template is
281
+ `"{variable1} {variable2}"`, and `partial_variables` is
282
+ `{"variable1": "foo"}`, then the final prompt will be
283
+ `"foo {variable2}"`.
284
+ **kwargs: Any other arguments to pass to the prompt template.
288
285
 
289
286
  Returns:
290
287
  The prompt template loaded from the template.
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import warnings
6
6
  from abc import ABC
7
- from collections.abc import Callable
7
+ from collections.abc import Callable, Sequence
8
8
  from string import Formatter
9
9
  from typing import Any, Literal
10
10
 
@@ -149,9 +149,7 @@ def mustache_template_vars(
149
149
  Defs = dict[str, "Defs"]
150
150
 
151
151
 
152
- def mustache_schema(
153
- template: str,
154
- ) -> type[BaseModel]:
152
+ def mustache_schema(template: str) -> type[BaseModel]:
155
153
  """Get the variables from a mustache template.
156
154
 
157
155
  Args:
@@ -175,6 +173,11 @@ def mustache_schema(
175
173
  fields[prefix] = False
176
174
  elif type_ in {"variable", "no escape"}:
177
175
  fields[prefix + tuple(key.split("."))] = True
176
+
177
+ for fkey, fval in fields.items():
178
+ fields[fkey] = fval and not any(
179
+ is_subsequence(fkey, k) for k in fields if k != fkey
180
+ )
178
181
  defs: Defs = {} # None means leaf node
179
182
  while fields:
180
183
  field, is_leaf = fields.popitem()
@@ -273,10 +276,10 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
273
276
 
274
277
  @classmethod
275
278
  def get_lc_namespace(cls) -> list[str]:
276
- """Get the namespace of the langchain object.
279
+ """Get the namespace of the LangChain object.
277
280
 
278
281
  Returns:
279
- ``["langchain", "prompts", "base"]``
282
+ `["langchain", "prompts", "base"]`
280
283
  """
281
284
  return ["langchain", "prompts", "base"]
282
285
 
@@ -284,7 +287,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
284
287
  """Format the prompt with the inputs.
285
288
 
286
289
  Args:
287
- kwargs: Any arguments to be passed to the prompt template.
290
+ **kwargs: Any arguments to be passed to the prompt template.
288
291
 
289
292
  Returns:
290
293
  A formatted string.
@@ -295,7 +298,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
295
298
  """Async format the prompt with the inputs.
296
299
 
297
300
  Args:
298
- kwargs: Any arguments to be passed to the prompt template.
301
+ **kwargs: Any arguments to be passed to the prompt template.
299
302
 
300
303
  Returns:
301
304
  A formatted string.
@@ -327,3 +330,12 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
327
330
  def pretty_print(self) -> None:
328
331
  """Print a pretty representation of the prompt."""
329
332
  print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
333
+
334
+
335
+ def is_subsequence(child: Sequence, parent: Sequence) -> bool:
336
+ """Return True if child is subsequence of parent."""
337
+ if len(child) == 0 or len(parent) == 0:
338
+ return False
339
+ if len(parent) < len(child):
340
+ return False
341
+ return all(child[i] == parent[i] for i in range(len(child)))
@@ -63,13 +63,13 @@ class StructuredPrompt(ChatPromptTemplate):
63
63
 
64
64
  @classmethod
65
65
  def get_lc_namespace(cls) -> list[str]:
66
- """Get the namespace of the langchain object.
66
+ """Get the namespace of the LangChain object.
67
67
 
68
- For example, if the class is ``langchain.llms.openai.OpenAI``, then the
69
- namespace is ``["langchain", "llms", "openai"]``
68
+ For example, if the class is `langchain.llms.openai.OpenAI`, then the
69
+ namespace is `["langchain", "llms", "openai"]`
70
70
 
71
71
  Returns:
72
- The namespace of the langchain object.
72
+ The namespace of the LangChain object.
73
73
  """
74
74
  return cls.__module__.split(".")
75
75
 
@@ -85,35 +85,34 @@ class StructuredPrompt(ChatPromptTemplate):
85
85
  Examples:
86
86
  Instantiation from a list of message templates:
87
87
 
88
- .. code-block:: python
88
+ ```python
89
+ from langchain_core.prompts import StructuredPrompt
89
90
 
90
- from langchain_core.prompts import StructuredPrompt
91
91
 
92
+ class OutputSchema(BaseModel):
93
+ name: str
94
+ value: int
92
95
 
93
- class OutputSchema(BaseModel):
94
- name: str
95
- value: int
96
-
97
-
98
- template = StructuredPrompt(
99
- [
100
- ("human", "Hello, how are you?"),
101
- ("ai", "I'm doing well, thanks!"),
102
- ("human", "That's good to hear."),
103
- ],
104
- OutputSchema,
105
- )
106
96
 
97
+ template = StructuredPrompt(
98
+ [
99
+ ("human", "Hello, how are you?"),
100
+ ("ai", "I'm doing well, thanks!"),
101
+ ("human", "That's good to hear."),
102
+ ],
103
+ OutputSchema,
104
+ )
105
+ ```
107
106
  Args:
108
107
  messages: sequence of message representations.
109
- A message can be represented using the following formats:
110
- (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
111
- (message type, template); e.g., ("human", "{user_input}"),
112
- (4) 2-tuple of (message class, template), (5) a string which is
113
- shorthand for ("human", template); e.g., "{user_input}"
108
+ A message can be represented using the following formats:
109
+ (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
110
+ (message type, template); e.g., ("human", "{user_input}"),
111
+ (4) 2-tuple of (message class, template), (5) a string which is
112
+ shorthand for ("human", template); e.g., "{user_input}"
114
113
  schema: a dictionary representation of function call, or a Pydantic model.
115
- kwargs: Any additional kwargs to pass through to
116
- ``ChatModel.with_structured_output(schema, **kwargs)``.
114
+ **kwargs: Any additional kwargs to pass through to
115
+ `ChatModel.with_structured_output(schema, **kwargs)`.
117
116
 
118
117
  Returns:
119
118
  a structured prompt template
@@ -145,7 +144,7 @@ class StructuredPrompt(ChatPromptTemplate):
145
144
 
146
145
  Args:
147
146
  others: The language model to pipe the structured prompt to.
148
- name: The name of the pipeline. Defaults to None.
147
+ name: The name of the pipeline.
149
148
 
150
149
  Returns:
151
150
  A RunnableSequence object.