Prompts

The Opik TypeScript SDK provides comprehensive prompt management functionality for versioning, storing, and formatting your LLM prompt templates. Prompts in Opik are versioned automatically, allowing you to track changes over time while seamlessly integrating with your codebase.

Introduction

Opik supports two types of prompts:

  • Text Prompts: Simple string templates for single-turn interactions
  • Chat Prompts: Structured message-based templates for conversational AI with support for multimodal content (text, images, videos)

Each prompt:

  • Has a unique name and auto-generated versions
  • Supports Mustache or Jinja2 template syntax
  • Tracks metadata, tags, and change descriptions
  • Maintains complete version history
  • Enables version comparison and rollback

Getting Started

This section covers text prompts. For chat prompts with structured messages, see the Chat Prompts section.

Creating Your First Prompt

Create a text prompt with the createPrompt method:

1import { Opik, PromptType } from "opik";
2
3const client = new Opik();
4
5const prompt = await client.createPrompt({
6 name: "greeting-prompt",
7 prompt: "Hello {{name}}, your score is {{score}}",
8 type: PromptType.MUSTACHE,
9 metadata: { version: "1.0" },
10 tags: ["greetings"],
11});
12
13console.log(`Created prompt with commit: ${prompt.commit}`);

Retrieving Prompts

Get prompts by name or specific version:

1// Get latest version
2const prompt = await client.getPrompt({ name: "greeting-prompt" });
3
4if (prompt) {
5 console.log(`Template: ${prompt.prompt}`);
6 console.log(`Commit: ${prompt.commit}`);
7}
8
9// Get specific version
10const oldVersion = await client.getPrompt({
11 name: "greeting-prompt",
12 commit: "abc123de",
13});

Formatting Prompts

Opik supports two powerful template engines:

  • Mustache - Simple, logic-less templates with {{variable}} placeholders (default)
  • Jinja2 - Advanced templating with control flow using {% %} blocks and {{ }} variables

The format() method works on both Prompt and PromptVersion instances:

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2
3// Format with variables
4const text = prompt.format({ name: "Alice", score: 95 });
5// Returns: "Hello Alice, your score is 95"
6
7// Format also works on PromptVersion objects
8const versions = await prompt.getVersions();
9const previousVersion = versions[1];
10const oldText = previousVersion.format({ name: "Alice", score: 95 });

Template Syntax Examples:

1// Mustache syntax (default)
2await client.createPrompt({
3 name: "mustache-prompt",
4 prompt: "Hello {{name}}, your score is {{score}}",
5 type: PromptType.MUSTACHE,
6});
7
8// Jinja2 syntax for advanced templating
9await client.createPrompt({
10 name: "jinja2-prompt",
11 prompt: "Hello {{ name }}! {% if premium %}Premium user{% endif %}",
12 type: PromptType.JINJA2,
13});

Core Operations

Creating and Updating

Understanding Version Creation

The createPrompt method intelligently handles versioning based on content changes:

New version is created when:

  • Template content (prompt) changes
  • Metadata changes (deep equality check)
  • Template type (type) changes

No new version (returns existing) when:

  • Template, metadata, and type are all identical
  • Only tags or description differ
1// First call - creates new prompt with version 1
2const prompt1 = await client.createPrompt({
3 name: "greeting-prompt",
4 prompt: "Hello {{name}}, your score is {{score}}",
5 type: PromptType.MUSTACHE,
6 metadata: { version: "1.0" },
7 tags: ["greetings"],
8});
9
10// Same template, metadata, and type - returns existing version
11const prompt2 = await client.createPrompt({
12 name: "greeting-prompt",
13 prompt: "Hello {{name}}, your score is {{score}}", // Same
14 metadata: { version: "1.0" }, // Same
15 type: PromptType.MUSTACHE, // Same
16 tags: ["updated-tags"], // Different tags don't trigger new version
17});
18console.log(prompt2.commit === prompt1.commit); // true
19
20// Changed template - creates new version 2
21const prompt3 = await client.createPrompt({
22 name: "greeting-prompt",
23 prompt: "Hi {{name}}, score: {{score}}", // Different template
24 changeDescription: "Simplified greeting message",
25});
26
27// Changed metadata - creates new version 3
28const prompt4 = await client.createPrompt({
29 name: "greeting-prompt",
30 prompt: "Hi {{name}}, score: {{score}}", // Same as version 2
31 metadata: { version: "2.0" }, // Different metadata triggers new version
32 changeDescription: "Updated metadata",
33});

Version creation is triggered by changes to template content, metadata, or type. Changes to tags, name or description alone do not create new versions - use updateProperties() for those.

Updating Prompt Properties

Update prompt metadata without creating new versions:

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2
3// Update name, description, or tags
4await prompt.updateProperties({
5 name: "welcome-prompt",
6 description: "Updated greeting template",
7 tags: ["welcome", "production", "v2"],
8});
9
10console.log(`Updated prompt name: ${prompt.name}`);

Updating properties (name, description, tags) does not create a new version. Only changes to the template content, metadata, or type trigger version creation.

Retrieving and Searching

Searching with Opik Query Language

Search and filter prompts using Opik Query Language (OQL) - a powerful SQL-like syntax for finding exactly the prompts you need.

Supported Fields:

FieldTypeDescriptionExample
idStringUnique prompt identifierid = "prompt-123"
nameStringPrompt namename contains "greeting"
descriptionStringPrompt descriptiondescription contains "template"
tagsListPrompt tagstags contains "production"
template_structureStringPrompt type (text or chat)template_structure = "chat"
created_byStringCreator email/identifiercreated_by = "user@example.com"
created_atDateTimeCreation timestampcreated_at > "2024-01-01"
last_updated_byStringLast updater email/identifierlast_updated_by = "admin@example.com"
last_updated_atDateTimeLast update timestamplast_updated_at > "2024-01-01"

Search Examples:

1// Search all prompts (no filter)
2const allPrompts = await client.searchPrompts();
3
4// Search by exact name
5const prompts = await client.searchPrompts('name = "greeting-prompt"');
6
7// Search by name pattern
8const chatPrompts = await client.searchPrompts('name contains "chat"');
9
10// Search by tags
11const prodPrompts = await client.searchPrompts('tags contains "production"');
12
13// Search by creator
14const myPrompts = await client.searchPrompts(
15 'created_by = "alice@company.com"',
16);
17
18// Filter by prompt type
19const chatPrompts = await client.searchPrompts('template_structure = "chat"');
20const textPrompts = await client.searchPrompts('template_structure = "text"');
21
22// Combine filters
23const prodChatPrompts = await client.searchPrompts(
24 'template_structure = "chat" AND tags contains "production"',
25);

Deleting Prompts

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2
3// Delete prompt and all its versions
4await prompt.delete();
5
6// Or delete multiple prompts by ID
7await client.deletePrompts([prompt.id, anotherPrompt.id]);

Version Management

Understanding Versions

Version Metadata and Properties

Access comprehensive version information:

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2const versions = await prompt.getVersions();
3const latest = versions[0];
4
5// Version properties
6console.log(`ID: ${latest.id}`);
7console.log(`Commit: ${latest.commit}`);
8console.log(`Template: ${latest.prompt}`);
9console.log(`Created: ${latest.createdAt}`);
10console.log(`Creator: ${latest.createdBy}`);
11console.log(`Type: ${latest.type}`);
12console.log(`Change: ${latest.changeDescription}`);
13
14// Formatted version info
15console.log(latest.getVersionInfo());
16// Output: [abc123de] 2024-01-15 by user@example.com - Initial version
17
18// Human-readable age
19console.log(latest.getVersionAge());
20// Output: "2 days ago"

Viewing Version History

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2
3// Get all versions
4const versions = await prompt.getVersions();
5
6console.log(`Total versions: ${versions.length}`);
7
8versions.forEach((version) => {
9 console.log(version.getVersionInfo());
10 // Output: [abc123de] 2024-01-15 by user@example.com - Initial version
11});

Working with Versions

Getting Specific Versions

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2
3// Option 1: Get version as Prompt instance (recommended for formatting)
4const oldVersion = await prompt.getVersion("abc123de");
5
6if (oldVersion) {
7 const text = oldVersion.format({ name: "Bob", score: 88 });
8 console.log(`Old version output: ${text}`);
9}
10
11// Option 2: Use format directly on PromptVersion objects
12const versions = await prompt.getVersions();
13const secondVersion = versions[1];
14
15// PromptVersion also has format() method
16const formattedText = secondVersion.format({ name: "Charlie", score: 92 });
17console.log(`Version ${secondVersion.commit}: ${formattedText}`);

Comparing Versions

1const versions = await prompt.getVersions();
2
3if (versions.length >= 2) {
4 const current = versions[0];
5 const previous = versions[1];
6
7 // Compare versions (logs diff and returns it)
8 const diff = current.compareTo(previous);
9 console.log(diff);
10 /* Output:
11 * - Current version [abc123de]
12 * + Other version [def456gh]
13 * @@ -1,2 +1,2 @@
14 * - Hello {{name}}, welcome!
15 * + Hello {{name}}, your score is {{score}}
16 */
17}

Restoring Previous Versions

1const prompt = await client.getPrompt({ name: "greeting-prompt" });
2const versions = await prompt.getVersions();
3
4// Find specific version to restore
5const targetVersion = versions.find((v) => v.commit === "abc123de");
6
7if (targetVersion) {
8 // Restore creates a new version with the old content
9 const restoredPrompt = await prompt.useVersion(targetVersion);
10
11 console.log(`Restored to commit: ${restoredPrompt.commit}`);
12 console.log(`Template: ${restoredPrompt.prompt}`);
13}

Advanced Usage

Integration with Tracing

Prompts work seamlessly with Opik’s tracing functionality:

1import { Opik, track } from "opik";
2
3const client = new Opik();
4
5@track
6async function generateGreeting(userName: string, userScore: number) {
7 // Get the prompt
8 const prompt = await client.getPrompt({ name: "greeting-prompt" });
9
10 // Format it
11 const message = prompt.format({
12 name: userName,
13 score: userScore,
14 });
15
16 // Use with your LLM
17 const response = await llmClient.complete(message);
18
19 return response;
20}

Best Practices

Store Prompts in Code

Keep your prompts versioned alongside your code:

1// prompts/greeting.ts
2export const GREETING_TEMPLATE = "Hello {{name}}, your score is {{score}}";
3
4// In your application
5import { GREETING_TEMPLATE } from "./prompts/greeting";
6
7const prompt = await client.createPrompt({
8 name: "greeting",
9 prompt: GREETING_TEMPLATE,
10 metadata: { version: "1.0" },
11});

Use Meaningful Version Descriptions

1const prompt = await client.createPrompt({
2 name: "summary-prompt",
3 prompt: updatedTemplate,
4 changeDescription: "Added support for multi-language summaries",
5 metadata: { sprint: "Q1-2024" },
6});

Tag Your Prompts

1const prompt = await client.createPrompt({
2 name: "production-greeting",
3 prompt: template,
4 tags: ["production", "customer-facing", "v2"],
5});
6
7// Later, search by tags
8const prodPrompts = await client.searchPrompts('tags contains "production"');

Chat Prompts

Chat prompts are structured message-based templates designed for conversational AI applications. They support multiple message roles (system, user, assistant) and multimodal content including text, images, and videos.

Key Features

  • Structured Messages: Organize prompts as a list of messages with roles (system, user, assistant)
  • Multimodal Support: Include images, videos, and text in the same prompt
  • Variable Substitution: Use Mustache ({{variable}}) or Jinja2 syntax
  • Version Control: Automatic versioning when messages change
  • Template Validation: Optional validation of template placeholders

Creating Chat Prompts

Create chat prompts using the createChatPrompt method:

1import { Opik, PromptType } from "opik";
2
3const client = new Opik();
4
5// Define chat messages with variables
6const messages = [
7 {
8 role: "system",
9 content: "You are a helpful assistant specializing in {{domain}}.",
10 },
11 {
12 role: "user",
13 content: "Explain {{topic}} in simple terms.",
14 },
15];
16
17// Create a chat prompt
18const chatPrompt = await client.createChatPrompt({
19 name: "educational-assistant",
20 messages: messages,
21 type: PromptType.MUSTACHE,
22 metadata: { category: "education" },
23 tags: ["education", "assistant"],
24});
25
26console.log(`Created chat prompt with commit: ${chatPrompt.commit}`);

Formatting Chat Prompts

Format chat prompts with variables to get ready-to-use message arrays:

1const chatPrompt = await client.getChatPrompt({
2 name: "educational-assistant",
3});
4
5if (chatPrompt) {
6 // Format the messages with variables
7 const formattedMessages = chatPrompt.format({
8 domain: "physics",
9 topic: "quantum entanglement",
10 });
11
12 console.log(formattedMessages);
13 // Output:
14 // [
15 // { role: "system", content: "You are a helpful assistant specializing in physics." },
16 // { role: "user", content: "Explain quantum entanglement in simple terms." }
17 // ]
18}

Multi-Turn Conversations

Create templates for multi-turn conversations:

1const messages = [
2 {
3 role: "system",
4 content: "You are a customer support agent for {{company}}.",
5 },
6 {
7 role: "user",
8 content: "I have an issue with {{product}}.",
9 },
10 {
11 role: "assistant",
12 content: "I'd be happy to help with your {{product}}. Can you describe the issue?",
13 },
14 {
15 role: "user",
16 content: "{{issue_description}}",
17 },
18];
19
20const chatPrompt = await client.createChatPrompt({
21 name: "customer-support-flow",
22 messages: messages,
23});
24
25// Format with specific values
26const formatted = chatPrompt.format({
27 company: "Acme Corp",
28 product: "Widget Pro",
29 issue_description: "It won't turn on",
30});

Multimodal Chat Prompts

Chat prompts support multimodal content for vision-enabled models:

Image Analysis

1// Chat prompt with image content
2const messages = [
3 {
4 role: "system",
5 content: "You analyze images and provide detailed descriptions.",
6 },
7 {
8 role: "user",
9 content: [
10 { type: "text", text: "What's in this image of {{subject}}?" },
11 {
12 type: "image_url",
13 image_url: {
14 url: "{{image_url}}",
15 detail: "high",
16 },
17 },
18 ],
19 },
20];
21
22const chatPrompt = await client.createChatPrompt({
23 name: "image-analyzer",
24 messages: messages,
25});
26
27// Format with variables
28const formatted = chatPrompt.format(
29 {
30 subject: "a sunset",
31 image_url: "https://example.com/sunset.jpg",
32 },
33 { vision: true }, // Supported modalities
34);

Video Analysis

1// Chat prompt with video content
2const messages = [
3 {
4 role: "system",
5 content: "You analyze videos and provide insights.",
6 },
7 {
8 role: "user",
9 content: [
10 { type: "text", text: "Analyze this video: {{description}}" },
11 {
12 type: "video_url",
13 video_url: {
14 url: "{{video_url}}",
15 mime_type: "video/mp4",
16 },
17 },
18 ],
19 },
20];
21
22const chatPrompt = await client.createChatPrompt({
23 name: "video-analyzer",
24 messages: messages,
25});
26
27// Format with variables
28const formatted = chatPrompt.format(
29 {
30 description: "traffic analysis",
31 video_url: "https://example.com/traffic.mp4",
32 },
33 { vision: true, video: true },
34);

Mixed Content

1// Chat prompt with multiple images and text
2const messages = [
3 {
4 role: "user",
5 content: [
6 { type: "text", text: "Compare these two images:" },
7 {
8 type: "image_url",
9 image_url: { url: "{{image1_url}}" },
10 },
11 { type: "text", text: "and" },
12 {
13 type: "image_url",
14 image_url: { url: "{{image2_url}}" },
15 },
16 { type: "text", text: "What are the main differences?" },
17 ],
18 },
19];
20
21const chatPrompt = await client.createChatPrompt({
22 name: "image-comparison",
23 messages: messages,
24});
25
26const formatted = chatPrompt.format(
27 {
28 image1_url: "https://example.com/before.jpg",
29 image2_url: "https://example.com/after.jpg",
30 },
31 { vision: true },
32);

When formatting multimodal prompts, you can specify supportedModalities to control how content is rendered:

  • If a modality is supported (e.g., { vision: true }), the structured content is preserved
  • If a modality is not supported, it’s replaced with text placeholders (e.g., <<<image>>><<</image>>>)

This allows you to use the same prompt template with different models that may or may not support certain modalities.

Retrieving Chat Prompts

Get chat prompts by name or specific version:

1// Get latest version
2const chatPrompt = await client.getChatPrompt({
3 name: "educational-assistant",
4});
5
6if (chatPrompt) {
7 console.log(`Messages: ${JSON.stringify(chatPrompt.messages)}`);
8 console.log(`Commit: ${chatPrompt.commit}`);
9}
10
11// Get specific version
12const oldVersion = await client.getChatPrompt({
13 name: "educational-assistant",
14 commit: "abc123de",
15});

Searching Chat Prompts

Search for chat prompts specifically using the template_structure filter:

1// Search for only chat prompts
2const chatPrompts = await client.searchPrompts(
3 'template_structure = "chat" AND name contains "assistant"',
4);
5
6for (const prompt of chatPrompts) {
7 console.log(`Chat prompt: ${prompt.name}`);
8}
9
10// Search for text prompts only
11const textPrompts = await client.searchPrompts('template_structure = "text"');

Without the template_structure filter, searchPrompts returns both text and chat prompts.

Template Types for Chat Prompts

Chat prompts support two template types:

Mustache (Default)

1import { PromptType } from "opik";
2
3const messages = [
4 {
5 role: "user",
6 content: "Hello {{name}}, you live in {{city}}.",
7 },
8];
9
10const chatPrompt = await client.createChatPrompt({
11 name: "mustache-example",
12 messages: messages,
13 type: PromptType.MUSTACHE, // Default
14});
15
16const formatted = chatPrompt.format({
17 name: "Alice",
18 city: "Paris",
19});
20// Result: [{ role: "user", content: "Hello Alice, you live in Paris." }]

Jinja2

1import { PromptType } from "opik";
2
3const messages = [
4 {
5 role: "user",
6 content: `
7 {% if is_premium %}
8 Hello {{ name }}, welcome to our premium service!
9 {% else %}
10 Hello {{ name }}, welcome!
11 {% endif %}
12 `,
13 },
14];
15
16const chatPrompt = await client.createChatPrompt({
17 name: "jinja-example",
18 messages: messages,
19 type: PromptType.JINJA2,
20});
21
22// With premium user
23const formatted1 = chatPrompt.format({
24 name: "Alice",
25 is_premium: true,
26});
27// Result includes: "Hello Alice, welcome to our premium service!"
28
29// With regular user
30const formatted2 = chatPrompt.format({
31 name: "Bob",
32 is_premium: false,
33});
34// Result includes: "Hello Bob, welcome!"

Jinja2 templates support advanced features like conditionals, loops, and filters, making them more powerful for complex prompt logic. However, Mustache templates are simpler and more portable.

Chat Prompt Versioning

Chat prompts are automatically versioned when the messages change:

1// Create initial version
2const messagesV1 = [
3 { role: "system", content: "You are helpful." },
4 { role: "user", content: "Hi!" },
5];
6
7const chatPrompt = await client.createChatPrompt({
8 name: "greeting-prompt",
9 messages: messagesV1,
10});
11
12console.log(`Version 1 commit: ${chatPrompt.commit}`);
13
14// Update with new messages - creates new version
15const messagesV2 = [
16 { role: "system", content: "You are a helpful assistant." },
17 { role: "user", content: "Hello {{name}}!" },
18];
19
20const chatPromptV2 = await client.createChatPrompt({
21 name: "greeting-prompt",
22 messages: messagesV2,
23 changeDescription: "Added personalization with name variable",
24});
25
26console.log(`Version 2 commit: ${chatPromptV2.commit}`);
27
28// Get version history
29const versions = await chatPrompt.getVersions();
30console.log(`Total versions: ${versions.length}`);

Version Management for Chat Prompts

Chat prompts support the same version management features as text prompts:

1const chatPrompt = await client.getChatPrompt({
2 name: "greeting-prompt",
3});
4
5// Get all versions
6const versions = await chatPrompt.getVersions();
7
8// Get specific version
9const oldVersion = await chatPrompt.getVersion("abc123de");
10
11// Compare versions
12if (versions.length >= 2) {
13 const current = versions[0];
14 const previous = versions[1];
15 const diff = current.compareTo(previous);
16 console.log(diff);
17}
18
19// Restore previous version
20const targetVersion = versions.find((v) => v.commit === "abc123de");
21if (targetVersion) {
22 const restoredPrompt = await chatPrompt.useVersion(targetVersion);
23 console.log(`Restored to commit: ${restoredPrompt.commit}`);
24}

Updating Chat Prompt Properties

Update chat prompt metadata without creating new versions:

1const chatPrompt = await client.getChatPrompt({
2 name: "greeting-prompt",
3});
4
5// Update name, description, or tags
6await chatPrompt.updateProperties({
7 name: "welcome-prompt",
8 description: "Updated greeting template",
9 tags: ["welcome", "production", "v2"],
10});
11
12console.log(`Updated prompt name: ${chatPrompt.name}`);

Updating properties (name, description, tags) does not create a new version. Only changes to the messages, metadata, or type trigger version creation.

API Reference

OpikClient Methods

createPrompt(options)

Creates a new prompt or returns existing version if content unchanged.

Arguments:

  • options.name: string - Prompt name (required)
  • options.prompt: string - Template content (required)
  • options.type?: PromptType - Template engine (default: MUSTACHE)
  • options.promptId?: string - Optional prompt ID
  • options.description?: string - Optional description
  • options.metadata?: JsonNode - Optional metadata
  • options.changeDescription?: string - Version change description
  • options.tags?: string[] - Optional tags

Returns: Promise<Prompt> - Created or existing prompt

getPrompt(options)

Retrieves a prompt by name and optional version.

Arguments:

  • options.name: string - Prompt name (required)
  • options.commit?: string - Optional commit ID for specific version

Returns: Promise<Prompt | null> - Prompt instance or null if not found

searchPrompts(filterString?)

Searches prompts with optional OQL filtering.

Arguments:

  • filterString?: string - Optional OQL filter expression

Returns: Promise<Prompt[]> - Array of matching prompts

Supported OQL fields:

  • id, name, created_by: String fields
  • tags: List field (use “contains” operator)

Operators: =, !=, contains, not_contains, starts_with, ends_with, >, <

deletePrompts(ids)

Deletes multiple prompts and all their versions.

Arguments:

  • ids: string[] - Array of prompt IDs to delete

Returns: Promise<void>

updatePromptVersionTags(versionIds, options?)

Updates tags for one or more prompt versions in a single batch operation.

Arguments:

  • versionIds: string[] - Array of prompt version IDs to update
  • options.tags?: string[] | null - Tags to set or merge:
    • [] – clears all tags (when mergeTags is false or unspecified)
    • ['tag1', 'tag2'] – sets or merges tags (based on mergeTags)
    • null / omitted – preserves existing tags unchanged
  • options.mergeTags?: boolean – If true, adds new tags to existing tags (union). If false (default), replaces all existing tags.

Returns: Promise<void>

Examples:

1// Replace all tags on multiple versions (default behavior)
2await client.updatePromptVersionTags(["version-id-1", "version-id-2"], {
3 tags: ["production", "v2"],
4});
5
6// Merge new tags with existing tags
7await client.updatePromptVersionTags(["version-id-1"], {
8 tags: ["hotfix"],
9 mergeTags: true,
10});
11
12// Clear all tags
13await client.updatePromptVersionTags(["version-id-1"], {
14 tags: [],
15});

createChatPrompt(options)

Creates a new chat prompt or returns existing version if content unchanged.

Arguments:

  • options.name: string - Chat prompt name (required)
  • options.messages: ChatMessage[] - Array of chat messages with roles and content (required)
  • options.type?: PromptType - Template engine (default: MUSTACHE)
  • options.promptId?: string - Optional prompt ID
  • options.description?: string - Optional description
  • options.metadata?: JsonNode - Optional metadata
  • options.changeDescription?: string - Version change description
  • options.tags?: string[] - Optional tags

Returns: Promise<ChatPrompt> - Created or existing chat prompt

ChatMessage Format:

1interface ChatMessage {
2 role: "system" | "user" | "assistant";
3 content: string | ContentPart[];
4}
5
6interface ContentPart {
7 type: "text" | "image_url" | "video_url";
8 text?: string; // For text type
9 image_url?: { url: string; detail?: string }; // For image_url type
10 video_url?: { url: string; mime_type?: string }; // For video_url type
11}

getChatPrompt(options)

Retrieves a chat prompt by name and optional version.

Arguments:

  • options.name: string - Chat prompt name (required)
  • options.commit?: string - Optional commit ID for specific version

Returns: Promise<ChatPrompt | null> - ChatPrompt instance or null if not found

Prompt Class

Methods

format(variables)

Formats the prompt template with provided variables.

Arguments:

  • variables: Record<string, unknown> - Variables to substitute

Returns: string - Formatted prompt text

Throws: PromptValidationError if required variables missing (Mustache only)

getVersions(options?)

Retrieves all version history for this prompt, with optional filtering, sorting, and search.

Arguments:

  • options.search?: string - Free-text search against template content and change description
  • options.filters?: string - JSON-encoded filter array. Each entry is { field, operator, value }.
  • options.sorting?: string - JSON-encoded sort array. Each entry is { field, direction } where direction is "ASC" or "DESC".

Supported filter fields:

FieldTypeOperators
idString=, !=, contains, not_contains, starts_with, ends_with, >, <
commitString=, !=, contains, not_contains, starts_with, ends_with, >, <
templateString=, !=, contains, not_contains, starts_with, ends_with, >, <
change_descriptionString=, !=, contains, not_contains, starts_with, ends_with, >, <
created_byString=, !=, contains, not_contains, starts_with, ends_with, >, <
typeEnum=, !=
tagsListcontains
created_atDateTime>=, <=, >, < (ISO 8601)

Returns: Promise<PromptVersion[]> - Array of all matching versions (newest first by default)

Examples:

1// Get all versions
2const versions = await prompt.getVersions();
3
4// Search by template or change description content
5const searched = await prompt.getVersions({ search: "customer" });
6
7// Filter by tag
8const prodVersions = await prompt.getVersions({
9 filters: JSON.stringify([
10 { field: "tags", operator: "contains", value: "production" },
11 ]),
12});
13
14// Filter by multiple tags (AND logic)
15const stable = await prompt.getVersions({
16 filters: JSON.stringify([
17 { field: "tags", operator: "contains", value: "production" },
18 { field: "tags", operator: "contains", value: "stable" },
19 ]),
20});
21
22// Filter by template content
23const customerVersions = await prompt.getVersions({
24 filters: JSON.stringify([
25 { field: "template", operator: "contains", value: "customer" },
26 ]),
27});
28
29// Filter by date
30const recentVersions = await prompt.getVersions({
31 filters: JSON.stringify([
32 { field: "created_at", operator: ">=", value: "2024-01-01T00:00:00Z" },
33 ]),
34});
35
36// Sort by creation date (oldest first)
37const oldest = await prompt.getVersions({
38 sorting: JSON.stringify([{ field: "created_at", direction: "ASC" }]),
39});
40
41// Sort alphabetically by template content
42const alphabetical = await prompt.getVersions({
43 sorting: JSON.stringify([{ field: "template", direction: "ASC" }]),
44});
45
46// Combine search, filter, and sort
47const results = await prompt.getVersions({
48 search: "customer",
49 filters: JSON.stringify([
50 { field: "tags", operator: "contains", value: "production" },
51 ]),
52 sorting: JSON.stringify([{ field: "created_at", direction: "DESC" }]),
53});
getVersion(commit)

Gets a specific version as a Prompt instance.

Arguments:

  • commit: string - Commit hash (8-char or full)

Returns: Promise<Prompt | null> - Prompt instance or null if not found

useVersion(version)

Restores a specific version by creating a new version with old content.

Arguments:

  • version: PromptVersion - Version object to restore

Returns: Promise<Prompt> - New prompt instance with restored content

updateProperties(updates)

Updates prompt properties without creating new version.

Arguments:

  • updates.name?: string - New prompt name
  • updates.description?: string - New description
  • updates.tags?: string[] - New tags array

Returns: Promise<this> - This prompt instance (for chaining)

delete()

Deletes this prompt and all its versions.

Returns: Promise<void>

Properties

  • id: string - Unique prompt identifier
  • name: string - Prompt name
  • prompt: string - Current template content
  • commit?: string - Current version commit ID
  • type: PromptType - Template engine type
  • description?: string - Prompt description
  • tags?: readonly string[] - Prompt tags
  • metadata?: JsonNode - Prompt metadata
  • changeDescription?: string - Latest version change description

PromptVersion Class

Methods

format(variables)

Formats this version’s template with provided variables.

Arguments:

  • variables: Record<string, unknown> - Variables to substitute

Returns: string - Formatted prompt text

getVersionInfo()

Gets formatted version information string.

Returns: string - Format: [commit] YYYY-MM-DD by user@email.com - Change description

getVersionAge()

Gets human-readable version age.

Returns: string - Format: “2 days ago”, “Today”, etc.

compareTo(other)

Compares this version’s template with another version.

Arguments:

  • other: PromptVersion - Version to compare against

Returns: string - Git-style unified diff showing changes

Properties

  • id: string - Version unique identifier
  • name: string - Associated prompt name
  • prompt: string - Template content for this version
  • commit: string - Version commit ID
  • type: PromptType - Template engine type
  • tags?: string[] - Tags associated with this version
  • metadata?: JsonNode - Version metadata
  • changeDescription?: string - Version change description
  • createdAt?: Date - Creation timestamp
  • createdBy?: string - Creator identifier

ChatPrompt Class

The ChatPrompt class extends BasePrompt and provides chat-specific functionality for managing structured message-based prompts.

Methods

format(variables, supportedModalities?)

Formats the chat prompt messages with provided variables.

Arguments:

  • variables: Record<string, unknown> - Variables to substitute in message content
  • supportedModalities?: SupportedModalities - Optional modality support configuration

SupportedModalities Format:

1interface SupportedModalities {
2 vision?: boolean; // Support for image content (default: true)
3 video?: boolean; // Support for video content (default: true)
4}

Returns: ChatMessage[] - Array of formatted chat messages

Throws: PromptValidationError if required variables missing (Mustache only)

Example:

1const formatted = chatPrompt.format(
2 { name: "Alice", topic: "AI" },
3 { vision: true, video: false },
4);
getVersions(options?)

Retrieves all version history for this chat prompt, with optional filtering, sorting, and search. Accepts the same options as the Prompt.getVersions() method.

Arguments:

  • options.search?: string - Search text to match against template content and change description
  • options.sorting?: string - Sort expression
  • options.filters?: string - JSON-encoded filter array (same format as Prompt.getVersions)

Returns: Promise<PromptVersion[]> - Array of all matching versions (newest first)

getVersion(commit)

Gets a specific version as a ChatPrompt instance.

Arguments:

  • commit: string - Commit hash (8-char or full)

Returns: Promise<ChatPrompt | null> - ChatPrompt instance or null if not found

useVersion(version)

Restores a specific version by creating a new version with old content.

Arguments:

  • version: PromptVersion - Version object to restore

Returns: Promise<ChatPrompt> - New chat prompt instance with restored content

updateProperties(updates)

Updates chat prompt properties without creating new version.

Arguments:

  • updates.name?: string - New prompt name
  • updates.description?: string - New description
  • updates.tags?: string[] - New tags array

Returns: Promise<this> - This chat prompt instance (for chaining)

delete()

Deletes this chat prompt and all its versions.

Returns: Promise<void>

Properties

  • id: string - Unique chat prompt identifier
  • name: string - Chat prompt name
  • messages: ChatMessage[] - Array of chat messages with roles and content
  • commit?: string - Current version commit ID
  • type: PromptType - Template engine type
  • description?: string - Chat prompt description
  • tags?: readonly string[] - Chat prompt tags
  • metadata?: JsonNode - Chat prompt metadata
  • changeDescription?: string - Latest version change description