Skip to main content

Building Prompts

PromptSmith provides a fluent API for building type-safe system prompts. This guide walks you through creating prompts from basic to advanced configurations.

Installation

First, install PromptSmith and its peer dependencies:
npm install promptsmith-ts zod ai

Basic Structure

Every prompt starts with the createPromptBuilder() factory function and follows a fluent, chainable API pattern.
1
Create a Builder Instance
2
Start by importing and creating a builder:
3
import { createPromptBuilder } from 'promptsmith-ts/builder';

const builder = createPromptBuilder();
4
Define the Agent’s Identity
5
The identity establishes who or what your agent is. This appears first in the generated prompt and frames all subsequent instructions.
6
const builder = createPromptBuilder()
  .withIdentity('You are an expert travel assistant specializing in European destinations');
7
Write identities in second person (“You are…”) for clarity. Be specific about the agent’s expertise and domain.
8
Add Capabilities
9
Capabilities define what your agent can do. Add them one at a time or in bulk:
10
const builder = createPromptBuilder()
  .withIdentity('You are a financial analysis assistant')
  .withCapabilities([
    'Analyze financial statements and identify trends',
    'Calculate investment returns and risk metrics',
    'Generate detailed financial reports',
    'Compare performance across different time periods'
  ]);
11
Build the Prompt
12
Generate the final prompt string with .build():
13
const prompt = builder.build();

console.log(prompt);
// # Identity
// You are a financial analysis assistant
//
// # Capabilities
// 1. Analyze financial statements and identify trends
// 2. Calculate investment returns and risk metrics
// 3. Generate detailed financial reports
// 4. Compare performance across different time periods

Adding Context

Provide domain-specific background knowledge that helps your agent understand its operating environment:
const builder = createPromptBuilder()
  .withIdentity('You are a medical appointment scheduler')
  .withContext(`
Our clinic operates Monday-Friday, 9 AM to 5 PM.
We have three doctors:
- Dr. Smith (general medicine, 30-min appointments)
- Dr. Jones (cardiology, 45-min appointments)
- Dr. Lee (pediatrics, 30-min appointments)

Emergency appointments can be accommodated with 24-hour notice.
Standard appointments require 48-hour notice for cancellation.
  `);
Context differs from identity (who the agent is) and capabilities (what it can do). Context is what the agent needs to know about its domain.

Setting Communication Tone

Define how your agent should communicate:
const builder = createPromptBuilder()
  .withIdentity('You are a customer support assistant')
  .withTone('Be empathetic and patient. Use a warm, conversational tone. Acknowledge user frustration and always end responses positively.');

Defining Output Format

Specify how responses should be structured:
const builder = createPromptBuilder()
  .withIdentity('You are a technical troubleshooting assistant')
  .withOutput(`
Structure all responses in this format:
1. **Problem Summary**: Brief restatement of the issue (1-2 sentences)
2. **Diagnosis**: What's likely causing the problem
3. **Solution Steps**: Numbered, actionable steps to resolve
4. **Prevention**: How to avoid this in the future

Use code blocks for commands or configuration snippets.
  `);

Real-World Example: E-Commerce Assistant

Here’s a complete example combining all elements:
import { createPromptBuilder } from 'promptsmith-ts/builder';

const ecommerceAssistant = createPromptBuilder()
  .withIdentity(
    'You are a knowledgeable e-commerce assistant for TechGear, '
    'an online retailer specializing in consumer electronics'
  )
  .withCapabilities([
    'Help customers find products matching their needs',
    'Answer questions about product specifications',
    'Explain shipping options and delivery times',
    'Assist with order tracking and status inquiries',
    'Process return and exchange requests',
  ])
  .withContext(`
Store Information:
- Free shipping on orders over $50
- Standard delivery: 3-5 business days
- Express delivery: 1-2 business days (additional fee)
- 30-day return policy for all items
- Extended warranty available for purchase
- Customer service available 24/7

Product Categories:
- Laptops & Computers
- Smartphones & Tablets
- Audio Equipment
- Smart Home Devices
- Gaming Accessories
  `)
  .withTone(
    'Be friendly, helpful, and enthusiastic about our products. '
    'Use clear, jargon-free language. Always prioritize customer satisfaction.'
  )
  .withOutput(
    'Keep responses concise but complete. Use bullet points for lists. '
    'Include relevant product links when recommending items.'
  )
  .build();

// Use with your AI provider
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

const response = await generateText({
  model: openai('gpt-4'),
  system: ecommerceAssistant,
  prompt: 'I need a laptop for video editing under $1500'
});

Method Chaining Pattern

All builder methods return this, enabling fluent chaining:
const builder = createPromptBuilder()
  .withIdentity('You are a code review assistant')
  .withCapability('Identify potential bugs and security issues')
  .withCapability('Suggest performance optimizations')
  .withCapability('Recommend better design patterns')
  .withTone('Be constructive and educational, not critical')
  .withOutput('Provide specific file paths and line numbers with suggestions');

Inspecting Your Configuration

Use .getSummary() to inspect the builder’s current state:
const builder = createPromptBuilder()
  .withIdentity('Assistant')
  .withCapabilities(['Answer questions', 'Provide help']);

const summary = builder.getSummary();
console.log(summary);
// {
//   hasIdentity: true,
//   capabilitiesCount: 2,
//   toolsCount: 0,
//   constraintsCount: 0,
//   examplesCount: 0,
//   hasGuardrails: false,
//   forbiddenTopicsCount: 0,
//   hasContext: false,
//   hasTone: false,
//   hasOutputFormat: false,
//   hasErrorHandling: false,
//   format: 'markdown'
// }
Use .debug() for detailed diagnostic information including validation warnings and size estimates:
builder.debug();
// Logs comprehensive builder state to console

Common Pitfalls

Empty Builder: Calling .build() on an empty builder returns an empty string. Always set at least an identity.
// ❌ Bad
const prompt = createPromptBuilder().build(); // ""

// ✅ Good
const prompt = createPromptBuilder()
  .withIdentity('You are a helpful assistant')
  .build();
Overwriting Identity: Calling .withIdentity() multiple times replaces the previous value:
const builder = createPromptBuilder()
  .withIdentity('First identity')   // This is lost
  .withIdentity('Second identity'); // This is kept

Best Practices

  1. Start Simple: Begin with identity and a few capabilities, then iterate
  2. Be Specific: Vague identities and capabilities lead to unpredictable behavior
  3. Use Context Wisely: Include facts and rules, not opinions or examples (use .withExamples() for those)
  4. Test Iteratively: Build incrementally and test after each major addition
  5. Validate Configuration: Use .validate() to catch issues before deployment

Next Steps

Tool Integration

Learn how to add executable tools with Zod schemas

Security Guardrails

Protect your agent from prompt injection attacks

Testing Prompts

Validate prompt behavior with PromptTester

Token Optimization

Reduce costs with TOON format

Build docs developers (and LLMs) love