aiMessage
Build AI message structures fluently using a chainable API. Supports multiple roles (system, user, assistant, tool), template interpolation, and seamless integration with chat requests and pipelines.
Syntax
aiMessage(message)Parameters
message
any
No
null
Initial message to add. Can be a string, struct, array, or AiMessage object
Message Format
Messages can be:
String: Added as a user message
Struct: With
roleandcontentkeys (e.g.,{ role: "user", content: "Hello" })Array: Array of message structs
AiMessage: Returns as-is (idempotent)
Returns
Returns an AiMessage object with fluent API for:
Adding messages:
system(),user(),assistant(),tool()Building conversations: Chaining multiple role methods
Template support: Variable interpolation with
${var}syntaxPipeline integration:
to(),toDefaultModel(),transform()Running:
run(),stream()for direct execution
Examples
Basic Message Creation
System Instructions
Multi-Turn Conversation
Template Interpolation
Pipeline Integration
Streaming Messages
Tool Messages
Dynamic Message Building
Role-Based Messages
Reusable Templates
Transformation Chains
Multi-Modal Messages
Conversation Context
Inspect Messages
Custom Providers
Advanced Pipeline
Notes
🔗 Fluent API: All role methods return the message object for chaining
🎨 Templates: Use
${variable}for dynamic content interpolation🔄 Reusable: Message objects are reusable across multiple requests
🎯 Type Safe: Automatic validation of message structure
🚀 Pipeline Ready: Seamlessly integrates with
aiModel()andaiTransform()📝 Dynamic Roles: Uses
onMissingMethodfor flexible role names🎪 Events: Fires
onAIMessageCreateevent for interceptors
Related Functions
aiChat()- Send messages to AI providersaiChatRequest()- Build complete request objectsaiModel()- Create model runnables for pipelinesaiTransform()- Transform message outputsaiAgent()- Create agents with message handling
Best Practices
✅ Use system messages - Set behavior and context upfront
✅ Template reusable prompts - Create templates with ${vars} for flexibility
✅ Chain fluently - Build complex messages in one expression
✅ Maintain conversation - Keep message history for multi-turn chats
✅ Use pipelines - Combine with toDefaultModel() for reusable workflows
❌ Don't nest messages - Keep message structure flat (one level of role/content)
❌ Don't mutate shared messages - Clone before modifying reused templates
❌ Don't overload system - Keep system message concise and focused
Last updated