Add from_file method to message prompt template (#4713)

**Feature**: This PR adds `from_template_file` class method to
BaseStringMessagePromptTemplate. This is useful to help user to create
message prompt templates directly from template files, including
`ChatMessagePromptTemplate`, `HumanMessagePromptTemplate`,
`AIMessagePromptTemplate` & `SystemMessagePromptTemplate`.

**Tests**: Unit tests have been added in this PR.

Co-authored-by: charosen <charosen@bupt.cn>
Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
dynamic_agent_tools
charosen 1 year ago committed by GitHub
parent e8d46bdd9b
commit 75fe9d3555
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -74,6 +74,16 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt = PromptTemplate.from_template(template)
return cls(prompt=prompt, **kwargs)
@classmethod
def from_template_file(
cls: Type[MessagePromptTemplateT],
template_file: Union[str, Path],
input_variables: List[str],
**kwargs: Any,
) -> MessagePromptTemplateT:
prompt = PromptTemplate.from_file(template_file, input_variables)
return cls(prompt=prompt, **kwargs)
@abstractmethod
def format(self, **kwargs: Any) -> BaseMessage:
"""To a BaseMessage."""

@ -1,3 +1,4 @@
from pathlib import Path
from typing import List
from langchain.prompts import PromptTemplate
@ -80,6 +81,21 @@ def test_create_chat_prompt_template_from_template_partial() -> None:
assert output_prompt.prompt == expected_prompt
def test_message_prompt_template_from_template_file() -> None:
expected = ChatMessagePromptTemplate(
prompt=PromptTemplate(
template="Question: {question}\nAnswer:", input_variables=["question"]
),
role="human",
)
actual = ChatMessagePromptTemplate.from_template_file(
Path(__file__).parent.parent / "data" / "prompt_file.txt",
["question"],
role="human",
)
assert expected == actual
def test_chat_prompt_template() -> None:
"""Test chat prompt template."""
prompt_template = create_chat_prompt_template()

Loading…
Cancel
Save