"""提示模式定义。"""
from __future__ import annotations
import warnings
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Union
from langchain_core.prompts.string import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
get_template_variables,
mustache_schema,
)
from langchain_core.pydantic_v1 import BaseModel, root_validator
from langchain_core.runnables.config import RunnableConfig
[docs]class PromptTemplate(StringPromptTemplate):
"""语言模型的提示模板。
提示模板由一个字符串模板组成。它接受用户的一组参数,这些参数可以用来生成语言模型的提示。
该模板可以使用f-strings(默认)或jinja2语法进行格式化。
*安全警告*:建议使用`template_format="f-string"`,而不是`template_format="jinja2"`,或者确保绝对不要接受来自不受信任来源的jinja2模板,因为它们可能导致任意Python代码执行。
截至LangChain 0.0.329版本,Jinja2模板将默认使用Jinja2的SandboxedEnvironment进行渲染。这种沙盒化应被视为一种尽力而为的方法,而不是安全性的保证,因为这是一种默认启用而非默认禁用的方法。
尽管进行了沙盒化,我们仍建议绝对不要使用来自不受信任来源的jinja2模板。
示例:
.. code-block:: python
from langchain_core.prompts import PromptTemplate
# 使用from_template进行实例化(推荐)
prompt = PromptTemplate.from_template("Say {foo}")
prompt.format(foo="bar")
# 使用初始化器进行实例化
prompt = PromptTemplate(input_variables=["foo"], template="Say {foo}")
"""
@property
def lc_attributes(self) -> Dict[str, Any]:
return {
"template_format": self.template_format,
}
[docs] @classmethod
def get_lc_namespace(cls) -> List[str]:
"""获取langchain对象的命名空间。"""
return ["langchain", "prompts", "prompt"]
input_variables: List[str]
"""提示模板期望的变量名称列表。"""
template: str
"""这是提示模板。"""
template_format: Literal["f-string", "mustache", "jinja2"] = "f-string"
"""提示模板的格式。
选项包括:'f-string','mustache','jinja2'。"""
validate_template: bool = False
"""是否尝试验证模板。"""
def __add__(self, other: Any) -> PromptTemplate:
"""重写+运算符以允许组合提示模板。"""
# Allow for easy combining
if isinstance(other, PromptTemplate):
if self.template_format != "f-string":
raise ValueError(
"Adding prompt templates only supported for f-strings."
)
if other.template_format != "f-string":
raise ValueError(
"Adding prompt templates only supported for f-strings."
)
input_variables = list(
set(self.input_variables) | set(other.input_variables)
)
template = self.template + other.template
# If any do not want to validate, then don't
validate_template = self.validate_template and other.validate_template
partial_variables = {k: v for k, v in self.partial_variables.items()}
for k, v in other.partial_variables.items():
if k in partial_variables:
raise ValueError("Cannot have same variable partialed twice.")
else:
partial_variables[k] = v
return PromptTemplate(
template=template,
input_variables=input_variables,
partial_variables=partial_variables,
template_format="f-string",
validate_template=validate_template,
)
elif isinstance(other, str):
prompt = PromptTemplate.from_template(other)
return self + prompt
else:
raise NotImplementedError(f"Unsupported operand type for +: {type(other)}")
@property
def _prompt_type(self) -> str:
"""返回提示类型键。"""
return "prompt"
@root_validator()
def template_is_valid(cls, values: Dict) -> Dict:
"""检查模板和输入变量是否一致。"""
if values["validate_template"]:
if values["template_format"] == "mustache":
raise ValueError("Mustache templates cannot be validated.")
all_inputs = values["input_variables"] + list(values["partial_variables"])
check_valid_template(
values["template"], values["template_format"], all_inputs
)
elif values.get("template_format"):
values["input_variables"] = [
var
for var in get_template_variables(
values["template"], values["template_format"]
)
if var not in values["partial_variables"]
]
return values
[docs] @classmethod
def from_examples(
cls,
examples: List[str],
suffix: str,
input_variables: List[str],
example_separator: str = "\n\n",
prefix: str = "",
**kwargs: Any,
) -> PromptTemplate:
"""以列表格式带有前缀和后缀的示例来创建提示。
旨在作为一种从示例动态创建提示的方式使用。
参数:
examples: 用于提示的示例列表。
suffix: 示例列表后面的字符串。通常应设置用户的输入。
input_variables: 最终提示模板将期望的变量名称列表。
example_separator: 示例之间使用的分隔符。默认为两个换行符。
prefix: 任何示例之前应该出现的字符串。通常包括示例。默认为空字符串。
返回:
生成的最终提示。
"""
template = example_separator.join([prefix, *examples, suffix])
return cls(input_variables=input_variables, template=template, **kwargs)
[docs] @classmethod
def from_file(
cls,
template_file: Union[str, Path],
input_variables: Optional[List[str]] = None,
**kwargs: Any,
) -> PromptTemplate:
"""从文件中加载提示。
参数:
template_file:包含提示模板的文件路径。
input_variables:[已弃用] 最终提示模板将期望的变量名称列表。
由于from_file现在委托给from_template(),因此将忽略input_variables。
返回:
从文件加载的提示。
"""
with open(str(template_file), "r") as f:
template = f.read()
if input_variables:
warnings.warn(
"`input_variables' is deprecated and ignored.", DeprecationWarning
)
return cls.from_template(template=template, **kwargs)
[docs] @classmethod
def from_template(
cls,
template: str,
*,
template_format: str = "f-string",
partial_variables: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> PromptTemplate:
"""从模板中加载一个提示模板。
*安全警告*:建议使用`template_format="f-string"`而不是`template_format="jinja2"`,或者确保绝对不要接受来自不受信任来源的jinja2模板,因为它们可能导致任意Python代码执行。
从LangChain 0.0.329开始,默认情况下将使用Jinja2的SandboxedEnvironment来渲染Jinja2模板。这种沙盒化应该被视为一种尽力而为的方法,而不是安全保证,因为这是一种默认启用而非默认禁用的方法。
尽管进行了沙盒化,我们仍建议永远不要使用来自不受信任来源的jinja2模板。
参数:
template: 要加载的模板。
template_format: 模板的格式。使用`jinja2`表示jinja2,使用`f-string`或None表示f-strings。
partial_variables: 一个可以用来部分填充模板的变量字典。例如,如果模板是`"{variable1} {variable2}"`,而`partial_variables`是`{"variable1": "foo"}`,那么最终的提示将是`"foo {variable2}"`。
返回:
从模板加载的提示模板。
"""
input_variables = get_template_variables(template, template_format)
_partial_variables = partial_variables or {}
if _partial_variables:
input_variables = [
var for var in input_variables if var not in _partial_variables
]
return cls(
input_variables=input_variables,
template=template,
template_format=template_format, # type: ignore[arg-type]
partial_variables=_partial_variables,
**kwargs,
)