langchain-core 1.0.0a8__py3-none-any.whl → 1.0.0rc1__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.
- langchain_core/__init__.py +1 -1
- langchain_core/_api/__init__.py +0 -1
- langchain_core/_api/beta_decorator.py +17 -20
- langchain_core/_api/deprecation.py +30 -35
- langchain_core/_import_utils.py +1 -1
- langchain_core/agents.py +7 -6
- langchain_core/caches.py +4 -10
- langchain_core/callbacks/__init__.py +1 -8
- langchain_core/callbacks/base.py +232 -243
- langchain_core/callbacks/file.py +33 -33
- langchain_core/callbacks/manager.py +353 -416
- langchain_core/callbacks/stdout.py +21 -22
- langchain_core/callbacks/streaming_stdout.py +32 -32
- langchain_core/callbacks/usage.py +54 -51
- langchain_core/chat_history.py +42 -57
- langchain_core/document_loaders/langsmith.py +21 -21
- langchain_core/documents/__init__.py +0 -1
- langchain_core/documents/base.py +37 -40
- langchain_core/documents/transformers.py +28 -29
- langchain_core/embeddings/fake.py +46 -52
- langchain_core/exceptions.py +5 -5
- langchain_core/indexing/api.py +11 -11
- langchain_core/indexing/base.py +24 -24
- langchain_core/language_models/__init__.py +0 -2
- langchain_core/language_models/_utils.py +51 -53
- langchain_core/language_models/base.py +23 -24
- langchain_core/language_models/chat_models.py +121 -144
- langchain_core/language_models/fake_chat_models.py +5 -5
- langchain_core/language_models/llms.py +10 -12
- langchain_core/load/dump.py +1 -1
- langchain_core/load/load.py +16 -16
- langchain_core/load/serializable.py +35 -34
- langchain_core/messages/__init__.py +1 -16
- langchain_core/messages/ai.py +105 -104
- langchain_core/messages/base.py +26 -26
- langchain_core/messages/block_translators/__init__.py +17 -17
- langchain_core/messages/block_translators/anthropic.py +2 -2
- langchain_core/messages/block_translators/bedrock_converse.py +2 -2
- langchain_core/messages/block_translators/google_genai.py +2 -2
- langchain_core/messages/block_translators/groq.py +117 -21
- langchain_core/messages/block_translators/langchain_v0.py +2 -2
- langchain_core/messages/block_translators/openai.py +4 -4
- langchain_core/messages/chat.py +1 -1
- langchain_core/messages/content.py +189 -193
- langchain_core/messages/function.py +5 -5
- langchain_core/messages/human.py +15 -17
- langchain_core/messages/modifier.py +1 -1
- langchain_core/messages/system.py +12 -14
- langchain_core/messages/tool.py +45 -49
- langchain_core/messages/utils.py +384 -396
- langchain_core/output_parsers/__init__.py +1 -14
- langchain_core/output_parsers/base.py +22 -23
- langchain_core/output_parsers/json.py +3 -3
- langchain_core/output_parsers/list.py +1 -1
- langchain_core/output_parsers/openai_functions.py +46 -44
- langchain_core/output_parsers/openai_tools.py +7 -7
- langchain_core/output_parsers/pydantic.py +10 -11
- langchain_core/output_parsers/string.py +1 -1
- langchain_core/output_parsers/transform.py +2 -2
- langchain_core/output_parsers/xml.py +1 -1
- langchain_core/outputs/__init__.py +1 -1
- langchain_core/outputs/chat_generation.py +14 -14
- langchain_core/outputs/generation.py +5 -5
- langchain_core/outputs/llm_result.py +5 -5
- langchain_core/prompt_values.py +5 -5
- langchain_core/prompts/__init__.py +3 -23
- langchain_core/prompts/base.py +32 -37
- langchain_core/prompts/chat.py +216 -222
- langchain_core/prompts/dict.py +2 -2
- langchain_core/prompts/few_shot.py +76 -83
- langchain_core/prompts/few_shot_with_templates.py +6 -8
- langchain_core/prompts/image.py +11 -13
- langchain_core/prompts/loading.py +1 -1
- langchain_core/prompts/message.py +2 -2
- langchain_core/prompts/prompt.py +14 -16
- langchain_core/prompts/string.py +19 -7
- langchain_core/prompts/structured.py +24 -25
- langchain_core/rate_limiters.py +36 -38
- langchain_core/retrievers.py +41 -182
- langchain_core/runnables/base.py +565 -590
- langchain_core/runnables/branch.py +7 -7
- langchain_core/runnables/config.py +37 -44
- langchain_core/runnables/configurable.py +8 -9
- langchain_core/runnables/fallbacks.py +8 -8
- langchain_core/runnables/graph.py +28 -27
- langchain_core/runnables/graph_ascii.py +19 -18
- langchain_core/runnables/graph_mermaid.py +20 -31
- langchain_core/runnables/graph_png.py +7 -7
- langchain_core/runnables/history.py +20 -20
- langchain_core/runnables/passthrough.py +8 -8
- langchain_core/runnables/retry.py +3 -3
- langchain_core/runnables/router.py +1 -1
- langchain_core/runnables/schema.py +33 -33
- langchain_core/runnables/utils.py +30 -34
- langchain_core/stores.py +72 -102
- langchain_core/sys_info.py +27 -29
- langchain_core/tools/__init__.py +1 -14
- langchain_core/tools/base.py +63 -63
- langchain_core/tools/convert.py +92 -92
- langchain_core/tools/render.py +9 -9
- langchain_core/tools/retriever.py +1 -1
- langchain_core/tools/simple.py +6 -7
- langchain_core/tools/structured.py +17 -18
- langchain_core/tracers/__init__.py +1 -9
- langchain_core/tracers/base.py +35 -35
- langchain_core/tracers/context.py +12 -17
- langchain_core/tracers/event_stream.py +3 -3
- langchain_core/tracers/langchain.py +8 -8
- langchain_core/tracers/log_stream.py +17 -18
- langchain_core/tracers/memory_stream.py +2 -2
- langchain_core/tracers/schemas.py +0 -129
- langchain_core/utils/aiter.py +31 -31
- langchain_core/utils/env.py +5 -5
- langchain_core/utils/function_calling.py +48 -120
- langchain_core/utils/html.py +4 -4
- langchain_core/utils/input.py +2 -2
- langchain_core/utils/interactive_env.py +1 -1
- langchain_core/utils/iter.py +19 -19
- langchain_core/utils/json.py +1 -1
- langchain_core/utils/json_schema.py +2 -2
- langchain_core/utils/mustache.py +5 -5
- langchain_core/utils/pydantic.py +17 -17
- langchain_core/utils/strings.py +4 -4
- langchain_core/utils/utils.py +25 -28
- langchain_core/vectorstores/base.py +43 -64
- langchain_core/vectorstores/in_memory.py +83 -85
- langchain_core/version.py +1 -1
- {langchain_core-1.0.0a8.dist-info → langchain_core-1.0.0rc1.dist-info}/METADATA +23 -11
- langchain_core-1.0.0rc1.dist-info/RECORD +172 -0
- langchain_core/memory.py +0 -120
- langchain_core/pydantic_v1/__init__.py +0 -30
- langchain_core/pydantic_v1/dataclasses.py +0 -23
- langchain_core/pydantic_v1/main.py +0 -23
- langchain_core-1.0.0a8.dist-info/RECORD +0 -176
- {langchain_core-1.0.0a8.dist-info → langchain_core-1.0.0rc1.dist-info}/WHEEL +0 -0
|
@@ -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
|
-
|
|
271
|
+
```python
|
|
272
|
+
from langchain_core.prompts import (
|
|
273
|
+
FewShotChatMessagePromptTemplate,
|
|
274
|
+
ChatPromptTemplate,
|
|
275
|
+
)
|
|
272
276
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
+
examples = [
|
|
278
|
+
{"input": "2+2", "output": "4"},
|
|
279
|
+
{"input": "2+3", "output": "5"},
|
|
280
|
+
]
|
|
277
281
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
282
|
+
example_prompt = ChatPromptTemplate.from_messages(
|
|
283
|
+
[
|
|
284
|
+
("human", "What is {input}?"),
|
|
285
|
+
("ai", "{output}"),
|
|
281
286
|
]
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
-
|
|
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
|
-
|
|
357
|
-
|
|
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
|
-
|
|
360
|
-
|
|
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)
|
|
@@ -49,7 +49,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
|
|
49
49
|
"""Get the namespace of the langchain object.
|
|
50
50
|
|
|
51
51
|
Returns:
|
|
52
|
-
|
|
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
|
-
|
|
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.
|
langchain_core/prompts/image.py
CHANGED
|
@@ -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
|
|
30
|
-
|
|
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"] = []
|
|
@@ -52,7 +52,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
|
|
52
52
|
"""Get the namespace of the langchain object.
|
|
53
53
|
|
|
54
54
|
Returns:
|
|
55
|
-
|
|
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
|
|
96
|
+
ValueError: If `'path'` is provided in the template or kwargs.
|
|
97
97
|
|
|
98
98
|
Example:
|
|
99
|
-
|
|
100
|
-
|
|
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.
|
|
142
|
+
encoding: Encoding of the file.
|
|
143
143
|
|
|
144
144
|
Returns:
|
|
145
145
|
A PromptTemplate object.
|
|
@@ -26,7 +26,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
|
|
|
26
26
|
"""Get the namespace of the langchain object.
|
|
27
27
|
|
|
28
28
|
Returns:
|
|
29
|
-
|
|
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. Defaults to `False`.
|
|
72
72
|
|
|
73
73
|
Returns:
|
|
74
74
|
Human-readable representation.
|
langchain_core/prompts/prompt.py
CHANGED
|
@@ -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
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
|
@@ -71,7 +69,7 @@ class PromptTemplate(StringPromptTemplate):
|
|
|
71
69
|
"""Get the namespace of the langchain object.
|
|
72
70
|
|
|
73
71
|
Returns:
|
|
74
|
-
|
|
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
|
|
145
|
+
NotImplementedError: If the other object is not a `PromptTemplate` or str.
|
|
148
146
|
|
|
149
147
|
Returns:
|
|
150
|
-
A new
|
|
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.
|
|
@@ -283,8 +281,8 @@ class PromptTemplate(StringPromptTemplate):
|
|
|
283
281
|
fill in the template. For example, if the template is
|
|
284
282
|
`"{variable1} {variable2}"`, and `partial_variables` is
|
|
285
283
|
`{"variable1": "foo"}`, then the final prompt will be
|
|
286
|
-
`"foo {variable2}"`.
|
|
287
|
-
kwargs: Any other arguments to pass to the prompt template.
|
|
284
|
+
`"foo {variable2}"`.
|
|
285
|
+
**kwargs: Any other arguments to pass to the prompt template.
|
|
288
286
|
|
|
289
287
|
Returns:
|
|
290
288
|
The prompt template loaded from the template.
|
langchain_core/prompts/string.py
CHANGED
|
@@ -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()
|
|
@@ -276,7 +279,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
|
|
|
276
279
|
"""Get the namespace of the langchain object.
|
|
277
280
|
|
|
278
281
|
Returns:
|
|
279
|
-
|
|
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)))
|
|
@@ -65,8 +65,8 @@ class StructuredPrompt(ChatPromptTemplate):
|
|
|
65
65
|
def get_lc_namespace(cls) -> list[str]:
|
|
66
66
|
"""Get the namespace of the langchain object.
|
|
67
67
|
|
|
68
|
-
For example, if the class is
|
|
69
|
-
namespace is
|
|
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
72
|
The namespace of the langchain object.
|
|
@@ -85,35 +85,34 @@ class StructuredPrompt(ChatPromptTemplate):
|
|
|
85
85
|
Examples:
|
|
86
86
|
Instantiation from a list of message templates:
|
|
87
87
|
|
|
88
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
-
|
|
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.
|
|
147
|
+
name: The name of the pipeline.
|
|
149
148
|
|
|
150
149
|
Returns:
|
|
151
150
|
A RunnableSequence object.
|
langchain_core/rate_limiters.py
CHANGED
|
@@ -39,12 +39,12 @@ class BaseRateLimiter(abc.ABC):
|
|
|
39
39
|
of the attempt to acquire the tokens.
|
|
40
40
|
|
|
41
41
|
Args:
|
|
42
|
-
blocking: If True
|
|
43
|
-
If False
|
|
44
|
-
the attempt. Defaults to True
|
|
42
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
43
|
+
If `False`, the method will return immediately with the result of
|
|
44
|
+
the attempt. Defaults to `True`.
|
|
45
45
|
|
|
46
46
|
Returns:
|
|
47
|
-
True if the tokens were successfully acquired, False otherwise.
|
|
47
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
48
48
|
"""
|
|
49
49
|
|
|
50
50
|
@abc.abstractmethod
|
|
@@ -58,12 +58,12 @@ class BaseRateLimiter(abc.ABC):
|
|
|
58
58
|
of the attempt to acquire the tokens.
|
|
59
59
|
|
|
60
60
|
Args:
|
|
61
|
-
blocking: If True
|
|
62
|
-
If False
|
|
63
|
-
the attempt. Defaults to True
|
|
61
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
62
|
+
If `False`, the method will return immediately with the result of
|
|
63
|
+
the attempt. Defaults to `True`.
|
|
64
64
|
|
|
65
65
|
Returns:
|
|
66
|
-
True if the tokens were successfully acquired, False otherwise.
|
|
66
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
67
67
|
"""
|
|
68
68
|
|
|
69
69
|
|
|
@@ -90,36 +90,34 @@ class InMemoryRateLimiter(BaseRateLimiter):
|
|
|
90
90
|
Current limitations:
|
|
91
91
|
|
|
92
92
|
- The rate limiter is not designed to work across different processes. It is
|
|
93
|
-
|
|
93
|
+
an in-memory rate limiter, but it is thread safe.
|
|
94
94
|
- The rate limiter only supports time-based rate limiting. It does not take
|
|
95
|
-
|
|
95
|
+
into account the size of the request or any other factors.
|
|
96
96
|
|
|
97
97
|
Example:
|
|
98
|
+
```python
|
|
99
|
+
import time
|
|
98
100
|
|
|
99
|
-
|
|
101
|
+
from langchain_core.rate_limiters import InMemoryRateLimiter
|
|
100
102
|
|
|
101
|
-
|
|
103
|
+
rate_limiter = InMemoryRateLimiter(
|
|
104
|
+
requests_per_second=0.1, # <-- Can only make a request once every 10 seconds!!
|
|
105
|
+
check_every_n_seconds=0.1, # Wake up every 100 ms to check whether allowed to make a request,
|
|
106
|
+
max_bucket_size=10, # Controls the maximum burst size.
|
|
107
|
+
)
|
|
102
108
|
|
|
103
|
-
|
|
109
|
+
from langchain_anthropic import ChatAnthropic
|
|
104
110
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
max_bucket_size=10, # Controls the maximum burst size.
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
from langchain_anthropic import ChatAnthropic
|
|
112
|
-
|
|
113
|
-
model = ChatAnthropic(
|
|
114
|
-
model_name="claude-3-opus-20240229", rate_limiter=rate_limiter
|
|
115
|
-
)
|
|
116
|
-
|
|
117
|
-
for _ in range(5):
|
|
118
|
-
tic = time.time()
|
|
119
|
-
model.invoke("hello")
|
|
120
|
-
toc = time.time()
|
|
121
|
-
print(toc - tic)
|
|
111
|
+
model = ChatAnthropic(
|
|
112
|
+
model_name="claude-3-opus-20240229", rate_limiter=rate_limiter
|
|
113
|
+
)
|
|
122
114
|
|
|
115
|
+
for _ in range(5):
|
|
116
|
+
tic = time.time()
|
|
117
|
+
model.invoke("hello")
|
|
118
|
+
toc = time.time()
|
|
119
|
+
print(toc - tic)
|
|
120
|
+
```
|
|
123
121
|
|
|
124
122
|
!!! version-added "Added in version 0.2.24"
|
|
125
123
|
|
|
@@ -207,12 +205,12 @@ class InMemoryRateLimiter(BaseRateLimiter):
|
|
|
207
205
|
of the attempt to acquire the tokens.
|
|
208
206
|
|
|
209
207
|
Args:
|
|
210
|
-
blocking: If True
|
|
211
|
-
If False
|
|
212
|
-
the attempt. Defaults to True
|
|
208
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
209
|
+
If `False`, the method will return immediately with the result of
|
|
210
|
+
the attempt. Defaults to `True`.
|
|
213
211
|
|
|
214
212
|
Returns:
|
|
215
|
-
True if the tokens were successfully acquired, False otherwise.
|
|
213
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
216
214
|
"""
|
|
217
215
|
if not blocking:
|
|
218
216
|
return self._consume()
|
|
@@ -231,12 +229,12 @@ class InMemoryRateLimiter(BaseRateLimiter):
|
|
|
231
229
|
of the attempt to acquire the tokens.
|
|
232
230
|
|
|
233
231
|
Args:
|
|
234
|
-
blocking: If True
|
|
235
|
-
If False
|
|
236
|
-
the attempt. Defaults to True
|
|
232
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
233
|
+
If `False`, the method will return immediately with the result of
|
|
234
|
+
the attempt. Defaults to `True`.
|
|
237
235
|
|
|
238
236
|
Returns:
|
|
239
|
-
True if the tokens were successfully acquired, False otherwise.
|
|
237
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
240
238
|
"""
|
|
241
239
|
if not blocking:
|
|
242
240
|
return self._consume()
|