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

Parameter
Type
Required
Default
Description

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 role and content keys (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} syntax

  • Pipeline 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() and aiTransform()

  • 📝 Dynamic Roles: Uses onMissingMethod for flexible role names

  • 🎪 Events: Fires onAIMessageCreate event for interceptors

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