From 8a5ec894e7cbca6a47afd195cce2a0e3c75e052b Mon Sep 17 00:00:00 2001 From: Edmar Ferreira Date: Sun, 13 Nov 2022 18:15:30 -0300 Subject: [PATCH] Prompt from file proof of concept using plain text (#127) This is a simple proof of concept of using external files as templates. I'm still feeling my way around the codebase. As a user, I want to use files as prompts, so it will be easier to manage and test prompts. The future direction is to use a template engine, most likely Mako. --- langchain/prompts/prompt.py | 15 +++++++++++++++ tests/unit_tests/data/prompt_file.txt | 2 ++ tests/unit_tests/test_prompt.py | 8 ++++++++ 3 files changed, 25 insertions(+) create mode 100644 tests/unit_tests/data/prompt_file.txt diff --git a/langchain/prompts/prompt.py b/langchain/prompts/prompt.py index 02f87b77003..b84b7718149 100644 --- a/langchain/prompts/prompt.py +++ b/langchain/prompts/prompt.py @@ -97,3 +97,18 @@ class Prompt(BaseModel, BasePrompt): example_str = example_separator.join(examples) template = prefix + example_str + suffix return cls(input_variables=input_variables, template=template) + + @classmethod + def from_file(cls, template_file: str, input_variables: List[str]) -> "Prompt": + """Load a prompt from a file. + + Args: + 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. + """ + with open(template_file, "r") as f: + template = f.read() + return cls(input_variables=input_variables, template=template) diff --git a/tests/unit_tests/data/prompt_file.txt b/tests/unit_tests/data/prompt_file.txt new file mode 100644 index 00000000000..0681c36f48e --- /dev/null +++ b/tests/unit_tests/data/prompt_file.txt @@ -0,0 +1,2 @@ +Question: {question} +Answer: \ No newline at end of file diff --git a/tests/unit_tests/test_prompt.py b/tests/unit_tests/test_prompt.py index 45040793626..80a7fca4a75 100644 --- a/tests/unit_tests/test_prompt.py +++ b/tests/unit_tests/test_prompt.py @@ -77,3 +77,11 @@ def test_prompt_invalid_template_format() -> None: Prompt( input_variables=input_variables, template=template, template_format="bar" ) + + +def test_prompt_from_file() -> None: + """Test prompt can be successfully constructed from a file.""" + template_file = "tests/unit_tests/data/prompt_file.txt" + input_variables = ["question"] + prompt = Prompt.from_file(template_file, input_variables) + assert prompt.template == "Question: {question}\nAnswer:"