Template

Template

We use Mustache template (opens in a new tab) to define a prompt template. This allows you to reuse the same prompt with different inputs.

For instance, a template with one variable name:

Say hello to {{ name }} in a cheerful way.

When using this template the value for the variable name must be provided. Using name equal BitCat the rendered template is:

Say hello to BitCat in a cheerful way.

After the AI processes the template we have a personalized response for this variable:

Hello, BitCat! 🐱 Wishing you a purr-fectly delightful day filled with whiskers and happiness!

📝 How to use

To access a template use the Promptd instance:

const promptd = new Promptd({ apiKey: promptdApiKey });
const template = promptd.template(promptSlug);

When instantiating your template access, it is possible to set optional arguments:

const gpt4o = new OpenAIChatApi({ apiKey: openAiKey }, { model: 'gpt-4o' });
const promptd = new Promptd({ apiKey: promptdApiKey });
const run = await promptd.startRun({ name: 'Script say hello' });
const template = promptd.template(promptSlug, {
  lazy: false,
  revalidate: 300,
  ai: gpt4o,
  runId: run.id,
});

Where:

  • lazy: If the value is true, the template will be fetched only when render() is called. Otherwise, it will be fetched immediately so it's available as soon you call render() for that prompt.
  • revalidate: The number of seconds to cache the template for. If not set, it defaults to 5 minutes. Set to false to disable caching.
  • ai: The AI to use for completion. If not set, calling generate() will throw an error.
  • runId: The ID of the run instance to associate with this template instance. When the template instance is created by a run instance, calling run.generate() will have the run ID automatically set.

Calling promptd.template() will return a Template instance that can be used to take some actions:

  • render(): Render the template variables and return an instance of Prompt that is used to process the prompt.
  • toString(): Returns the template as a string.
  • setRunId(): Used to assign this template instance to a specific run instance. It is useful before processing the prompt because setting the run ID will create prompt events assigned to the current execution.

It is important to note that setting the run ID used on the current template instance is not mandatory, but it is recommended. It can be helpful to track executions.

There are two ways to set the run ID:

  • Using the optional arguments when instantiating the template:
const promptd = new Promptd({ apiKey: promptdApiKey });
const run = await promptd.startRun({ name: 'Script say hello' });
const template = promptd.template(promptSlug, { runId: run.id });
  • By explicitly calling the method setRunId():
const promptd = new Promptd({ apiKey: promptdApiKey });
const run = await promptd.startRun({ name: 'Script say hello' });
const template = promptd.template(promptSlug);
template.setRunId(run.id);