langchain
langchain copied to clipboard
Automatically detect input_variables from PromptTemplate string
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']
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}?"
)
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!