Message Templates

Build reusable, dynamic prompts with placeholders that get filled in at runtime. Message templates are the foundation of flexible AI pipelines.

Build reusable, dynamic prompts with placeholders that get filled in at runtime. Message templates are the foundation of flexible AI pipelines.

🚀 Creating Messages

Use aiMessage() to build structured messages:

🏗️ Message Template Architecture

Basic Message

message = aiMessage()
    .user( "Hello, world!" )

messages = message.run()
// [{ role: "user", content: "Hello, world!" }]

Multiple Messages

message = aiMessage()
    .system( "You are a helpful assistant" )
    .user( "What is BoxLang?" )
    .assistant( "BoxLang is a modern JVM language" )
    .user( "Tell me more" )

messages = message.run()

Message Roles

  • system: Sets AI behavior/personality

  • user: Your messages/questions

  • assistant: AI responses (for conversation history)

🔤 Template Placeholders

Use ${key} syntax for dynamic values:

🔄 Placeholder Binding Flow

Simple Placeholder

Multiple Placeholders

Complex Templates

🎯 Binding Strategies

Runtime Bindings

Pass bindings when running:

Stored Bindings

Pre-bind values with .bind():

Binding Precedence

Runtime bindings override stored bindings:

Merging Bindings

Bindings merge at each level:

📦 Message Context

Beyond simple placeholder bindings, you can inject rich contextual data like security information, RAG documents, or application metadata using the message context system.

🔄 Context Injection Flow

The ${context} Placeholder

Use the special ${context} placeholder to inject contextual data that gets JSON-serialized:

Context Methods

RAG with Context

Perfect for Retrieval Augmented Generation:

Security Context

Inject user and tenant information securely:

📖 Full Message Context Documentation - Learn about multi-tenant patterns, RAG implementation, context with agents, and best practices.


Messages in Pipelines

Basic Pipeline

Reusable Template

Multi-Step Templates

Pipeline Options

Messages in pipelines support the options parameter for controlling runtime behavior.

Setting Default Options

Runtime Options Override

Convenience Methods

For return format, use convenience methods:

Available Options

  • returnFormat:string - "raw" (default), "single", or "all"

  • timeout:numeric - Request timeout in seconds

  • logRequest:boolean - Log requests to ai.log

  • logRequestToConsole:boolean - Log requests to console

  • logResponse:boolean - Log responses to ai.log

  • logResponseToConsole:boolean - Log responses to console

  • provider:string - Override AI provider

  • apiKey:string - Override API key

Advanced Features

Rendering Templates

Get formatted messages without running through AI:

Named Messages

History

Use history() to inflate an AiMessage with a prior conversation. This accepts either an array of message structs or another AiMessage instance. Each message is appended to the current message list in order.

Signature:

Behavior highlights:

  • If passed an AiMessage, its internal messages are extracted and appended.

  • If passed an array, each element (struct) is added via the normal .add() flow.

  • The method will throw an error when passed anything other than an array or AiMessage.

  • History can be chained fluently with other message methods.

Examples:

Images

Add images to messages for vision-capable AI models like GPT-4 Vision, Claude 3, or Gemini.

Image URLs

Use image() to add an image by URL:

Embedded Images

Use embedImage() to read a local file and embed it as base64:

Multiple Images

Add multiple images to compare or analyze together:

Detail Levels

Control image processing with the detail parameter:

  • auto (default): Model chooses based on image and task

  • low: 512x512 resolution, faster and cheaper

  • high: Full detail, better for complex images

Practical Examples

Image Analysis Pipeline

Document Scanner

Multi-Image Comparison

Vision-Based Content Generation

Note: Image support requires vision-capable AI models. Check your provider's documentation for supported models and pricing.

Audio

Add audio files to messages for AI models that support audio processing.

Supported by: OpenAI (GPT-4o-audio-preview), Gemini (1.5+, 2.0)

Formats: mp3, mp4, mpeg, mpga, m4a, wav, webm

Audio URLs

Embedded Audio

Audio Analysis Pipeline

Video

Add video files to messages for AI models with video understanding capabilities.

Supported by: Gemini (gemini-1.5-pro, gemini-2.0-flash)

Formats: mp4, mpeg, mov, avi, flv, mpg, webm, wmv

Video URLs

Embedded Videos

Video Analysis Pipeline

Documents and PDFs

Add documents and PDFs to messages for AI models that support document understanding.

Supported by: Claude (Opus, Sonnet), OpenAI (GPT-4o)

Formats: pdf, doc, docx, txt, xls, xlsx

Document URLs

Embedded Documents

Document Analysis Pipeline

Mixed Multimodal Content

Combine multiple media types in a single message:

Multimodal Provider Support

Feature
OpenAI
Claude
Gemini

Images

✅ GPT-4o, GPT-4-turbo

✅ Claude 3+

✅ All vision models

Audio

✅ GPT-4o-audio

✅ Gemini 1.5+, 2.0

Video

✅ Gemini 1.5+, 2.0

Documents

✅ GPT-4o

✅ Claude 3+

⚠️ Via OCR

Important Notes:

  • File Size Limits: Images (20MB), Audio (25MB for OpenAI), Video (2GB for Gemini), Documents (~10MB inline)

  • Large Files: For files >10MB, consider using provider-specific file upload APIs

  • Base64 Inline: All embed* methods use base64 inline encoding for simplicity

  • Context Limits: Large media files consume significant context tokens

Streaming Messages

Messages can stream their content:

Practical Examples

FAQ Template

Code Generator

Translation Pipeline

Context-Aware Assistant

Multi-Language Support

Tips and Best Practices

  1. Use Descriptive Names: ${userId} not ${id}

  2. Provide Defaults: Use .bind() for common values

  3. Document Templates: Comment placeholder meanings

  4. Validate Inputs: Check required bindings exist

  5. Escape Special Chars: Handle user input safely

  6. Version Templates: Track changes to prompts

  7. Test Variations: Try different wording

Template Library Pattern

Next Steps

Last updated