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
Section titled “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
Section titled “Getting Started”This section covers text prompts. For chat prompts with structured messages, see the Chat Prompts section.
Creating Your First Prompt
Section titled “Creating Your First Prompt”Create a text prompt with the createPrompt method:
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}`);Retrieving Prompts
Section titled “Retrieving Prompts”Get prompts by name or specific version:
// 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",
});Formatting Prompts
Section titled “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:
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:
// 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",
});Core Operations
Section titled “Core Operations”Creating and Updating
Section titled “Creating and Updating”Understanding Version Creation
Section titled “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
tagsordescriptiondiffer
// 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",
});Updating Prompt Properties
Section titled “Updating Prompt Properties”Update prompt metadata without creating new versions:
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}`);Retrieving and Searching
Section titled “Retrieving and Searching”Searching with Opik Query Language
Section titled “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:
| 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:
// 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"',
);Deleting Prompts
Section titled “Deleting Prompts”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]);Version Management
Section titled “Version Management”Understanding Versions
Section titled “Understanding Versions”Version Metadata and Properties
Section titled “Version Metadata and Properties”Access comprehensive version information:
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"Viewing Version History
Section titled “Viewing Version History”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
});Working with Versions
Section titled “Working with Versions”Getting Specific Versions
Section titled “Getting Specific Versions”// 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);Comparing Versions
Section titled “Comparing Versions”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}}
*/
}Restoring Previous Versions
Section titled “Restoring Previous Versions”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}`);
}Advanced Usage
Section titled “Advanced Usage”Integration with Tracing
Section titled “Integration with Tracing”Prompts work seamlessly with Opik's tracing functionality:
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;
}Best Practices
Section titled “Best Practices”Store Prompts in Code
Section titled “Store Prompts in Code”Keep your prompts versioned alongside your code:
// 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",
});Use Meaningful Version Descriptions
Section titled “Use Meaningful Version Descriptions”const prompt = await client.createPrompt({
name: "summary-prompt",
prompt: updatedTemplate,
changeDescription: "Added support for multi-language summaries",
metadata: { sprint: "Q1-2024" },
projectName: "my-project",
});Tag Your Prompts
Section titled “Tag Your Prompts”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
Section titled “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
Section titled “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
Section titled “Creating Chat Prompts”Create chat prompts using the createChatPrompt method:
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}`);Formatting Chat Prompts
Section titled “Formatting Chat Prompts”Format chat prompts with variables to get ready-to-use message arrays:
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." }
// ]
}Multi-Turn Conversations
Section titled “Multi-Turn Conversations”Create templates for multi-turn conversations:
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",
});Multimodal Chat Prompts
Section titled “Multimodal Chat Prompts”Chat prompts support multimodal content for vision-enabled models:
Image Analysis
Section titled “Image Analysis”// 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
);Video Analysis
Section titled “Video Analysis”// 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 },
);Mixed Content
Section titled “Mixed Content”// 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 },
);Retrieving Chat Prompts
Section titled “Retrieving Chat Prompts”Get chat prompts by name or specific version:
// 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",
});Searching Chat Prompts
Section titled “Searching Chat Prompts”Search for chat prompts specifically using the template_structure filter:
// 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.
Template Types for Chat Prompts
Section titled “Template Types for Chat Prompts”Chat prompts support two template types:
Mustache (Default)
Section titled “Mustache (Default)”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." }]Jinja2
Section titled “Jinja2”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 Prompt Versioning
Section titled “Chat Prompt Versioning”Chat prompts are automatically versioned when the messages change:
// 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}`);Version Management for Chat Prompts
Section titled “Version Management for Chat Prompts”Chat prompts support the same version management features as text prompts:
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}`);
}Updating Chat Prompt Properties
Section titled “Updating Chat Prompt Properties”Update chat prompt metadata without creating new versions:
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}`);API Reference
Section titled “API Reference”OpikClient Methods
Section titled “OpikClient Methods”createPrompt(options)
Section titled “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 IDoptions.description?: string- Optional descriptionoptions.metadata?: JsonNode- Optional metadataoptions.changeDescription?: string- Version change descriptionoptions.tags?: string[]- Optional tags
Returns: Promise<Prompt> - Created or existing prompt
getPrompt(options)
Section titled “getPrompt(options)”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
searchPrompts(filterString?)
Section titled “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 fieldstags: List field (use "contains" operator)
Operators: =, !=, contains, not_contains, starts_with, ends_with, >, <
deletePrompts(ids)
Section titled “deletePrompts(ids)”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 updateoptions.tags?: string[] | null- Tags to set or merge:[]– clears all tags (whenmergeTagsis false or unspecified)['tag1', 'tag2']– sets or merges tags (based onmergeTags)null/ omitted – preserves existing tags unchanged
options.mergeTags?: boolean– Iftrue, adds new tags to existing tags (union). Iffalse(default), replaces all existing tags.
Returns: Promise<void>
Examples:
// 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: [],
});createChatPrompt(options)
Section titled “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 IDoptions.description?: string- Optional descriptionoptions.metadata?: JsonNode- Optional metadataoptions.changeDescription?: string- Version change descriptionoptions.tags?: string[]- Optional tags
Returns: Promise<ChatPrompt> - Created or existing chat prompt
ChatMessage Format:
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
}getChatPrompt(options)
Section titled “getChatPrompt(options)”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
Prompt Class
Section titled “Prompt Class”Methods
Section titled “Methods”format(variables)
Section titled “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?)
Section titled “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 descriptionoptions.filters?: string- JSON-encoded filter array. Each entry is{ field, operator, value }.options.sorting?: string- JSON-encoded sort array. Each entry is{ field, direction }wheredirectionis"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:
// 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" }]),
});getVersion(version)
Section titled “getVersion(version)”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
// Preferred: fetch by sequential version identifier
const v3 = await prompt.getVersion("v3");
// Deprecated: fetch by commit hash
const byCommit = await prompt.getVersion("abc123de");useVersion(version)
Section titled “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)
Section titled “updateProperties(updates)”Updates prompt properties without creating new version.
Arguments:
updates.name?: string- New prompt nameupdates.description?: string- New descriptionupdates.tags?: string[]- New tags array
Returns: Promise<this> - This prompt instance (for chaining)
delete()
Section titled “delete()”Deletes this prompt and all its versions.
Returns: Promise<void>
Properties
Section titled “Properties”id: string- Unique prompt identifiername: string- Prompt nameprompt: string- Current template contentversion?: string- Sequential version identifier (e.g."v3")type: PromptType- Template engine typedescription?: string- Prompt descriptiontags?: readonly string[]- Prompt tagsmetadata?: JsonNode- Prompt metadatachangeDescription?: string- Latest version change description
PromptVersion Class
Section titled “PromptVersion Class”Methods
Section titled “Methods”format(variables)
Section titled “format(variables)”Formats this version's template with provided variables.
Arguments:
variables: Record<string, unknown>- Variables to substitute
Returns: string - Formatted prompt text
getVersionInfo()
Section titled “getVersionInfo()”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"
getVersionAge()
Section titled “getVersionAge()”Gets human-readable version age.
Returns: string - Format: "2 days ago", "Today", etc.
compareTo(other)
Section titled “compareTo(other)”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
Properties
Section titled “Properties”id: string- Version unique identifiername: string- Associated prompt nameprompt: string- Template content for this versionversion?: string- Sequential version identifier (e.g."v3")type: PromptType- Template engine typetags?: string[]- Tags associated with this versionmetadata?: JsonNode- Version metadatachangeDescription?: string- Version change descriptioncreatedAt?: Date- Creation timestampcreatedBy?: string- Creator identifier
ChatPrompt Class
Section titled “ChatPrompt Class”The ChatPrompt class extends BasePrompt and provides chat-specific functionality for managing structured message-based prompts.
Methods
Section titled “Methods”format(variables, supportedModalities?)
Section titled “format(variables, supportedModalities?)”Formats the chat prompt messages with provided variables.
Arguments:
variables: Record<string, unknown>- Variables to substitute in message contentsupportedModalities?: SupportedModalities- Optional modality support configuration
SupportedModalities Format:
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:
const formatted = chatPrompt.format(
{ name: "Alice", topic: "AI" },
{ vision: true, video: false },
);getVersions(options?)
Section titled “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 descriptionoptions.sorting?: string- Sort expressionoptions.filters?: string- JSON-encoded filter array (same format asPrompt.getVersions)
Returns: Promise<PromptVersion[]> - Array of all matching versions (newest first)
getVersion(version)
Section titled “getVersion(version)”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
// Preferred: fetch by sequential version identifier
const v3 = await chatPrompt.getVersion("v3");
// Deprecated: fetch by commit hash
const byCommit = await chatPrompt.getVersion("abc123de");useVersion(version)
Section titled “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)
Section titled “updateProperties(updates)”Updates chat prompt properties without creating new version.
Arguments:
updates.name?: string- New prompt nameupdates.description?: string- New descriptionupdates.tags?: string[]- New tags array
Returns: Promise<this> - This chat prompt instance (for chaining)
delete()
Section titled “delete()”Deletes this chat prompt and all its versions.
Returns: Promise<void>
Properties
Section titled “Properties”id: string- Unique chat prompt identifiername: string- Chat prompt namemessages: ChatMessage[]- Array of chat messages with roles and contentversion?: string- Sequential version identifier (e.g."v3")type: PromptType- Template engine typedescription?: string- Chat prompt descriptiontags?: readonly string[]- Chat prompt tagsmetadata?: JsonNode- Chat prompt metadatachangeDescription?: string- Latest version change description