langchain.prompts.prompt.PromptTemplate¶
- class langchain.prompts.prompt.PromptTemplate(*, input_variables: List[str], output_parser: Optional[BaseOutputParser] = None, partial_variables: Mapping[str, Union[str, Callable[[], str]]] = None, template: str, template_format: str = 'f-string', validate_template: bool = True)[source]¶
Bases:
StringPromptTemplateA prompt template for a language model.
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) or jinja2 syntax.
Example
from langchain import PromptTemplate # Instantiation using from_template (recommended) prompt = PromptTemplate.from_template("Say {foo}") prompt.format(foo="bar") # Instantiation using initializer prompt = PromptTemplate(input_variables=["foo"], template="Say {foo}")
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
- param input_variables: List[str] [Required]¶
A list of the names of the variables the prompt template expects.
- param output_parser: Optional[BaseOutputParser] = None¶
How to parse the output of calling an LLM on this formatted prompt.
- param partial_variables: Mapping[str, Union[str, Callable[[], str]]] [Optional]¶
- param template: str [Required]¶
The prompt template.
- param template_format: str = 'f-string'¶
The format of the prompt template. Options are: ‘f-string’, ‘jinja2’.
- param validate_template: bool = True¶
Whether or not to try validating the template.
- dict(**kwargs: Any) Dict¶
Return dictionary representation of prompt.
- format(**kwargs: Any) str[source]¶
Format the prompt with the inputs.
- Parameters
kwargs – Any arguments to be passed to the prompt template.
- Returns
A formatted string.
Example
prompt.format(variable1="foo")
- format_prompt(**kwargs: Any) PromptValue¶
Create Chat Messages.
- classmethod from_examples(examples: List[str], suffix: str, input_variables: List[str], example_separator: str = '\n\n', prefix: str = '', **kwargs: Any) PromptTemplate[source]¶
Take examples in list format with prefix and suffix to create a prompt.
Intended to be used as a way to dynamically create a prompt from examples.
- Parameters
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. Default to an empty string.
- Returns
The final prompt generated.
- classmethod from_file(template_file: Union[str, Path], input_variables: List[str], **kwargs: Any) PromptTemplate[source]¶
Load a prompt from a file.
- Parameters
template_file – The path to the file containing the prompt template.
input_variables – A list of variable names the final prompt template will expect.
- Returns
The prompt loaded from the file.
- classmethod from_template(template: str, *, template_format: str = 'f-string', partial_variables: Optional[Dict[str, Any]] = None, **kwargs: Any) PromptTemplate[source]¶
Load a prompt template from a template.
- Parameters
template – The template to load.
template_format – The format of the template. Use jinja2 for jinja2, and f-string or None 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}”.
- Returns
The prompt template loaded from the template.
- invoke(input: Dict, config: langchain.schema.runnable.RunnableConfig | None = None) PromptValue¶
- partial(**kwargs: Union[str, Callable[[], str]]) BasePromptTemplate¶
Return a partial of the prompt template.
- save(file_path: Union[Path, str]) None¶
Save the prompt.
- Parameters
file_path – Path to directory to save prompt to.
Example: .. code-block:: python
prompt.save(file_path=”path/prompt.yaml”)
- validator template_is_valid » all fields[source]¶
Check that template and input variables are consistent.
- to_json() Union[SerializedConstructor, SerializedNotImplemented]¶
- to_json_not_implemented() SerializedNotImplemented¶
- validator validate_variable_names » all fields¶
Validate variable names do not include restricted names.
- property lc_attributes: Dict[str, Any]¶
Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor.
- property lc_namespace: List[str]¶
Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”]
- property lc_secrets: Dict[str, str]¶
Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”}
- property lc_serializable: bool¶
Return whether or not the class is serializable.