Performance: PromptTemplate basics
This affects how quickly prompts are generated and sent to language models, impacting response time and user experience.
Jump into concepts and practice - no test required
from langchain import PromptTemplate prompt = PromptTemplate(input_variables=['name', 'age'], template='Hello {name}, you are {age} years old.') # Reuse the same template object for all queries for user in users: result = prompt.format(name=user.name, age=user.age)
from langchain import PromptTemplate prompt = PromptTemplate(input_variables=['name', 'age'], template='Hello {name}, you are {age} years old.') # Re-creating the template inside a loop for each query for user in users: prompt = PromptTemplate(input_variables=['name', 'age'], template='Hello {name}, you are {age} years old.') result = prompt.format(name=user.name, age=user.age)
| Pattern | CPU Usage | Memory Usage | Response Delay | Verdict |
|---|---|---|---|---|
| Recreating PromptTemplate per query | High (parsing each time) | Higher (new objects) | Longer (blocks formatting) | [X] Bad |
| Reusing single PromptTemplate | Low (one-time parse) | Lower (single object) | Shorter (fast formatting) | [OK] Good |
PromptTemplate in langchain?PromptTemplate with a placeholder named name?from langchain.prompts import PromptTemplate
prompt = PromptTemplate.from_template("Hello, {name}!")
result = prompt.format(name="Alice")
print(result)from langchain.prompts import PromptTemplate
prompt = PromptTemplate.from_template("Hi, {user}!")
result = prompt.format(name="Bob")
print(result)PromptTemplate that asks for a user's name and age, then formats a greeting. Which code correctly defines and uses this template?