使用 Dotprompt 管理提示

Firebase Genkit 提供 Dotprompt 插件和文本格式,可帮助您编写和整理生成式 AI 提示。

Dotprompt 在设计时遵循了提示就是代码这一前提。您可以在采用特殊格式的文件(称为 dotprompt 文件)中编写和维护提示,使用用于代码的同一版本控制系统跟踪对提示的更改,并将提示与调用生成式 AI 模型的代码一起进行部署。

如需使用 Dotprompt,请先在项目根目录中创建一个 prompts 目录,然后在该目录中创建一个 .prompt 文件。下面是一个简单的示例,您可以调用 greeting.prompt

---
model: vertexai/gemini-1.0-pro
config:
  temperature: 0.9
input:
  schema:
    location: string
    style?: string
    name?: string
  default:
    location: a restaurant
---

You are the world's most welcoming AI assistant and are currently working at {{location}}.

Greet a guest{{#if name}} named {{name}}{{/if}}{{#if style}} in the style of {{style}}{{/if}}.

如需使用此提示,请安装 dotprompt 插件,并从 @genkit-ai/dotprompt 库导入 prompt 函数:

import { dotprompt, prompt } from '@genkit-ai/dotprompt';

configureGenkit({ plugins: [dotprompt()] });

然后,使用 prompt('file_name') 加载提示:

const greetingPrompt = await prompt('greeting');

const result = await greetingPrompt.generate({
  input: {
    location: 'the beach',
    style: 'a fancy pirate',
  },
});

console.log(result.text());

Dotprompt 的语法基于 Handlebars 模板语言。您可以使用 ifunlesseach 帮助程序向提示添加条件部分或迭代结构化内容。该文件格式利用 YAML 前置矩阵为内嵌模板的提示提供元数据。

使用 Picoschema 定义输入/输出架构

Dotprompt 包含一种针对 YAML 优化的紧凑架构定义格式,名为 Picoschema,可让您轻松为 LLM 应用定义最重要的架构属性。下面是报道的架构示例:

schema:
  title: string # string, number, and boolean types are defined like this
  subtitle?: string # optional fields are marked with a `?`
  draft?: boolean, true when in draft state
  status?(enum, approval status): [PENDING, APPROVED]
  date: string, the date of publication e.g. '2024-04-09' # descriptions follow a comma
  tags(array, relevant tags for article): string # arrays are denoted via parentheses
  authors(array):
    name: string
    email?: string
  metadata?(object): # objects are also denoted via parentheses
    updatedAt?: string, ISO timestamp of last update
    approvedBy?: integer, id of approver

上述架构等同于以下 TypeScript 接口:

interface Article {
  title: string;
  subtitle?: string;
  /** true when in draft state */
  draft?: boolean;
  /** approval status */
  status?: 'PENDING' | 'APPROVED';
  /** the date of publication e.g. '2024-04-09' */
  date: string;
  /** relevant tags for article */
  tags: string[];
  authors: {
    name: string;
    email?: string;
  }[];
  metadata?: {
    /** ISO timestamp of last update */
    updatedAt?: string;
    /** id of approver */
    approvedBy?: number;
  };
}

Picoschema 支持标量类型 stringintegernumberboolean。对于对象、数组和枚举,它们在字段名称后面用括号表示。

由 Picoschema 定义的对象具有所有必需属性,除非由 ? 表示为可选属性,并且不允许添加其他属性。

Picoschema 不支持完整 JSON 架构的许多功能。如果您需要更强大的架构,可以改为提供 JSON 架构:

output:
  schema:
    type: object
    properties:
      field1:
        type: number
        minimum: 20

替换提示元数据

虽然 .prompt 文件允许您在文件本身中嵌入元数据(例如模型配置),但您也可以按调用替换这些值:

const result = await greetingPrompt.generate({
  model: 'google-genai/gemini-pro',
  config: {
    temperature: 1.0,
  },
  input: {
    location: 'the beach',
    style: 'a fancy pirate',
  },
});

结构化输出

您可以将提示的格式和输出架构强制转换为 JSON:

---
model: vertexai/gemini-1.0-pro
input:
  schema:
    theme: string
output:
  format: json
  schema:
    name: string
    price: integer
    ingredients(array): string
---

Generate a menu item that could be found at a {{theme}} themed restaurant.

使用结构化输出生成提示时,请使用 output() 帮助程序检索并验证该提示:

const createMenuPrompt = await prompt('create_menu');

const menu = await createMenuPrompt.generate({
  input: {
    theme: 'banana',
  },
});

console.log(menu.output());

多消息提示

默认情况下,Dotprompt 会构造一条具有 "user" 角色的消息。某些提示最好由多条消息的组合表示,例如系统提示。

{{role}} 帮助程序提供了一种构造多消息提示的简单方法:

---
model: vertexai/gemini-1.0-pro
input:
  schema:
    userQuestion: string
---

{{role "system"}}
You are a helpful AI assistant that really loves to talk about food. Try to work
food items into all of your conversations.
{{role "user"}}
{{userQuestion}}

多模态提示

对于支持多模态输入(例如图片和文字)的模型,您可以使用 {{media}} 辅助程序:

---
model: vertexai/gemini-1.0-pro-vision
input:
  schema:
    photoUrl: string
---

Describe this image in a detailed paragraph:

{{media url=photoUrl}}

该网址可以是用于“内嵌”图片用途的 https:// 或 base64 编码的 data: URI。代码如下所示:

const describeImagePrompt = await prompt('describe_image');

const result = await describeImagePrompt.generate({
  input: {
    photoUrl: 'https://example.com/image.png',
  },
});

console.log(result.text());

提示变体

由于提示文件只是文本,您可以(并且应该!)将其提交到您的版本控制系统,从而轻松比较一段时间内的更改。很多时候,调整后的提示版本只能在现有版本与生产环境中并行进行全面测试。Dotprompt 通过其变体功能支持此功能。

如需创建变体,请创建 [name].[variant].prompt 文件。例如,如果您在提示中使用了 Gemini 1.0 Pro,但想要看看 Gemini 1.5 Pro 是否会更好,您可以创建两个文件:

  • my_prompt.prompt:“baseline”提示
  • my_prompt.gemini15.prompt:名为“gemini”的变体

如需使用提示变体,请在加载时指定 variant 选项:

const myPrompt = await prompt('my_prompt', { variant: 'gemini15' });

提示加载器将尝试加载该名称的变体,如果不存在此类变体,则会回退到基准。这意味着,您可以根据对您的应用有意义的任何条件使用条件加载:

const myPrompt = await prompt('my_prompt', {
  variant: isBetaTester(user) ? 'gemini15' : null,
});

变体的名称包含在生成轨迹的元数据中,因此您可以在 Genkit 轨迹检查器中比较和对比变体之间的实际性能。

加载和定义提示的其他方法

Dotprompt 针对提示目录中的组织进行了优化。不过,还有其他一些方法可以加载和定义提示:

  • loadPromptFile:从提示目录中的文件加载提示。
  • loadPromptUrl:从网址加载提示。
  • defineDotprompt:在代码中定义提示。

示例:

import {
  loadPromptFile,
  loadPromptUrl,
  defineDotprompt,
} from '@genkit-ai/dotprompt';
import path from 'path';
import { z } from 'zod';

// Load a prompt from a file
const myPrompt = await loadPromptFile(
  path.resolve(__dirname, './path/to/my_prompt.prompt')
);

// Load a prompt from a URL
const myPrompt = await loadPromptUrl('https://example.com/my_prompt.prompt');

// Define a prompt in code
const myPrompt = defineDotprompt(
  {
    model: 'vertexai/gemini-1.0-pro',
    input: {
      schema: z.object({
        name: z.string(),
      }),
    },
  },
  `Hello {{name}}, how are you today?`
);