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

A prompt in Opik is a versioned template with variables that can be formatted at runtime. 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

Creating Your First Prompt

Create a 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"
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);

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"');

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

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()

Retrieves all version history for this prompt.

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

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 hash
  • 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 hash
  • type: PromptType - Template engine type
  • metadata?: JsonNode - Version metadata
  • changeDescription?: string - Version change description
  • createdAt?: Date - Creation timestamp
  • createdBy?: string - Creator identifier