mirror of
https://github.com/hwchase17/langchain.git
synced 2025-07-06 13:18:12 +00:00
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>
This commit is contained in:
parent
e8d46bdd9b
commit
75fe9d3555
@ -74,6 +74,16 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
|||||||
prompt = PromptTemplate.from_template(template)
|
prompt = PromptTemplate.from_template(template)
|
||||||
return cls(prompt=prompt, **kwargs)
|
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
|
@abstractmethod
|
||||||
def format(self, **kwargs: Any) -> BaseMessage:
|
def format(self, **kwargs: Any) -> BaseMessage:
|
||||||
"""To a BaseMessage."""
|
"""To a BaseMessage."""
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
from pathlib import Path
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from langchain.prompts import PromptTemplate
|
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
|
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:
|
def test_chat_prompt_template() -> None:
|
||||||
"""Test chat prompt template."""
|
"""Test chat prompt template."""
|
||||||
prompt_template = create_chat_prompt_template()
|
prompt_template = create_chat_prompt_template()
|
||||||
|
Loading…
Reference in New Issue
Block a user