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
${context} PlaceholderUse 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 secondslogRequest:boolean- Log requests toai.loglogRequestToConsole:boolean- Log requests to consolelogResponse:boolean- Log responses toai.loglogResponseToConsole:boolean- Log responses to consoleprovider:string- Override AI providerapiKey: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 tasklow: 512x512 resolution, faster and cheaperhigh: 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
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 simplicityContext 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
Use Descriptive Names:
${userId}not${id}Provide Defaults: Use
.bind()for common valuesDocument Templates: Comment placeholder meanings
Validate Inputs: Check required bindings exist
Escape Special Chars: Handle user input safely
Version Templates: Track changes to prompts
Test Variations: Try different wording
Template Library Pattern
Next Steps
Working with Models - Connect templates to AI
Message Context - Inject security and RAG data into messages
Transformers - Process responses
Pipeline Streaming - Real-time template execution
Last updated