Skip to main content
Opik Documentation

Search documentation

Type to search this documentation.

On this pageOverview

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.

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

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

Create a text prompt with the createPrompt method:

TypeScript
import { Opik, PromptType } from "opik";

const client = new Opik();

const prompt = await client.createPrompt({
  name: "greeting-prompt",
  prompt: "Hello {{name}}, your score is {{score}}",
  type: PromptType.MUSTACHE,
  metadata: { version: "1.0" },
  tags: ["greetings"],
  projectName: "my-project",
});

console.log(`Created prompt with version: ${prompt.version}`);

Get prompts by name or specific version:

TypeScript
// Get latest version
const prompt = await client.getPrompt({ name: "greeting-prompt" });

if (prompt) {
  console.log(`Template: ${prompt.prompt}`);
  console.log(`Version: ${prompt.version}`);
}

// Get specific version by its sequential version identifier ("v<N>")
const oldVersion = await client.getPrompt({
  name: "greeting-prompt",
  version: "v1",
});

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:

TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });

// Format with variables
const text = prompt.format({ name: "Alice", score: 95 });
// Returns: "Hello Alice, your score is 95"

// Format also works on PromptVersion objects
const versions = await prompt.getVersions();
const previousVersion = versions[1];
const oldText = previousVersion.format({ name: "Alice", score: 95 });

Template Syntax Examples:

TypeScript
// Mustache syntax (default)
await client.createPrompt({
  name: "mustache-prompt",
  prompt: "Hello {{name}}, your score is {{score}}",
  type: PromptType.MUSTACHE,
  projectName: "my-project",
});

// Jinja2 syntax for advanced templating
await client.createPrompt({
  name: "jinja2-prompt",
  prompt: "Hello {{ name }}! {% if premium %}Premium user{% endif %}",
  type: PromptType.JINJA2,
  projectName: "my-project",
});

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
TypeScript
// First call - creates new prompt with version 1
const prompt1 = await client.createPrompt({
  name: "greeting-prompt",
  prompt: "Hello {{name}}, your score is {{score}}",
  type: PromptType.MUSTACHE,
  metadata: { version: "1.0" },
  tags: ["greetings"],
  projectName: "my-project",
});

// Same template, metadata, and type - returns existing version
const prompt2 = await client.createPrompt({
  name: "greeting-prompt",
  prompt: "Hello {{name}}, your score is {{score}}", // Same
  metadata: { version: "1.0" }, // Same
  type: PromptType.MUSTACHE, // Same
  tags: ["updated-tags"], // Different tags don't trigger new version
  projectName: "my-project",
});
console.log(prompt2.version === prompt1.version); // true

// Changed template - creates new version 2
const prompt3 = await client.createPrompt({
  name: "greeting-prompt",
  prompt: "Hi {{name}}, score: {{score}}", // Different template
  changeDescription: "Simplified greeting message",
  projectName: "my-project",
});

// Changed metadata - creates new version 3
const prompt4 = await client.createPrompt({
  name: "greeting-prompt",
  prompt: "Hi {{name}}, score: {{score}}", // Same as version 2
  metadata: { version: "2.0" }, // Different metadata triggers new version
  changeDescription: "Updated metadata",
  projectName: "my-project",
});

Update prompt metadata without creating new versions:

TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });

// Update name, description, or tags
await prompt.updateProperties({
  name: "welcome-prompt",
  description: "Updated greeting template",
  tags: ["welcome", "production", "v2"],
});

console.log(`Updated prompt name: ${prompt.name}`);

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

Supported Fields:

Field Type Description Example
id String Unique prompt identifier id = "prompt-123"
name String Prompt name name contains "greeting"
description String Prompt description description contains "template"
tags List Prompt tags tags contains "production"
template_structure String Prompt type (text or chat) template_structure = "chat"
created_by String Creator email/identifier created_by = "user@example.com"
created_at DateTime Creation timestamp created_at > "2024-01-01"
last_updated_by String Last updater email/identifier last_updated_by = "admin@example.com"
last_updated_at DateTime Last update timestamp last_updated_at > "2024-01-01"

Search Examples:

TypeScript
// Search all prompts (no filter)
const allPrompts = await client.searchPrompts();

// Search by exact name
const prompts = await client.searchPrompts('name = "greeting-prompt"');

// Search by name pattern
const chatPrompts = await client.searchPrompts('name contains "chat"');

// Search by tags
const prodPrompts = await client.searchPrompts('tags contains "production"');

// Search by creator
const myPrompts = await client.searchPrompts(
  'created_by = "alice@company.com"',
);

// Filter by prompt type
const chatPrompts = await client.searchPrompts('template_structure = "chat"');
const textPrompts = await client.searchPrompts('template_structure = "text"');

// Combine filters
const prodChatPrompts = await client.searchPrompts(
  'template_structure = "chat" AND tags contains "production"',
);
TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });

// Delete prompt and all its versions
await prompt.delete();

// Or delete multiple prompts by ID
await client.deletePrompts([prompt.id, anotherPrompt.id]);

Access comprehensive version information:

TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });
const versions = await prompt.getVersions();
const latest = versions[0];

// Version properties
console.log(`ID: ${latest.id}`);
console.log(`Version: ${latest.version}`);
console.log(`Template: ${latest.prompt}`);
console.log(`Created: ${latest.createdAt}`);
console.log(`Creator: ${latest.createdBy}`);
console.log(`Type: ${latest.type}`);
console.log(`Change: ${latest.changeDescription}`);

// Formatted version info
console.log(latest.getVersionInfo());
// Output: [abc123de] 2024-01-15 by user@example.com - Initial version

// Human-readable age
console.log(latest.getVersionAge());
// Output: "2 days ago"
TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });

// Get all versions
const versions = await prompt.getVersions();

console.log(`Total versions: ${versions.length}`);

versions.forEach((version) => {
  console.log(version.getVersionInfo());
  // Output: [abc123de] 2024-01-15 by user@example.com - Initial version
});
TypeScript
// Option 1: Fetch a specific version straight from the client
const oldVersion = await client.getPrompt({
  name: "greeting-prompt",
  version: "v1",
});

if (oldVersion) {
  const text = oldVersion.format({ name: "Bob", score: 88 });
  console.log(`Version ${oldVersion.version} output: ${text}`);
}

// Option 2: From an existing prompt instance, pin to a specific version
const prompt = await client.getPrompt({ name: "greeting-prompt" });
const v1 = await prompt.getVersion("v1");

if (v1) {
  console.log(v1.format({ name: "Alice", score: 95 }));
}

// Option 3: Iterate version history and use format() directly on PromptVersion objects
const versions = await prompt.getVersions();
const previousVersion = versions[1];

// PromptVersion also has a format() method
const formattedText = previousVersion.format({ name: "Charlie", score: 92 });
console.log(formattedText);
TypeScript
const versions = await prompt.getVersions();

if (versions.length >= 2) {
  const current = versions[0]; // e.g. "v3"
  const previous = versions[1]; // e.g. "v2"

  // Compare versions (logs diff and returns it). Diff labels show the
  // sequential version identifiers (e.g. "[v3]" / "[v2]").
  const diff = current.compareTo(previous);
  console.log(diff);
  /* Output:
   * - Other version [v2]
   * + Current version [v3]
   * @@ -1,2 +1,2 @@
   * - Hello {{name}}, welcome!
   * + Hello {{name}}, your score is {{score}}
   */
}
TypeScript
const prompt = await client.getPrompt({ name: "greeting-prompt" });
const versions = await prompt.getVersions();

// Pick the version you want to restore — for example, the previous one
const [, previousVersion] = versions;

if (previousVersion) {
  // Restore creates a new version with the old content
  const restoredPrompt = await prompt.useVersion(previousVersion);

  console.log(`Restored to version: ${restoredPrompt.version}`);
  console.log(`Template: ${restoredPrompt.prompt}`);
}

Prompts work seamlessly with Opik's tracing functionality:

TypeScript
import { Opik, track } from "opik";

const client = new Opik();

@track
async function generateGreeting(userName: string, userScore: number) {
  // Get the prompt
  const prompt = await client.getPrompt({ name: "greeting-prompt" });

  // Format it
  const message = prompt.format({
    name: userName,
    score: userScore,
  });

  // Use with your LLM
  const response = await llmClient.complete(message);

  return response;
}

Keep your prompts versioned alongside your code:

TypeScript
// prompts/greeting.ts
export const GREETING_TEMPLATE = "Hello {{name}}, your score is {{score}}";

// In your application
import { GREETING_TEMPLATE } from "./prompts/greeting";

const prompt = await client.createPrompt({
  name: "greeting",
  prompt: GREETING_TEMPLATE,
  metadata: { version: "1.0" },
  projectName: "my-project",
});
TypeScript
const prompt = await client.createPrompt({
  name: "summary-prompt",
  prompt: updatedTemplate,
  changeDescription: "Added support for multi-language summaries",
  metadata: { sprint: "Q1-2024" },
  projectName: "my-project",
});
TypeScript
const prompt = await client.createPrompt({
  name: "production-greeting",
  prompt: template,
  tags: ["production", "customer-facing", "v2"],
  projectName: "my-project",
});

// Later, search by tags
const prodPrompts = await client.searchPrompts('tags contains "production"');

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.

  • 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

Create chat prompts using the createChatPrompt method:

TypeScript
import { Opik, PromptType } from "opik";

const client = new Opik();

// Define chat messages with variables
const messages = [
  {
    role: "system",
    content: "You are a helpful assistant specializing in {{domain}}.",
  },
  {
    role: "user",
    content: "Explain {{topic}} in simple terms.",
  },
];

// Create a chat prompt
const chatPrompt = await client.createChatPrompt({
  name: "educational-assistant",
  messages: messages,
  type: PromptType.MUSTACHE,
  metadata: { category: "education" },
  tags: ["education", "assistant"],
  projectName: "my-project",
});

console.log(`Created chat prompt with version: ${chatPrompt.version}`);

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

TypeScript
const chatPrompt = await client.getChatPrompt({
  name: "educational-assistant",
});

if (chatPrompt) {
  // Format the messages with variables
  const formattedMessages = chatPrompt.format({
    domain: "physics",
    topic: "quantum entanglement",
  });

  console.log(formattedMessages);
  // Output:
  // [
  //   { role: "system", content: "You are a helpful assistant specializing in physics." },
  //   { role: "user", content: "Explain quantum entanglement in simple terms." }
  // ]
}

Create templates for multi-turn conversations:

TypeScript
const messages = [
  {
    role: "system",
    content: "You are a customer support agent for {{company}}.",
  },
  {
    role: "user",
    content: "I have an issue with {{product}}.",
  },
  {
    role: "assistant",
    content: "I'd be happy to help with your {{product}}. Can you describe the issue?",
  },
  {
    role: "user",
    content: "{{issue_description}}",
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "customer-support-flow",
  messages: messages,
  projectName: "my-project",
});

// Format with specific values
const formatted = chatPrompt.format({
  company: "Acme Corp",
  product: "Widget Pro",
  issue_description: "It won't turn on",
});

Chat prompts support multimodal content for vision-enabled models:

TypeScript
// Chat prompt with image content
const messages = [
  {
    role: "system",
    content: "You analyze images and provide detailed descriptions.",
  },
  {
    role: "user",
    content: [
      { type: "text", text: "What's in this image of {{subject}}?" },
      {
        type: "image_url",
        image_url: {
          url: "{{image_url}}",
          detail: "high",
        },
      },
    ],
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "image-analyzer",
  messages: messages,
  projectName: "my-project",
});

// Format with variables
const formatted = chatPrompt.format(
  {
    subject: "a sunset",
    image_url: "https://example.com/sunset.jpg",
  },
  { vision: true }, // Supported modalities
);
TypeScript
// Chat prompt with video content
const messages = [
  {
    role: "system",
    content: "You analyze videos and provide insights.",
  },
  {
    role: "user",
    content: [
      { type: "text", text: "Analyze this video: {{description}}" },
      {
        type: "video_url",
        video_url: {
          url: "{{video_url}}",
          mime_type: "video/mp4",
        },
      },
    ],
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "video-analyzer",
  messages: messages,
  projectName: "my-project",
});

// Format with variables
const formatted = chatPrompt.format(
  {
    description: "traffic analysis",
    video_url: "https://example.com/traffic.mp4",
  },
  { vision: true, video: true },
);
TypeScript
// Chat prompt with multiple images and text
const messages = [
  {
    role: "user",
    content: [
      { type: "text", text: "Compare these two images:" },
      {
        type: "image_url",
        image_url: { url: "{{image1_url}}" },
      },
      { type: "text", text: "and" },
      {
        type: "image_url",
        image_url: { url: "{{image2_url}}" },
      },
      { type: "text", text: "What are the main differences?" },
    ],
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "image-comparison",
  messages: messages,
  projectName: "my-project",
});

const formatted = chatPrompt.format(
  {
    image1_url: "https://example.com/before.jpg",
    image2_url: "https://example.com/after.jpg",
  },
  { vision: true },
);

Get chat prompts by name or specific version:

TypeScript
// Get latest version
const chatPrompt = await client.getChatPrompt({
  name: "educational-assistant",
});

if (chatPrompt) {
  console.log(`Messages: ${JSON.stringify(chatPrompt.messages)}`);
  console.log(`Version: ${chatPrompt.version}`);
}

// Get specific version by its sequential version identifier ("v<N>")
const oldVersion = await client.getChatPrompt({
  name: "educational-assistant",
  version: "v1",
});

Search for chat prompts specifically using the template_structure filter:

TypeScript
// Search for only chat prompts
const chatPrompts = await client.searchPrompts(
  'template_structure = "chat" AND name contains "assistant"',
);

for (const prompt of chatPrompts) {
  console.log(`Chat prompt: ${prompt.name}`);
}

// Search for text prompts only
const textPrompts = await client.searchPrompts('template_structure = "text"');

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

Chat prompts support two template types:

TypeScript
import { PromptType } from "opik";

const messages = [
  {
    role: "user",
    content: "Hello {{name}}, you live in {{city}}.",
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "mustache-example",
  messages: messages,
  type: PromptType.MUSTACHE, // Default
  projectName: "my-project",
});

const formatted = chatPrompt.format({
  name: "Alice",
  city: "Paris",
});
// Result: [{ role: "user", content: "Hello Alice, you live in Paris." }]
TypeScript
import { PromptType } from "opik";

const messages = [
  {
    role: "user",
    content: `
      {% if is_premium %}
      Hello {{ name }}, welcome to our premium service!
      {% else %}
      Hello {{ name }}, welcome!
      {% endif %}
    `,
  },
];

const chatPrompt = await client.createChatPrompt({
  name: "jinja-example",
  messages: messages,
  type: PromptType.JINJA2,
  projectName: "my-project",
});

// With premium user
const formatted1 = chatPrompt.format({
  name: "Alice",
  is_premium: true,
});
// Result includes: "Hello Alice, welcome to our premium service!"

// With regular user
const formatted2 = chatPrompt.format({
  name: "Bob",
  is_premium: false,
});
// Result includes: "Hello Bob, welcome!"

Chat prompts are automatically versioned when the messages change:

TypeScript
// Create initial version
const messagesV1 = [
  { role: "system", content: "You are helpful." },
  { role: "user", content: "Hi!" },
];

const chatPrompt = await client.createChatPrompt({
  name: "greeting-prompt",
  messages: messagesV1,
  projectName: "my-project",
});

console.log(`Created ${chatPrompt.version}`);

// Update with new messages - creates new version
const messagesV2 = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Hello {{name}}!" },
];

const chatPromptV2 = await client.createChatPrompt({
  name: "greeting-prompt",
  messages: messagesV2,
  changeDescription: "Added personalization with name variable",
  projectName: "my-project",
});

console.log(`Created ${chatPromptV2.version}`);

// Get version history
const versions = await chatPrompt.getVersions();
console.log(`Total versions: ${versions.length}`);

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

TypeScript
const chatPrompt = await client.getChatPrompt({
  name: "greeting-prompt",
});

// Get all versions
const versions = await chatPrompt.getVersions();

// Get a specific version by its sequential identifier ("v<N>")
const oldVersion = await client.getChatPrompt({
  name: "greeting-prompt",
  version: "v1",
});

// Compare versions
if (versions.length >= 2) {
  const current = versions[0];
  const previous = versions[1];
  const diff = current.compareTo(previous);
  console.log(diff);
}

// Restore the previous version
const [, previousVersion] = versions;
if (previousVersion) {
  const restoredPrompt = await chatPrompt.useVersion(previousVersion);
  console.log(`Restored to version: ${restoredPrompt.version}`);
}

Update chat prompt metadata without creating new versions:

TypeScript
const chatPrompt = await client.getChatPrompt({
  name: "greeting-prompt",
});

// Update name, description, or tags
await chatPrompt.updateProperties({
  name: "welcome-prompt",
  description: "Updated greeting template",
  tags: ["welcome", "production", "v2"],
});

console.log(`Updated prompt name: ${chatPrompt.name}`);

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

Retrieves a prompt by name, optionally targeting a specific version.

Arguments:

  • options.name: string - Prompt name (required)
  • options.version?: string - Sequential version identifier (e.g. "v3"). If omitted, the latest version is returned.

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

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, >, <

Deletes multiple prompts and all their versions.

Arguments:

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

Returns: Promise<void>

updatePromptVersionTags(versionIds, options?)

Section titled “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:

TypeScript
// Replace all tags on multiple versions (default behavior)
await client.updatePromptVersionTags(["version-id-1", "version-id-2"], {
  tags: ["production", "v2"],
});

// Merge new tags with existing tags
await client.updatePromptVersionTags(["version-id-1"], {
  tags: ["hotfix"],
  mergeTags: true,
});

// Clear all tags
await client.updatePromptVersionTags(["version-id-1"], {
  tags: [],
});

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:

TypeScript
interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string | ContentPart[];
}

interface ContentPart {
  type: "text" | "image_url" | "video_url";
  text?: string; // For text type
  image_url?: { url: string; detail?: string }; // For image_url type
  video_url?: { url: string; mime_type?: string }; // For video_url type
}

Retrieves a chat prompt by name, optionally targeting a specific version.

Arguments:

  • options.name: string - Chat prompt name (required)
  • options.version?: string - Sequential version identifier (e.g. "v3"). If omitted, the latest version is returned.

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

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)

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:

Field Type Operators
id String =, !=, contains, not_contains, starts_with, ends_with, >, <
template String =, !=, contains, not_contains, starts_with, ends_with, >, <
change_description String =, !=, contains, not_contains, starts_with, ends_with, >, <
created_by String =, !=, contains, not_contains, starts_with, ends_with, >, <
type Enum =, !=
tags List contains
created_at DateTime >=, <=, >, < (ISO 8601)

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

Examples:

TypeScript
// Get all versions
const versions = await prompt.getVersions();

// Search by template or change description content
const searched = await prompt.getVersions({ search: "customer" });

// Filter by tag
const prodVersions = await prompt.getVersions({
  filters: JSON.stringify([
    { field: "tags", operator: "contains", value: "production" },
  ]),
});

// Filter by multiple tags (AND logic)
const stable = await prompt.getVersions({
  filters: JSON.stringify([
    { field: "tags", operator: "contains", value: "production" },
    { field: "tags", operator: "contains", value: "stable" },
  ]),
});

// Filter by template content
const customerVersions = await prompt.getVersions({
  filters: JSON.stringify([
    { field: "template", operator: "contains", value: "customer" },
  ]),
});

// Filter by date
const recentVersions = await prompt.getVersions({
  filters: JSON.stringify([
    { field: "created_at", operator: ">=", value: "2024-01-01T00:00:00Z" },
  ]),
});

// Sort by creation date (oldest first)
const oldest = await prompt.getVersions({
  sorting: JSON.stringify([{ field: "created_at", direction: "ASC" }]),
});

// Sort alphabetically by template content
const alphabetical = await prompt.getVersions({
  sorting: JSON.stringify([{ field: "template", direction: "ASC" }]),
});

// Combine search, filter, and sort
const results = await prompt.getVersions({
  search: "customer",
  filters: JSON.stringify([
    { field: "tags", operator: "contains", value: "production" },
  ]),
  sorting: JSON.stringify([{ field: "created_at", direction: "DESC" }]),
});

Returns a Prompt instance pinned to a specific version of this prompt. Accepts either the sequential version identifier (e.g. "v3") — preferred — or a commit hash (deprecated; retained for backwards compatibility). Inputs matching /^v\d+$/ are treated as version numbers; anything else is treated as a commit.

Arguments:

  • version: string - Sequential version ("v<N>") or commit hash (deprecated)

Returns: Promise<Prompt | null> - Prompt instance pinned to that version, or null if not found

TypeScript
// Preferred: fetch by sequential version identifier
const v3 = await prompt.getVersion("v3");

// Deprecated: fetch by commit hash
const byCommit = await prompt.getVersion("abc123de");

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

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)

Deletes this prompt and all its versions.

Returns: Promise<void>

  • id: string - Unique prompt identifier
  • name: string - Prompt name
  • prompt: string - Current template content
  • version?: string - Sequential version identifier (e.g. "v3")
  • type: PromptType - Template engine type
  • description?: string - Prompt description
  • tags?: readonly string[] - Prompt tags
  • metadata?: JsonNode - Prompt metadata
  • changeDescription?: string - Latest version change description

Formats this version's template with provided variables.

Arguments:

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

Returns: string - Formatted prompt text

Gets a formatted version-info string suitable for display. Includes the version identifier (e.g. "v3"), creation date, creator, and change description.

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

Gets human-readable version age.

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

Compares this version's template with another version. The diff is logged to the terminal and returned. Labels in the diff use the sequential version identifier (e.g. "[v3]").

Arguments:

  • other: PromptVersion - Version to compare against

Returns: string - Git-style unified diff showing changes

  • id: string - Version unique identifier
  • name: string - Associated prompt name
  • prompt: string - Template content for this version
  • version?: string - Sequential version identifier (e.g. "v3")
  • 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

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

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:

TypeScript
interface SupportedModalities {
  vision?: boolean; // Support for image content (default: true)
  video?: boolean; // Support for video content (default: true)
}

Returns: ChatMessage[] - Array of formatted chat messages

Throws: PromptValidationError if required variables missing (Mustache only)

Example:

TypeScript
const formatted = chatPrompt.format(
  { name: "Alice", topic: "AI" },
  { vision: true, video: false },
);

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)

Returns a ChatPrompt instance pinned to a specific version of this chat prompt. Accepts either the sequential version identifier (e.g. "v3") — preferred — or a commit hash (deprecated; retained for backwards compatibility). Inputs matching /^v\d+$/ are treated as version numbers; anything else is treated as a commit.

Arguments:

  • version: string - Sequential version ("v<N>") or commit hash (deprecated)

Returns: Promise<ChatPrompt | null> - ChatPrompt instance pinned to that version, or null if not found

TypeScript
// Preferred: fetch by sequential version identifier
const v3 = await chatPrompt.getVersion("v3");

// Deprecated: fetch by commit hash
const byCommit = await chatPrompt.getVersion("abc123de");

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

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)

Deletes this chat prompt and all its versions.

Returns: Promise<void>

  • id: string - Unique chat prompt identifier
  • name: string - Chat prompt name
  • messages: ChatMessage[] - Array of chat messages with roles and content
  • version?: string - Sequential version identifier (e.g. "v3")
  • 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
Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu