langchain icon indicating copy to clipboard operation
langchain copied to clipboard

Automatically detect input_variables from PromptTemplate string

Open adivekar-utexas opened this issue 1 year ago • 1 comments

Feature request

If input_variables is not passed, try to detect them automatically as those which are surrounded by curly braces:

E.g.

prompt_template = PromptTemplate(template="What is the price of {product_name}?")  ## Automatically detects the input_variables to be ['product_name']

Motivation

This has been bugging me for a while and makes it more cumbersome.

Your contribution

You can use the code mentioned below, it's literally that simple (at least for f-strings).

I can submit a PR.

def str_format_args(x: str, named_only: bool = True) -> List[str]:
    ## Ref: https://stackoverflow.com/a/46161774/4900327
    args: List[str] = [
        str(tup[1]) for tup in string.Formatter().parse(x)
        if tup[1] is not None
    ]
    if named_only:
        args: List[str] = [
            arg for arg in args
            if not arg.isdigit() and len(arg) > 0
        ]
    return args


str_format_args("What is the price of {product_name}?")  ## Returns ['product_name']

adivekar-utexas avatar May 31 '23 15:05 adivekar-utexas

PromptTemplate.from_template already does this example code:

from langchain.prompts import PromptTemplate

assert PromptTemplate.from_template("What is the price of {product_name}?") == PromptTemplate(
    input_variables=['product_name'],
    template="What is the price of {product_name}?"
) 

Nahdus avatar Jun 03 '23 06:06 Nahdus

Hi, @adivekar-utexas! I'm Dosu, and I'm here to help the LangChain team manage their backlog. I wanted to let you know that we are marking this issue as stale.

From what I understand, this issue is a feature request to automatically detect input variables from a prompt template string. User "Nahdus" pointed out that the PromptTemplate.from_template function already does this and provided an example code snippet. User "KeshavSingh29" confirmed this solution with a thumbs up reaction.

Before we close this issue, we wanted to check with you if it is still relevant to the latest version of the LangChain repository. If it is, please let us know by commenting on the issue. Otherwise, feel free to close the issue yourself or it will be automatically closed in 7 days.

Thank you for your contribution to LangChain!

dosubot[bot] avatar Sep 11 '23 16:09 dosubot[bot]