Prompt Templates and Variables

Introduction and Context Setting

Welcome to the lesson on Prompt Structure and Variables. In this lesson, we will explore how prompts are structured and how variables are used to create dynamic and flexible AI interactions. Prompts are essential in guiding AI behavior, allowing us to tailor responses to specific needs. By the end of this lesson, you will understand how to load and render templates using variables — a crucial skill in building the AI Cooking Helper.

Recall: Basics of File Handling in Python

Before we dive into templates, let's briefly recall file handling in Python. This knowledge is essential, as we will be loading template files in this lesson. In Python, the open() function is used to open a file, and the read() method is used to read its contents. Here's a quick reminder:

file_path = 'example.txt'
with open(file_path, 'r') as file:
    content = file.read()
print(content)

This code snippet opens a file named example.txt, reads its contents, and prints them. The with statement ensures the file is closed automatically after reading.

Understanding Template Structure

Our templates will represent prompts that can be enriched with variables, in the form of text files with placeholders. These placeholders are enclosed in double curly braces, like {{variable_name}}, where variable_name can be any custom name you choose. This allows you to create flexible templates that can be reused with different values.

For example, consider the following template:

Rewrite the following sentence in a different way that retains its original meaning:

Original: {{sentence}}

Return a list of up to {{max_versions}} paraphrased versions as plain text strings.

In this template, {{sentence}} and {{max_versions}} are placeholders. When rendering the template, you can provide any values for these variables, making the prompt adaptable to different situations.

Loading Templates with `load_template`

To use a template, we first need to load it from a file. Let's break down the load_template function:

import os

def load_template(template_name):
    base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    prompts_dir = os.path.join(base_dir, 'static', 'prompts')
    file_path = os.path.join(prompts_dir, f"{template_name}.txt")
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()
  • base_dir is set to the absolute path of the parent directory of the current script.
  • prompts_dir points to the folder where prompt templates are stored.
  • file_path is constructed by joining prompts_dir with the template filename (using f"{template_name}.txt"), resulting in the full path to the desired template file.
  • The file is opened, and its contents are read and returned as a string.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal