使用 Dotprompt 管理提示

Firebase Genkit 提供 Dotprompt 外掛程式和文字格式,可協助你編寫 及整理生成式 AI 提示

Dotprompt 的設計宗旨是提示。您編寫 會將提示維持在特殊格式的檔案,稱為 dotprompt 檔案,追蹤 您可以使用 也可以與呼叫生成式 AI 的程式碼一起部署 我們來看評估分類模型成效時 的喚回度和精確度指標

如要使用 Dotprompt,請先在專案根目錄中建立 prompts 目錄,並 然後在該目錄中建立 .prompt 檔案這裡舉了一個簡單的例子 可能會呼叫 greeting.prompt

---
model: vertexai/gemini-1.5-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}}.

如要使用這則提示,請按照下列步驟操作:

Go

安裝 dotprompt 外掛程式:

go get github.com/firebase/genkit/go/plugins/dotprompt

然後使用 Open 載入提示:

import "github.com/firebase/genkit/go/plugins/dotprompt"
dotprompt.SetDirectory("prompts")
prompt, err := dotprompt.Open("greeting")

您可以呼叫提示的 Generate 方法,以算繪範本並傳送 通往模型 API

ctx := context.Background()

// The .prompt file specifies vertexai/gemini-1.5-pro, so make sure it's set
// up.
// Default to the project in GCLOUD_PROJECT and the location "us-central1".
vertexai.Init(ctx, nil)
vertexai.DefineModel("gemini-1.5-pro", nil)

type GreetingPromptInput struct {
  Location string `json:"location"`
  Style    string `json:"style"`
  Name     string `json:"name"`
}
response, err := prompt.Generate(
  ctx,
  &dotprompt.PromptRequest{
      Variables: GreetingPromptInput{
          Location: "the beach",
          Style:    "a fancy pirate",
          Name:     "Ed",
      },
  },
  nil,
)
if err != nil {
  return err
}

if responseText, err := response.Text(); err == nil {
  fmt.Println(responseText)
}

或是直接將範本轉譯為字串:

Go

renderedPrompt, err := prompt.RenderText(map[string]any{
  "location": "a restaurant",
  "style":    "a pirate",
})

點號的語法以處理常式為基礎 範本語言您可以使用 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
  extra?: any, arbitrary extra data
  (*): string, wildcard field

上述結構定義相當於下列 JSON 結構定義:

{
  "properties": {
    "metadata": {
      "properties": {
        "updatedAt": {
          "type": "string",
          "description": "ISO timestamp of last update"
        },
        "approvedBy": {
          "type": "integer",
          "description": "id of approver"
        }
      },
      "type": "object"
    },
    "title": {
      "type": "string"
    },
    "subtitle": {
      "type": "string"
    },
    "draft": {
      "type": "boolean",
      "description": "true when in draft state"
    },
    "date": {
      "type": "string",
      "description": "the date of publication e.g. '2024-04-09'"
    },
    "tags": {
      "items": {
        "type": "string"
      },
      "type": "array",
      "description": "relevant tags for article"
    },
    "authors": {
      "items": {
        "properties": {
          "name": {
            "type": "string"
          },
          "email": {
            "type": "string"
          }
        },
        "type": "object",
        "required": ["name"]
      },
      "type": "array"
    }
  },
  "type": "object",
  "required": ["title", "date", "tags", "authors"]
}

Picoschema 支援純量類型 stringintegernumberbooleanany。 如果是物件、陣列和列舉,欄位名稱後面會以括號表示。

Picoschema 定義的物件包含所有必要屬性,除非另有註明 ,且不允許其他屬性。?屬性標示為選用時 也能讓 LLM 傳回空值 省略欄位。

在物件定義中,您可以使用特殊鍵 (*) 宣告「萬用字元」 欄位定義。這將與 明確金鑰。

Picoschema 不支援完整 JSON 結構定義的許多功能。如果發生以下情況: 如需更完整的結構定義,您可以改為提供 JSON 結構定義:

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

覆寫提示中繼資料

雖然 .prompt 檔案可讓您將模型設定等中繼資料嵌入 檔案本身,您也可以在每次呼叫上覆寫這些值:

Go

// Make sure you set up the model you're using.
vertexai.DefineModel("gemini-1.5-flash", nil)

response, err := prompt.Generate(
  context.Background(),
  &dotprompt.PromptRequest{
      Variables: GreetingPromptInput{
          Location: "the beach",
          Style:    "a fancy pirate",
          Name:     "Ed",
      },
      Model: "vertexai/gemini-1.5-flash",
      Config: &ai.GenerationCommonConfig{
          Temperature: 1.0,
      },
  },
  nil,
)

多重訊息提示

根據預設,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圖片 。在程式碼中,這會是:

Go

dotprompt.SetDirectory("prompts")
describeImagePrompt, err := dotprompt.Open("describe_image")
if err != nil {
  return err
}

imageBytes, err := os.ReadFile("img.jpg")
if err != nil {
  return err
}
encodedImage := base64.StdEncoding.EncodeToString(imageBytes)
dataURI := "data:image/jpeg;base64," + encodedImage

type DescribeImagePromptInput struct {
  PhotoUrl string `json:"photo_url"`
}
response, err := describeImagePrompt.Generate(
  context.Background(),
  &dotprompt.PromptRequest{Variables: DescribeImagePromptInput{
      PhotoUrl: dataURI,
  }},
  nil,
)

提示變化版本

由於提示檔案只有文字,您可以 (也應該) 提交 版本管控系統,方便您比較不同時期的變更。 修改過的提示通常只能在 實際工作環境和現有版本。Dotprompt 支援 透過變化版本功能達成這個目標

如要建立變化版本,請建立 [name].[variant].prompt 檔案。舉例來說 您是否在提示中使用 Gemini 1.0 Pro,但想瞭解 Gemini 1.5 Pro 建議您製作兩個檔案:

  • my_prompt.prompt:「基準」提示
  • my_prompt.gemini15.prompt:名為「gemini」的變化版本

如要使用提示變化版本,請在載入時指定變化版本:

Go

describeImagePrompt, err := dotprompt.OpenVariant("describe_image", "gemini15")

提示載入器會嘗試載入該名稱的變化版本 就會加入基準。也就是說,您可以使用以條件式載入 選擇適合你的應用程式

Go

var myPrompt *dotprompt.Prompt
var err error
if isBetaTester(user) {
  myPrompt, err = dotprompt.OpenVariant("describe_image", "gemini15")
} else {
  myPrompt, err = dotprompt.Open("describe_image")
}

產生追蹤記錄的中繼資料會包含變化版本名稱,因此 可以比較 Genkit 追蹤記錄中各變化版本的實際成效 檢查工具