Tagged template function with embedded if-else conditions and automatic dedentation to write readable strings
npm install f-stringsUse If, Else, and EndIf expressions to include conditional content.
import { f, If, Else, EndIf } from 'f-strings';
const history = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' },
];
const question = 'What is the capital of France?';
const prompt = f`
You are a helpful assistant.
${If(history.length)}
Conversation history:
${history.map((msg) => `- ${msg.role}: ${msg.content}`)}
${Else}
No conversation history.
${EndIf}
User question:
${question}
`;
console.log(message);You are a helpful assistant.
Conversation history:
- user: Hello
- assistant: Hi there!
User question:
What is the capital of France?
Strips indentation from multi-line strings.
import { f, If, EndIf } from 'f-strings';
const prompt = f`
Hello
World!
How are you?
I'm good, thank you!
`;
console.log(dedented);Hello
World!
How are you?
I'm good, thank you!
Values will be lazily evaluated, so you can use functions to generate content only when needed.
Tip
Arrays are automatically joined with newlines, so ${messages} is equivalent to ${messages.join('\n')}.
import { f, If, EndIf } from 'f-strings';
const messages = await getMessages();
const prompt = f`
${If(messages.length)}
You have ${messages.length} messages:
${() => messages.map((msg) => `- ${msg}`)}
${Else}
No messages.
${EndIf}
`;
console.log(prompt);You have 1000 messages:
- Message 1
- Message 2
...
- Message 1000
const text = f`template ${value} string`Starts a conditional block. Includes the following content if the condition is truthy.
const text = f`
${If(condition)}
content when true
${EndIf}
`;Starts an alternative block. Includes the following content if the condition is falsy.
Tip
Else can be used without calling it as a function: ${Else} or ${Else()}.
const text = f`
${If(condition)}
content when true
${Else}
content when false
${EndIf}
`;Marks the end of a conditional block. Required for every If.
Tip
EndIf can be used without calling it as a function: ${EndIf} or ${EndIf()}.
MIT