Prompt templates with f-strings
Write a prompt once, fill in the details each time.
Most AI programs send the same kind of prompt again and again with different details: summarize THIS article, explain THIS topic to THIS age. A prompt template is a string with blanks, and an f-string fills the blanks from variables. It keeps your wording the same every time, which makes results more consistent and easier to improve.
# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import anthropic
client = anthropic.Anthropic()
def explain(topic, age):
prompt = f"Explain {topic} to a {age}-year-old in three short sentences."
reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=300,
messages=[{"role": "user", "content": prompt}])
return reply.content[0].text
print(explain("rainbows", 8))
print(explain("compound interest", 16))One function, many prompts. If you find a better wording, you change it in one place.
When you paste in text from somewhere else (an article, a review, an email), wrap it in tags like <text> ... </text>. Then the model can tell your instructions apart from the text you want it to work on.
In this unit the pretend model can summarize (it returns the first sentence) or judge sentiment. It looks for your text between <text> and </text>.
A triple-quoted f-string (f""" ... """) lets a template span several lines.