mirror of
https://github.com/hwchase17/langchain.git
synced 2026-06-09 10:17:00 +00:00
style(core): lint (#34862)
it looks scary but i promise it is not improving documentation consistency across core. primarily update docstrings and comments for better formatting, readability, and accuracy, as well as add minor clarifications and formatting improvements to user-facing documentation.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""**Prompt** is the input to the model.
|
||||
"""A prompt is the input to the model.
|
||||
|
||||
Prompt is often constructed from multiple components and prompt values. Prompt classes
|
||||
and functions make constructing and working with prompts easy.
|
||||
|
||||
@@ -45,27 +45,33 @@ class BasePromptTemplate(
|
||||
"""A list of the names of the variables whose values are required as inputs to the
|
||||
prompt.
|
||||
"""
|
||||
|
||||
optional_variables: list[str] = Field(default=[])
|
||||
"""A list of the names of the variables for placeholder or `MessagePlaceholder` that
|
||||
are optional.
|
||||
|
||||
These variables are auto inferred from the prompt and user need not provide them.
|
||||
"""
|
||||
|
||||
input_types: builtins.dict[str, Any] = Field(default_factory=dict, exclude=True)
|
||||
"""A dictionary of the types of the variables the prompt template expects.
|
||||
|
||||
If not provided, all variables are assumed to be strings.
|
||||
"""
|
||||
|
||||
output_parser: BaseOutputParser | None = None
|
||||
"""How to parse the output of calling an LLM on this formatted prompt."""
|
||||
|
||||
partial_variables: Mapping[str, Any] = Field(default_factory=dict)
|
||||
"""A dictionary of the partial variables the prompt template carries.
|
||||
|
||||
Partial variables populate the template so that you don't need to pass them in every
|
||||
time you call the prompt.
|
||||
"""
|
||||
|
||||
metadata: builtins.dict[str, Any] | None = None
|
||||
"""Metadata to be used for tracing."""
|
||||
|
||||
tags: list[str] | None = None
|
||||
"""Tags to be used for tracing."""
|
||||
|
||||
@@ -410,20 +416,18 @@ def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
|
||||
|
||||
First, this pulls information from the document from two sources:
|
||||
|
||||
1. `page_content`:
|
||||
This takes the information from the `document.page_content` and assigns it to a
|
||||
variable named `page_content`.
|
||||
2. `metadata`:
|
||||
This takes information from `document.metadata` and assigns it to variables of
|
||||
the same name.
|
||||
1. `page_content`: This takes the information from the `document.page_content` and
|
||||
assigns it to a variable named `page_content`.
|
||||
2. `metadata`: This takes information from `document.metadata` and assigns it to
|
||||
variables of the same name.
|
||||
|
||||
Those variables are then passed into the `prompt` to produce a formatted string.
|
||||
|
||||
Args:
|
||||
doc: `Document`, the `page_content` and `metadata` will be used to create
|
||||
the final string.
|
||||
prompt: `BasePromptTemplate`, will be used to format the `page_content`
|
||||
and `metadata` into the final string.
|
||||
doc: `Document`, the `page_content` and `metadata` will be used to create the
|
||||
final string.
|
||||
prompt: `BasePromptTemplate`, will be used to format the `page_content` and
|
||||
`metadata` into the final string.
|
||||
|
||||
Returns:
|
||||
String of the document formatted.
|
||||
@@ -436,7 +440,7 @@ def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
|
||||
doc = Document(page_content="This is a joke", metadata={"page": "1"})
|
||||
prompt = PromptTemplate.from_template("Page {page}: {page_content}")
|
||||
format_document(doc, prompt)
|
||||
>>> "Page 1: This is a joke"
|
||||
# -> "Page 1: This is a joke"
|
||||
```
|
||||
"""
|
||||
return prompt.format(**_get_document_info(doc, prompt))
|
||||
@@ -447,20 +451,18 @@ async def aformat_document(doc: Document, prompt: BasePromptTemplate[str]) -> st
|
||||
|
||||
First, this pulls information from the document from two sources:
|
||||
|
||||
1. `page_content`:
|
||||
This takes the information from the `document.page_content` and assigns it to a
|
||||
variable named `page_content`.
|
||||
2. `metadata`:
|
||||
This takes information from `document.metadata` and assigns it to variables of
|
||||
the same name.
|
||||
1. `page_content`: This takes the information from the `document.page_content` and
|
||||
assigns it to a variable named `page_content`.
|
||||
2. `metadata`: This takes information from `document.metadata` and assigns it to
|
||||
variables of the same name.
|
||||
|
||||
Those variables are then passed into the `prompt` to produce a formatted string.
|
||||
|
||||
Args:
|
||||
doc: `Document`, the `page_content` and `metadata` will be used to create
|
||||
the final string.
|
||||
prompt: `BasePromptTemplate`, will be used to format the `page_content`
|
||||
and `metadata` into the final string.
|
||||
doc: `Document`, the `page_content` and `metadata` will be used to create the
|
||||
final string.
|
||||
prompt: `BasePromptTemplate`, will be used to format the `page_content` and
|
||||
`metadata` into the final string.
|
||||
|
||||
Returns:
|
||||
String of the document formatted.
|
||||
|
||||
@@ -54,7 +54,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
|
||||
A placeholder which can be used to pass in a list of messages.
|
||||
|
||||
Direct usage:
|
||||
!!! example "Direct usage"
|
||||
|
||||
```python
|
||||
from langchain_core.prompts import MessagesPlaceholder
|
||||
@@ -77,7 +77,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
# ]
|
||||
```
|
||||
|
||||
Building a prompt with chat history:
|
||||
!!! example "Building a prompt with chat history"
|
||||
|
||||
```python
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
@@ -103,7 +103,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
# ])
|
||||
```
|
||||
|
||||
Limiting the number of messages:
|
||||
!!! example "Limiting the number of messages"
|
||||
|
||||
```python
|
||||
from langchain_core.prompts import MessagesPlaceholder
|
||||
@@ -126,12 +126,19 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
"""Name of variable to use as messages."""
|
||||
|
||||
optional: bool = False
|
||||
"""If `True` format_messages can be called with no arguments and will return an
|
||||
empty list. If `False` then a named argument with name `variable_name` must be
|
||||
passed in, even if the value is an empty list."""
|
||||
"""Whether `format_messages` must be provided.
|
||||
|
||||
If `True` `format_messages` can be called with no arguments and will return an empty
|
||||
list.
|
||||
|
||||
If `False` then a named argument with name `variable_name` must be passed in, even
|
||||
if the value is an empty list.
|
||||
"""
|
||||
|
||||
n_messages: PositiveInt | None = None
|
||||
"""Maximum number of messages to include. If `None`, then will include all.
|
||||
"""Maximum number of messages to include.
|
||||
|
||||
If `None`, then will include all.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -141,13 +148,17 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
|
||||
Args:
|
||||
variable_name: Name of variable to use as messages.
|
||||
optional: If `True` format_messages can be called with no arguments and will
|
||||
return an empty list. If `False` then a named argument with name
|
||||
`variable_name` must be passed in, even if the value is an empty list.
|
||||
optional: Whether `format_messages` must be provided.
|
||||
|
||||
If `True` format_messages can be called with no arguments and will
|
||||
return an empty list.
|
||||
|
||||
If `False` then a named argument with name `variable_name` must be
|
||||
passed in, even if the value is an empty list.
|
||||
"""
|
||||
# mypy can't detect the init which is defined in the parent class
|
||||
# b/c these are BaseModel classes.
|
||||
super().__init__(variable_name=variable_name, optional=optional, **kwargs)
|
||||
super().__init__(variable_name=variable_name, optional=optional, **kwargs) # type: ignore[call-arg,unused-ignore]
|
||||
|
||||
def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
|
||||
"""Format messages from kwargs.
|
||||
@@ -156,7 +167,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
List of BaseMessage.
|
||||
List of `BaseMessage` objects.
|
||||
|
||||
Raises:
|
||||
ValueError: If variable is not a list of messages.
|
||||
@@ -216,6 +227,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
|
||||
prompt: StringPromptTemplate
|
||||
"""String prompt template."""
|
||||
|
||||
additional_kwargs: dict = Field(default_factory=dict)
|
||||
"""Additional keyword arguments to pass to the prompt template."""
|
||||
|
||||
@@ -233,12 +245,13 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
template: a template.
|
||||
template_format: format of the template.
|
||||
partial_variables: A dictionary of variables that can be used to partially
|
||||
fill in the template. For example, if the template is
|
||||
`"{variable1} {variable2}"`, and `partial_variables` is
|
||||
`{"variable1": "foo"}`, then the final prompt will be
|
||||
`"foo {variable2}"`.
|
||||
fill in the template.
|
||||
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
For example, if the template is `"{variable1} {variable2}"`, and
|
||||
`partial_variables` is `{"variable1": "foo"}`, then the final prompt
|
||||
will be `"foo {variable2}"`.
|
||||
|
||||
**kwargs: Keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
A new instance of this class.
|
||||
@@ -259,8 +272,8 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
"""Create a class from a template file.
|
||||
|
||||
Args:
|
||||
template_file: path to a template file. String or Path.
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
template_file: path to a template file.
|
||||
**kwargs: Keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
A new instance of this class.
|
||||
@@ -297,7 +310,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
List of BaseMessages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
return [self.format(**kwargs)]
|
||||
|
||||
@@ -308,7 +321,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
List of BaseMessages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
return [await self.aformat(**kwargs)]
|
||||
|
||||
@@ -408,10 +421,11 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
|
||||
Args:
|
||||
template: a template.
|
||||
template_format: format of the template.
|
||||
Options are: 'f-string', 'mustache', 'jinja2'.
|
||||
|
||||
Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
|
||||
partial_variables: A dictionary of variables that can be used too partially.
|
||||
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
**kwargs: Keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
A new instance of this class.
|
||||
@@ -524,9 +538,9 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
|
||||
"""Create a class from a template file.
|
||||
|
||||
Args:
|
||||
template_file: path to a template file. String or Path.
|
||||
template_file: path to a template file.
|
||||
input_variables: list of input variables.
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
**kwargs: Keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
A new instance of this class.
|
||||
@@ -541,7 +555,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
List of BaseMessages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
return [self.format(**kwargs)]
|
||||
|
||||
@@ -552,7 +566,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
List of BaseMessages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
return [await self.aformat(**kwargs)]
|
||||
|
||||
@@ -647,13 +661,19 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
|
||||
|
||||
|
||||
class HumanMessagePromptTemplate(_StringImageMessagePromptTemplate):
|
||||
"""Human message prompt template. This is a message sent from the user."""
|
||||
"""Human message prompt template.
|
||||
|
||||
This is a message sent from the user.
|
||||
"""
|
||||
|
||||
_msg_class: type[BaseMessage] = HumanMessage
|
||||
|
||||
|
||||
class AIMessagePromptTemplate(_StringImageMessagePromptTemplate):
|
||||
"""AI message prompt template. This is a message sent from the AI."""
|
||||
"""AI message prompt template.
|
||||
|
||||
This is a message sent from the AI.
|
||||
"""
|
||||
|
||||
_msg_class: type[BaseMessage] = AIMessage
|
||||
|
||||
@@ -679,11 +699,11 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
|
||||
"""Format the chat template into a string.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
**kwargs: Keyword arguments to use for filling in template variables in all
|
||||
the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
formatted string.
|
||||
Formatted string.
|
||||
"""
|
||||
return self.format_prompt(**kwargs).to_string()
|
||||
|
||||
@@ -691,34 +711,32 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
|
||||
"""Async format the chat template into a string.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
**kwargs: Keyword arguments to use for filling in template variables in all
|
||||
the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
formatted string.
|
||||
Formatted string.
|
||||
"""
|
||||
return (await self.aformat_prompt(**kwargs)).to_string()
|
||||
|
||||
def format_prompt(self, **kwargs: Any) -> ChatPromptValue:
|
||||
"""Format prompt. Should return a ChatPromptValue.
|
||||
"""Format prompt.
|
||||
|
||||
Should return a `ChatPromptValue`.
|
||||
|
||||
Args:
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
ChatPromptValue.
|
||||
"""
|
||||
messages = self.format_messages(**kwargs)
|
||||
return ChatPromptValue(messages=messages)
|
||||
|
||||
async def aformat_prompt(self, **kwargs: Any) -> ChatPromptValue:
|
||||
"""Async format prompt. Should return a ChatPromptValue.
|
||||
"""Async format prompt.
|
||||
|
||||
Should return a `ChatPromptValue`.
|
||||
|
||||
Args:
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
PromptValue.
|
||||
"""
|
||||
messages = await self.aformat_messages(**kwargs)
|
||||
return ChatPromptValue(messages=messages)
|
||||
@@ -728,14 +746,14 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
|
||||
"""Format kwargs into a list of messages.
|
||||
|
||||
Returns:
|
||||
List of messages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
|
||||
async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
|
||||
"""Async format kwargs into a list of messages.
|
||||
|
||||
Returns:
|
||||
List of messages.
|
||||
List of `BaseMessage` objects.
|
||||
"""
|
||||
return self.format_messages(**kwargs)
|
||||
|
||||
@@ -773,34 +791,36 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Use to create flexible templated prompts for chat models.
|
||||
|
||||
```python
|
||||
from langchain_core.prompts import ChatPromptTemplate
|
||||
!!! example
|
||||
|
||||
template = ChatPromptTemplate(
|
||||
[
|
||||
("system", "You are a helpful AI bot. Your name is {name}."),
|
||||
("human", "Hello, how are you doing?"),
|
||||
("ai", "I'm doing well, thanks!"),
|
||||
("human", "{user_input}"),
|
||||
]
|
||||
)
|
||||
```python
|
||||
from langchain_core.prompts import ChatPromptTemplate
|
||||
|
||||
prompt_value = template.invoke(
|
||||
{
|
||||
"name": "Bob",
|
||||
"user_input": "What is your name?",
|
||||
}
|
||||
)
|
||||
# Output:
|
||||
# ChatPromptValue(
|
||||
# messages=[
|
||||
# SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
|
||||
# HumanMessage(content='Hello, how are you doing?'),
|
||||
# AIMessage(content="I'm doing well, thanks!"),
|
||||
# HumanMessage(content='What is your name?')
|
||||
# ]
|
||||
# )
|
||||
```
|
||||
template = ChatPromptTemplate(
|
||||
[
|
||||
("system", "You are a helpful AI bot. Your name is {name}."),
|
||||
("human", "Hello, how are you doing?"),
|
||||
("ai", "I'm doing well, thanks!"),
|
||||
("human", "{user_input}"),
|
||||
]
|
||||
)
|
||||
|
||||
prompt_value = template.invoke(
|
||||
{
|
||||
"name": "Bob",
|
||||
"user_input": "What is your name?",
|
||||
}
|
||||
)
|
||||
# Output:
|
||||
# ChatPromptValue(
|
||||
# messages=[
|
||||
# SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
|
||||
# HumanMessage(content='Hello, how are you doing?'),
|
||||
# AIMessage(content="I'm doing well, thanks!"),
|
||||
# HumanMessage(content='What is your name?')
|
||||
# ]
|
||||
# )
|
||||
```
|
||||
|
||||
!!! note "Messages Placeholder"
|
||||
|
||||
@@ -845,8 +865,8 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
!!! note "Single-variable template"
|
||||
|
||||
If your prompt has only a single input variable (i.e., 1 instance of
|
||||
"{variable_nams}"), and you invoke the template with a non-dict object, the
|
||||
If your prompt has only a single input variable (i.e., one instance of
|
||||
`'{variable_nams}'`), and you invoke the template with a non-dict object, the
|
||||
prompt template will inject the provided argument into that variable location.
|
||||
|
||||
```python
|
||||
@@ -875,6 +895,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
messages: Annotated[list[MessageLike], SkipValidation()]
|
||||
"""List of messages consisting of either message prompt templates or messages."""
|
||||
|
||||
validate_template: bool = False
|
||||
"""Whether or not to try validating the template."""
|
||||
|
||||
@@ -895,10 +916,10 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
1. `BaseMessagePromptTemplate`
|
||||
2. `BaseMessage`
|
||||
3. 2-tuple of `(message type, template)`; e.g.,
|
||||
`("human", "{user_input}")`
|
||||
`('human', '{user_input}')`
|
||||
4. 2-tuple of `(message class, template)`
|
||||
5. A string which is shorthand for `("human", template)`; e.g.,
|
||||
`"{user_input}"`
|
||||
5. A string which is shorthand for `('human', template)`; e.g.,
|
||||
`'{user_input}'`
|
||||
template_format: Format of the template.
|
||||
**kwargs: Additional keyword arguments passed to `BasePromptTemplate`,
|
||||
including (but not limited to):
|
||||
@@ -1027,8 +1048,8 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
def validate_input_variables(cls, values: dict) -> Any:
|
||||
"""Validate input variables.
|
||||
|
||||
If input_variables is not set, it will be set to the union of
|
||||
all input variables in the messages.
|
||||
If `input_variables` is not set, it will be set to the union of all input
|
||||
variables in the messages.
|
||||
|
||||
Args:
|
||||
values: values to validate.
|
||||
@@ -1080,12 +1101,12 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
|
||||
"""Create a chat prompt template from a template string.
|
||||
|
||||
Creates a chat template consisting of a single message assumed to be from
|
||||
the human.
|
||||
Creates a chat template consisting of a single message assumed to be from the
|
||||
human.
|
||||
|
||||
Args:
|
||||
template: template string
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
template: Template string
|
||||
**kwargs: Keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
A new instance of this class.
|
||||
@@ -1133,14 +1154,14 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
1. `BaseMessagePromptTemplate`
|
||||
2. `BaseMessage`
|
||||
3. 2-tuple of `(message type, template)`; e.g.,
|
||||
`("human", "{user_input}")`
|
||||
`('human', '{user_input}')`
|
||||
4. 2-tuple of `(message class, template)`
|
||||
5. A string which is shorthand for `("human", template)`; e.g.,
|
||||
`"{user_input}"`
|
||||
template_format: format of the template.
|
||||
5. A string which is shorthand for `('human', template)`; e.g.,
|
||||
`'{user_input}'`
|
||||
template_format: Format of the template.
|
||||
|
||||
Returns:
|
||||
a chat prompt template.
|
||||
A chat prompt template.
|
||||
|
||||
"""
|
||||
return cls(messages, template_format=template_format)
|
||||
@@ -1149,14 +1170,14 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
"""Format the chat template into a list of finalized messages.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
**kwargs: Keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Raises:
|
||||
ValueError: if messages are of unexpected types.
|
||||
ValueError: If messages are of unexpected types.
|
||||
|
||||
Returns:
|
||||
list of formatted messages.
|
||||
List of formatted messages.
|
||||
"""
|
||||
kwargs = self._merge_partial_and_user_variables(**kwargs)
|
||||
result = []
|
||||
@@ -1177,11 +1198,11 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
"""Async format the chat template into a list of finalized messages.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
**kwargs: Keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
list of formatted messages.
|
||||
List of formatted messages.
|
||||
|
||||
Raises:
|
||||
ValueError: If unexpected input.
|
||||
@@ -1202,15 +1223,15 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
return result
|
||||
|
||||
def partial(self, **kwargs: Any) -> ChatPromptTemplate:
|
||||
"""Get a new ChatPromptTemplate with some input variables already filled in.
|
||||
"""Get a new `ChatPromptTemplate` with some input variables already filled in.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables. Ought
|
||||
to be a subset of the input variables.
|
||||
**kwargs: Keyword arguments to use for filling in template variables.
|
||||
|
||||
Ought to be a subset of the input variables.
|
||||
|
||||
Returns:
|
||||
A new ChatPromptTemplate.
|
||||
|
||||
A new `ChatPromptTemplate`.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@@ -1265,8 +1286,9 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Returns:
|
||||
If index is an int, returns the message at that index.
|
||||
If index is a slice, returns a new `ChatPromptTemplate`
|
||||
containing the messages in that slice.
|
||||
|
||||
If index is a slice, returns a new `ChatPromptTemplate` containing the
|
||||
messages in that slice.
|
||||
"""
|
||||
if isinstance(index, slice):
|
||||
start, stop, step = index.indices(len(self.messages))
|
||||
@@ -1313,12 +1335,12 @@ def _create_template_from_message_type(
|
||||
"""Create a message prompt template from a message type and template string.
|
||||
|
||||
Args:
|
||||
message_type: str the type of the message template (e.g., "human", "ai", etc.)
|
||||
template: str the template string.
|
||||
template_format: format of the template.
|
||||
message_type: The type of the message template (e.g., `'human'`, `'ai'`, etc.)
|
||||
template: The template string.
|
||||
template_format: Format of the template.
|
||||
|
||||
Returns:
|
||||
a message prompt template of the appropriate type.
|
||||
A message prompt template of the appropriate type.
|
||||
|
||||
Raises:
|
||||
ValueError: If unexpected message type.
|
||||
@@ -1388,20 +1410,20 @@ def _convert_to_message_template(
|
||||
) -> BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate:
|
||||
"""Instantiate a message from a variety of message formats.
|
||||
|
||||
The message format can be one of the following:
|
||||
A message can be represented using the following formats:
|
||||
|
||||
- BaseMessagePromptTemplate
|
||||
- BaseMessage
|
||||
- 2-tuple of (role string, template); e.g., ("human", "{user_input}")
|
||||
- 2-tuple of (message class, template)
|
||||
- string: shorthand for ("human", template); e.g., "{user_input}"
|
||||
1. `BaseMessagePromptTemplate`
|
||||
2. `BaseMessage`
|
||||
3. 2-tuple of `(message type, template)`; e.g., `('human', '{user_input}')`
|
||||
4. 2-tuple of `(message class, template)`
|
||||
5. A string which is shorthand for `('human', template)`; e.g., `'{user_input}'`
|
||||
|
||||
Args:
|
||||
message: a representation of a message in one of the supported formats.
|
||||
template_format: format of the template.
|
||||
message: A representation of a message in one of the supported formats.
|
||||
template_format: Format of the template.
|
||||
|
||||
Returns:
|
||||
an instance of a message or a message template.
|
||||
An instance of a message or a message template.
|
||||
|
||||
Raises:
|
||||
ValueError: If unexpected message type.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Dict prompt template."""
|
||||
"""Dictionary prompt template."""
|
||||
|
||||
import warnings
|
||||
from functools import cached_property
|
||||
@@ -16,10 +16,11 @@ from langchain_core.runnables.config import ensure_config
|
||||
|
||||
|
||||
class DictPromptTemplate(RunnableSerializable[dict, dict]):
|
||||
"""Template represented by a dict.
|
||||
"""Template represented by a dictionary.
|
||||
|
||||
Recognizes variables in f-string or mustache formatted string dict values. Does NOT
|
||||
recognize variables in dict keys. Applies recursively.
|
||||
Recognizes variables in f-string or mustache formatted string dict values.
|
||||
|
||||
Does NOT recognize variables in dict keys. Applies recursively.
|
||||
"""
|
||||
|
||||
template: dict[str, Any]
|
||||
|
||||
@@ -35,11 +35,15 @@ class _FewShotPromptTemplateMixin(BaseModel):
|
||||
|
||||
examples: list[dict] | None = None
|
||||
"""Examples to format into the prompt.
|
||||
Either this or example_selector should be provided."""
|
||||
|
||||
Either this or `example_selector` should be provided.
|
||||
"""
|
||||
|
||||
example_selector: BaseExampleSelector | None = None
|
||||
"""ExampleSelector to choose the examples to format into the prompt.
|
||||
Either this or examples should be provided."""
|
||||
"""`ExampleSelector` to choose the examples to format into the prompt.
|
||||
|
||||
Either this or `examples` should be provided.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
arbitrary_types_allowed=True,
|
||||
@@ -49,7 +53,7 @@ class _FewShotPromptTemplateMixin(BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def check_examples_and_selector(cls, values: dict) -> Any:
|
||||
"""Check that one and only one of examples/example_selector are provided.
|
||||
"""Check that one and only one of `examples`/`example_selector` are provided.
|
||||
|
||||
Args:
|
||||
values: The values to check.
|
||||
@@ -58,8 +62,9 @@ class _FewShotPromptTemplateMixin(BaseModel):
|
||||
The values if they are valid.
|
||||
|
||||
Raises:
|
||||
ValueError: If neither or both examples and example_selector are provided.
|
||||
ValueError: If both examples and example_selector are provided.
|
||||
ValueError: If neither or both `examples` and `example_selector` are
|
||||
provided.
|
||||
ValueError: If both `examples` and `example_selector` are provided.
|
||||
"""
|
||||
examples = values.get("examples")
|
||||
example_selector = values.get("example_selector")
|
||||
@@ -83,7 +88,7 @@ class _FewShotPromptTemplateMixin(BaseModel):
|
||||
List of examples.
|
||||
|
||||
Raises:
|
||||
ValueError: If neither examples nor example_selector are provided.
|
||||
ValueError: If neither `examples` nor `example_selector` are provided.
|
||||
"""
|
||||
if self.examples is not None:
|
||||
return self.examples
|
||||
@@ -102,7 +107,7 @@ class _FewShotPromptTemplateMixin(BaseModel):
|
||||
List of examples.
|
||||
|
||||
Raises:
|
||||
ValueError: If neither examples nor example_selector are provided.
|
||||
ValueError: If neither `examples` nor `example_selector` are provided.
|
||||
"""
|
||||
if self.examples is not None:
|
||||
return self.examples
|
||||
@@ -117,14 +122,14 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
|
||||
|
||||
@classmethod
|
||||
def is_lc_serializable(cls) -> bool:
|
||||
"""Return False as this class is not serializable."""
|
||||
"""Return `False` as this class is not serializable."""
|
||||
return False
|
||||
|
||||
validate_template: bool = False
|
||||
"""Whether or not to try validating the template."""
|
||||
|
||||
example_prompt: PromptTemplate
|
||||
"""PromptTemplate used to format an individual example."""
|
||||
"""`PromptTemplate` used to format an individual example."""
|
||||
|
||||
suffix: str
|
||||
"""A prompt template string to put after the examples."""
|
||||
@@ -136,7 +141,10 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
|
||||
"""A prompt template string to put before the examples."""
|
||||
|
||||
template_format: Literal["f-string", "jinja2"] = "f-string"
|
||||
"""The format of the prompt template. Options are: 'f-string', 'jinja2'."""
|
||||
"""The format of the prompt template.
|
||||
|
||||
Options are: `'f-string'`, `'jinja2'`.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
"""Initialize the few shot prompt template."""
|
||||
@@ -174,7 +182,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
|
||||
Use this method to generate a string representation of a prompt.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for formatting.
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
A string representation of the prompt.
|
||||
@@ -202,7 +210,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
|
||||
Use this method to generate a string representation of a prompt.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for formatting.
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
A string representation of the prompt.
|
||||
@@ -236,7 +244,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
|
||||
file_path: The path to save the prompt template to.
|
||||
|
||||
Raises:
|
||||
ValueError: If example_selector is provided.
|
||||
ValueError: If `example_selector` is provided.
|
||||
"""
|
||||
if self.example_selector:
|
||||
msg = "Saving an example selector is not currently supported"
|
||||
@@ -254,15 +262,22 @@ class FewShotChatMessagePromptTemplate(
|
||||
|
||||
This structure enables creating a conversation with intermediate examples like:
|
||||
|
||||
System: You are a helpful AI Assistant
|
||||
Human: What is 2+2?
|
||||
AI: 4
|
||||
Human: What is 2+3?
|
||||
AI: 5
|
||||
Human: What is 4+4?
|
||||
```txt
|
||||
System: You are a helpful AI Assistant
|
||||
|
||||
This prompt template can be used to generate a fixed list of examples or else
|
||||
to dynamically select examples based on the input.
|
||||
Human: What is 2+2?
|
||||
|
||||
AI: 4
|
||||
|
||||
Human: What is 2+3?
|
||||
|
||||
AI: 5
|
||||
|
||||
Human: What is 4+4?
|
||||
```
|
||||
|
||||
This prompt template can be used to generate a fixed list of examples or else to
|
||||
dynamically select examples based on the input.
|
||||
|
||||
Examples:
|
||||
Prompt template with a fixed list of examples (matching the sample
|
||||
@@ -355,15 +370,16 @@ class FewShotChatMessagePromptTemplate(
|
||||
"""
|
||||
|
||||
input_variables: list[str] = Field(default_factory=list)
|
||||
"""A list of the names of the variables the prompt template will use
|
||||
to pass to the example_selector, if provided."""
|
||||
"""A list of the names of the variables the prompt template will use to pass to
|
||||
the `example_selector`, if provided.
|
||||
"""
|
||||
|
||||
example_prompt: BaseMessagePromptTemplate | BaseChatPromptTemplate
|
||||
"""The class to format each example."""
|
||||
|
||||
@classmethod
|
||||
def is_lc_serializable(cls) -> bool:
|
||||
"""Return False as this class is not serializable."""
|
||||
"""Return `False` as this class is not serializable."""
|
||||
return False
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -375,7 +391,7 @@ class FewShotChatMessagePromptTemplate(
|
||||
"""Format kwargs into a list of messages.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in templates in messages.
|
||||
**kwargs: Keyword arguments to use for filling in templates in messages.
|
||||
|
||||
Returns:
|
||||
A list of formatted messages with all template variables filled in.
|
||||
@@ -396,7 +412,7 @@ class FewShotChatMessagePromptTemplate(
|
||||
"""Async format kwargs into a list of messages.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in templates in messages.
|
||||
**kwargs: Keyword arguments to use for filling in templates in messages.
|
||||
|
||||
Returns:
|
||||
A list of formatted messages with all template variables filled in.
|
||||
@@ -416,13 +432,13 @@ class FewShotChatMessagePromptTemplate(
|
||||
def format(self, **kwargs: Any) -> str:
|
||||
"""Format the prompt with inputs generating a string.
|
||||
|
||||
Use this method to generate a string representation of a prompt consisting
|
||||
of chat messages.
|
||||
Use this method to generate a string representation of a prompt consisting of
|
||||
chat messages.
|
||||
|
||||
Useful for feeding into a string-based completion language model or debugging.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for formatting.
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
A string representation of the prompt
|
||||
@@ -433,13 +449,13 @@ class FewShotChatMessagePromptTemplate(
|
||||
async def aformat(self, **kwargs: Any) -> str:
|
||||
"""Async format the prompt with inputs generating a string.
|
||||
|
||||
Use this method to generate a string representation of a prompt consisting
|
||||
of chat messages.
|
||||
Use this method to generate a string representation of a prompt consisting of
|
||||
chat messages.
|
||||
|
||||
Useful for feeding into a string-based completion language model or debugging.
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for formatting.
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
Returns:
|
||||
A string representation of the prompt
|
||||
|
||||
@@ -20,27 +20,33 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
||||
|
||||
examples: list[dict] | None = None
|
||||
"""Examples to format into the prompt.
|
||||
Either this or example_selector should be provided."""
|
||||
|
||||
Either this or `example_selector` should be provided.
|
||||
"""
|
||||
|
||||
example_selector: BaseExampleSelector | None = None
|
||||
"""ExampleSelector to choose the examples to format into the prompt.
|
||||
Either this or examples should be provided."""
|
||||
"""`ExampleSelector` to choose the examples to format into the prompt.
|
||||
|
||||
Either this or `examples` should be provided.
|
||||
"""
|
||||
|
||||
example_prompt: PromptTemplate
|
||||
"""PromptTemplate used to format an individual example."""
|
||||
"""`PromptTemplate` used to format an individual example."""
|
||||
|
||||
suffix: StringPromptTemplate
|
||||
"""A PromptTemplate to put after the examples."""
|
||||
"""A `PromptTemplate` to put after the examples."""
|
||||
|
||||
example_separator: str = "\n\n"
|
||||
"""String separator used to join the prefix, the examples, and suffix."""
|
||||
|
||||
prefix: StringPromptTemplate | None = None
|
||||
"""A PromptTemplate to put before the examples."""
|
||||
"""A `PromptTemplate` to put before the examples."""
|
||||
|
||||
template_format: PromptTemplateFormat = "f-string"
|
||||
"""The format of the prompt template.
|
||||
Options are: 'f-string', 'jinja2', 'mustache'."""
|
||||
|
||||
Options are: `'f-string'`, `'jinja2'`, `'mustache'`.
|
||||
"""
|
||||
|
||||
validate_template: bool = False
|
||||
"""Whether or not to try validating the template."""
|
||||
@@ -123,9 +129,9 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
||||
A formatted string.
|
||||
|
||||
Example:
|
||||
```python
|
||||
prompt.format(variable1="foo")
|
||||
```
|
||||
```python
|
||||
prompt.format(variable1="foo")
|
||||
```
|
||||
"""
|
||||
kwargs = self._merge_partial_and_user_variables(**kwargs)
|
||||
# Get the examples to use.
|
||||
@@ -216,7 +222,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
||||
file_path: The path to save the prompt to.
|
||||
|
||||
Raises:
|
||||
ValueError: If example_selector is provided.
|
||||
ValueError: If `example_selector` is provided.
|
||||
"""
|
||||
if self.example_selector:
|
||||
msg = "Saving an example selector is not currently supported"
|
||||
|
||||
@@ -18,9 +18,12 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
||||
|
||||
template: dict = Field(default_factory=dict)
|
||||
"""Template for the prompt."""
|
||||
|
||||
template_format: PromptTemplateFormat = "f-string"
|
||||
"""The format of the prompt template.
|
||||
Options are: 'f-string', 'mustache', 'jinja2'."""
|
||||
|
||||
Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
"""Create an image prompt template.
|
||||
|
||||
@@ -18,13 +18,13 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def load_prompt_from_config(config: dict) -> BasePromptTemplate:
|
||||
"""Load prompt from Config Dict.
|
||||
"""Load prompt from config dict.
|
||||
|
||||
Args:
|
||||
config: Dict containing the prompt configuration.
|
||||
|
||||
Returns:
|
||||
A PromptTemplate object.
|
||||
A `PromptTemplate` object.
|
||||
|
||||
Raises:
|
||||
ValueError: If the prompt type is not supported.
|
||||
@@ -135,17 +135,17 @@ def _load_prompt(config: dict) -> PromptTemplate:
|
||||
|
||||
|
||||
def load_prompt(path: str | Path, encoding: str | None = None) -> BasePromptTemplate:
|
||||
"""Unified method for loading a prompt from LangChainHub or local fs.
|
||||
"""Unified method for loading a prompt from LangChainHub or local filesystem.
|
||||
|
||||
Args:
|
||||
path: Path to the prompt file.
|
||||
encoding: Encoding of the file.
|
||||
|
||||
Returns:
|
||||
A PromptTemplate object.
|
||||
A `PromptTemplate` object.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the path is a Lang Chain Hub path.
|
||||
RuntimeError: If the path is a LangChainHub path.
|
||||
"""
|
||||
if isinstance(path, str) and path.startswith("lc://"):
|
||||
msg = (
|
||||
|
||||
@@ -32,7 +32,9 @@ class BaseMessagePromptTemplate(Serializable, ABC):
|
||||
|
||||
@abstractmethod
|
||||
def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
|
||||
"""Format messages from kwargs. Should return a list of `BaseMessage` objects.
|
||||
"""Format messages from kwargs.
|
||||
|
||||
Should return a list of `BaseMessage` objects.
|
||||
|
||||
Args:
|
||||
**kwargs: Keyword arguments to use for formatting.
|
||||
|
||||
@@ -27,21 +27,22 @@ class PromptTemplate(StringPromptTemplate):
|
||||
A prompt template consists of a string template. It accepts a set of parameters
|
||||
from the user that can be used to generate a prompt for a language model.
|
||||
|
||||
The template can be formatted using either f-strings (default), jinja2,
|
||||
or mustache syntax.
|
||||
The template can be formatted using either f-strings (default), jinja2, or mustache
|
||||
syntax.
|
||||
|
||||
*Security warning*:
|
||||
Prefer using `template_format="f-string"` instead of
|
||||
`template_format="jinja2"`, or make sure to NEVER accept jinja2 templates
|
||||
from untrusted sources as they may lead to arbitrary Python code execution.
|
||||
!!! warning "Security"
|
||||
|
||||
As of LangChain 0.0.329, Jinja2 templates will be rendered using
|
||||
Jinja2's SandboxedEnvironment by default. This sand-boxing should
|
||||
be treated as a best-effort approach rather than a guarantee of security,
|
||||
as it is an opt-out rather than opt-in approach.
|
||||
Prefer using `template_format='f-string'` instead of `template_format='jinja2'`,
|
||||
or make sure to NEVER accept jinja2 templates from untrusted sources as they may
|
||||
lead to arbitrary Python code execution.
|
||||
|
||||
Despite the sand-boxing, we recommend to never use jinja2 templates
|
||||
from untrusted sources.
|
||||
As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
|
||||
SandboxedEnvironment by default. This sand-boxing should be treated as a
|
||||
best-effort approach rather than a guarantee of security, as it is an opt-out
|
||||
rather than opt-in approach.
|
||||
|
||||
Despite the sandboxing, we recommend to never use jinja2 templates from
|
||||
untrusted sources.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@@ -78,7 +79,9 @@ class PromptTemplate(StringPromptTemplate):
|
||||
|
||||
template_format: PromptTemplateFormat = "f-string"
|
||||
"""The format of the prompt template.
|
||||
Options are: 'f-string', 'mustache', 'jinja2'."""
|
||||
|
||||
Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
|
||||
"""
|
||||
|
||||
validate_template: bool = False
|
||||
"""Whether or not to try validating the template."""
|
||||
@@ -137,7 +140,7 @@ class PromptTemplate(StringPromptTemplate):
|
||||
return mustache_schema(self.template)
|
||||
|
||||
def __add__(self, other: Any) -> PromptTemplate:
|
||||
"""Override the + operator to allow for combining prompt templates.
|
||||
"""Override the `+` operator to allow for combining prompt templates.
|
||||
|
||||
Raises:
|
||||
ValueError: If the template formats are not f-string or if there are
|
||||
@@ -213,14 +216,15 @@ class PromptTemplate(StringPromptTemplate):
|
||||
|
||||
Args:
|
||||
examples: List of examples to use in the prompt.
|
||||
suffix: String to go after the list of examples. Should generally
|
||||
set up the user's input.
|
||||
input_variables: A list of variable names the final prompt template
|
||||
will expect.
|
||||
example_separator: The separator to use in between examples. Defaults
|
||||
to two new line characters.
|
||||
prefix: String that should go before any examples. Generally includes
|
||||
examples.
|
||||
suffix: String to go after the list of examples.
|
||||
|
||||
Should generally set up the user's input.
|
||||
input_variables: A list of variable names the final prompt template will
|
||||
expect.
|
||||
example_separator: The separator to use in between examples.
|
||||
prefix: String that should go before any examples.
|
||||
|
||||
Generally includes examples.
|
||||
|
||||
Returns:
|
||||
The final prompt generated.
|
||||
@@ -240,6 +244,7 @@ class PromptTemplate(StringPromptTemplate):
|
||||
Args:
|
||||
template_file: The path to the file containing the prompt template.
|
||||
encoding: The encoding system for opening the template file.
|
||||
|
||||
If not provided, will use the OS default.
|
||||
|
||||
Returns:
|
||||
@@ -259,28 +264,32 @@ class PromptTemplate(StringPromptTemplate):
|
||||
) -> PromptTemplate:
|
||||
"""Load a prompt template from a template.
|
||||
|
||||
*Security warning*:
|
||||
Prefer using `template_format="f-string"` instead of
|
||||
`template_format="jinja2"`, or make sure to NEVER accept jinja2 templates
|
||||
!!! warning "Security"
|
||||
|
||||
Prefer using `template_format='f-string'` instead of
|
||||
`template_format='jinja2'`, or make sure to NEVER accept jinja2 templates
|
||||
from untrusted sources as they may lead to arbitrary Python code execution.
|
||||
|
||||
As of LangChain 0.0.329, Jinja2 templates will be rendered using
|
||||
Jinja2's SandboxedEnvironment by default. This sand-boxing should
|
||||
be treated as a best-effort approach rather than a guarantee of security,
|
||||
as it is an opt-out rather than opt-in approach.
|
||||
As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
|
||||
SandboxedEnvironment by default. This sand-boxing should be treated as a
|
||||
best-effort approach rather than a guarantee of security, as it is an
|
||||
opt-out rather than opt-in approach.
|
||||
|
||||
Despite the sand-boxing, we recommend never using jinja2 templates
|
||||
from untrusted sources.
|
||||
Despite the sandboxing, we recommend to never use jinja2 templates from
|
||||
untrusted sources.
|
||||
|
||||
Args:
|
||||
template: The template to load.
|
||||
template_format: The format of the template. Use `jinja2` for jinja2,
|
||||
`mustache` for mustache, and `f-string` for f-strings.
|
||||
template_format: The format of the template.
|
||||
|
||||
Use `jinja2` for jinja2, `mustache` for mustache, and `f-string` for
|
||||
f-strings.
|
||||
partial_variables: A dictionary of variables that can be used to partially
|
||||
fill in the template. For example, if the template is
|
||||
`"{variable1} {variable2}"`, and `partial_variables` is
|
||||
`{"variable1": "foo"}`, then the final prompt will be
|
||||
`"foo {variable2}"`.
|
||||
fill in the template.
|
||||
|
||||
For example, if the template is `'{variable1} {variable2}'`, and
|
||||
`partial_variables` is `{"variable1": "foo"}`, then the final prompt
|
||||
will be `'foo {variable2}'`.
|
||||
**kwargs: Any other arguments to pass to the prompt template.
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""BasePrompt schema definition."""
|
||||
"""`BasePrompt` schema definition."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -33,14 +33,16 @@ PromptTemplateFormat = Literal["f-string", "mustache", "jinja2"]
|
||||
def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
|
||||
"""Format a template using jinja2.
|
||||
|
||||
*Security warning*:
|
||||
As of LangChain 0.0.329, this method uses Jinja2's
|
||||
SandboxedEnvironment by default. However, this sand-boxing should
|
||||
be treated as a best-effort approach rather than a guarantee of security.
|
||||
!!! warning "Security"
|
||||
|
||||
As of LangChain 0.0.329, this method uses Jinja2's `SandboxedEnvironment` by
|
||||
default. However, this sandboxing should be treated as a best-effort approach
|
||||
rather than a guarantee of security.
|
||||
|
||||
Do not accept jinja2 templates from untrusted sources as they may lead
|
||||
to arbitrary Python code execution.
|
||||
|
||||
https://jinja.palletsprojects.com/en/3.1.x/sandbox/
|
||||
[More information.](https://jinja.palletsprojects.com/en/3.1.x/sandbox/)
|
||||
|
||||
Args:
|
||||
template: The template string.
|
||||
@@ -123,14 +125,14 @@ def mustache_template_vars(
|
||||
) -> set[str]:
|
||||
"""Get the top-level variables from a mustache template.
|
||||
|
||||
For nested variables like `{{person.name}}`, only the top-level
|
||||
key (`person`) is returned.
|
||||
For nested variables like `{{person.name}}`, only the top-level key (`person`) is
|
||||
returned.
|
||||
|
||||
Args:
|
||||
template: The template string.
|
||||
|
||||
Returns:
|
||||
The top-level variables from the template.
|
||||
The top-level variables from the template.
|
||||
"""
|
||||
variables: set[str] = set()
|
||||
section_depth = 0
|
||||
@@ -222,7 +224,9 @@ def check_valid_template(
|
||||
|
||||
Args:
|
||||
template: The template string.
|
||||
template_format: The template format. Should be one of "f-string" or "jinja2".
|
||||
template_format: The template format.
|
||||
|
||||
Should be one of `'f-string'` or `'jinja2'`.
|
||||
input_variables: The input variables.
|
||||
|
||||
Raises:
|
||||
@@ -252,7 +256,9 @@ def get_template_variables(template: str, template_format: str) -> list[str]:
|
||||
|
||||
Args:
|
||||
template: The template string.
|
||||
template_format: The template format. Should be one of "f-string" or "jinja2".
|
||||
template_format: The template format.
|
||||
|
||||
Should be one of `'f-string'` or `'jinja2'`.
|
||||
|
||||
Returns:
|
||||
The variables from the template.
|
||||
@@ -366,7 +372,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
|
||||
|
||||
|
||||
def is_subsequence(child: Sequence, parent: Sequence) -> bool:
|
||||
"""Return True if child is subsequence of parent."""
|
||||
"""Return `True` if child is subsequence of parent."""
|
||||
if len(child) == 0 or len(parent) == 0:
|
||||
return False
|
||||
if len(parent) < len(child):
|
||||
|
||||
@@ -30,6 +30,7 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
|
||||
schema_: dict | type
|
||||
"""Schema for the structured prompt."""
|
||||
|
||||
structured_output_kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
def __init__(
|
||||
@@ -44,13 +45,13 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
"""Create a structured prompt template.
|
||||
|
||||
Args:
|
||||
messages: sequence of messages.
|
||||
schema_: schema for the structured prompt.
|
||||
structured_output_kwargs: additional kwargs for structured output.
|
||||
template_format: template format for the prompt.
|
||||
messages: Sequence of messages.
|
||||
schema_: Schema for the structured prompt.
|
||||
structured_output_kwargs: Additional kwargs for structured output.
|
||||
template_format: Template format for the prompt.
|
||||
|
||||
Raises:
|
||||
ValueError: if schema is not provided.
|
||||
ValueError: If schema is not provided.
|
||||
"""
|
||||
schema_ = schema_ or kwargs.pop("schema", None)
|
||||
if not schema_:
|
||||
@@ -74,8 +75,8 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
def get_lc_namespace(cls) -> list[str]:
|
||||
"""Get the namespace of the LangChain object.
|
||||
|
||||
For example, if the class is `langchain.llms.openai.OpenAI`, then the
|
||||
namespace is `["langchain", "llms", "openai"]`
|
||||
For example, if the class is `langchain.llms.openai.OpenAI`, then the namespace
|
||||
is `["langchain", "llms", "openai"]`
|
||||
|
||||
Returns:
|
||||
The namespace of the LangChain object.
|
||||
@@ -112,6 +113,7 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
OutputSchema,
|
||||
)
|
||||
```
|
||||
|
||||
Args:
|
||||
messages: Sequence of message representations.
|
||||
|
||||
@@ -160,11 +162,11 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
name: The name of the pipeline.
|
||||
|
||||
Returns:
|
||||
A RunnableSequence object.
|
||||
A `RunnableSequence` object.
|
||||
|
||||
Raises:
|
||||
NotImplementedError: If the first element of `others`
|
||||
is not a language model.
|
||||
NotImplementedError: If the first element of `others` is not a language
|
||||
model.
|
||||
"""
|
||||
if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
|
||||
others[0], "with_structured_output"
|
||||
|
||||
Reference in New Issue
Block a user