Chat Output and Multi-Modal Messages
Kaya's special handling of chat-style IO streams
Overview
Kaya programs can output messages to a chat interface in multiple ways:
- Bare strings: Simple text output to chat
- Speaker-prefixed strings: Messages from specific speakers/roles
- Multi-modal messages: Text combined with images using the
| imagefilter
All chat output is automatically tracked in the conversation history and can be used by subsequent LLM calls.
The basic text examples need no model provider. Examples that generate images or call a model require the corresponding native binding and session grant; see Configuration. File examples need their named resources.
Bare Strings (Echo Statements)
Basic Syntax
The simplest way to output to chat is with a bare string:
"Hello, world!"This creates an assistant message in the chat with the content "Hello, world!".
With Template Interpolation
Strings support template variable interpolation:
let name = "Alice"
let temp = 30
"Hi {{name}}! It's {{temp}} degrees today."Output: "Hi Alice! It's 30 degrees today."
Multiple Messages
Each bare string creates a separate chat message:
"First message"
"Second message"
"Third message"This creates three separate assistant messages in the chat.
Speaker-Prefixed Strings
Syntax
Prefix a string with [speaker] to specify who is speaking:
[user] "What is AI?"
[assistant] "AI stands for Artificial Intelligence."
[system] "You are a helpful assistant."Special Speaker Roles
Three speaker names map directly to LLM message roles:
[system] - System role:
[system] "You are a professional translator."
[system] "Always respond in French."[user] - User role:
[user] "What is the weather today?"
[user] "Tell me about quantum computing."[assistant] - Assistant role (explicit):
[assistant] "The weather is sunny."
[assistant] "Quantum computing uses quantum mechanics..."Note: Bare strings without a speaker prefix default to [assistant] role.
Named Speakers
Any other speaker name produces an assistant message that carries the
speaker as from.name:
[alice] "Hi there!"
[bob] "Hello, Alice!"
[narrator] "The two friends met in the park."All three produce role: "assistant" messages with from: {name: "alice"}
(etc.) attached, so the speaker survives into the chat history and UI.
Multi-Modal Messages with Images
The | image Filter
Use the | image filter to embed images in chat messages:
let photo = generateImage(prompt: "A sunset over mountains")
"Here's the sunset: {{photo | image}}"This creates a multi-part message containing both text and the image.
How It Works
The | image filter:
- Marks a variable as an image to be embedded
- Reads the file path from the variable
- Creates a multi-part message with text and image content
- Sends both to the chat interface
Technical details:
- Works with string variables containing a file path, and with file objects (from
generateImage(),save(), etc.) - Supports multiple images in one message
- Compatible with vision-capable LLMs
- Creates proper multi-part content structure
| imageis not a regular Liquid filter — it is pre-processing applied to the message template (the runtime splits the string on{{var | image}}boundaries). Because the match is exact,| imagemust be the only filter in its expression:{{photo | image}}works; chains like{{photo | upcase | image}}are not recognized and render as text.
Multiple Images
Include multiple images in a single message:
let img1 = generateImage(prompt: "Cat")
let img2 = generateImage(prompt: "Dog")
"Compare these: {{img1 | image}} vs {{img2 | image}}"This creates one message with two images embedded.
With Speakers
Combine speaker prefixes with images:
let screenshot = "screenshot.png"
[user] "What do you see in {{screenshot | image}}?"Vision Workflows
The | image filter enables vision workflows:
// User provides an image
let userPhoto = "input.jpg"
[user] "Analyze this photo: {{userPhoto | image}}"
// Generate analysis
let analysis = generate(
message: "What's in the image?",
model: "claude-3-5-sonnet-20241022"
)
[assistant] "{{analysis}}"
// Create a modified version
let enhanced = generateImage(
prompt: "Enhanced version of: {{analysis}}"
)
[assistant] "Here's an enhanced version: {{enhanced | image}}"Template Filters (Liquid Syntax)
Kaya supports Liquid-style filters for formatting values in templates:
Common Filters
json - Convert to JSON string:
let user = {name: "Alice", age: 30}
"User data: {{user | json}}"Output: User data: {"name":"Alice","age":30}
upcase - Convert to uppercase:
let name = "alice"
"Hello, {{name | upcase}}!"Output: Hello, ALICE!
downcase - Convert to lowercase:
let name = "ALICE"
"Hello, {{name | downcase}}!"Output: Hello, alice!
image - Embed image (special, multi-modal):
let photo = "sunset.png"
"Look: {{photo | image}}"Creates a multi-part message with the image.
Filter Chaining
Regular Liquid filters can be chained (where it makes sense):
let data = {value: 42}
"Data: {{data | json | upcase}}"Exception: | image cannot be chained at all — it must be the sole filter in its expression ({{photo | image}}). It is implemented as message pre-processing, not as a Liquid filter, and chained forms are simply not recognized.
Chat Message Structure
Simple Text Message
"Hello, world!"Creates:
{
"role": "assistant",
"content": "Hello, world!"
}Named Speaker Message
[alice] "Hi there!"Creates:
{
"role": "assistant",
"content": "Hi there!"
}The speaker name alice is dropped — see Named Speakers above.
Multi-Part Message with Images
"Here's a photo: {{photo | image}}"Creates an AI-SDK-shaped multi-part message:
{
"role": "assistant",
"content": [
{"type": "text", "text": "Here's a photo:"},
{"type": "image", "image": "<published URL or base64 data>", "mediaType": "image/png"}
]
}The image part carries either a published URL or base64-encoded data depending on the runtime's image output mode (images are resized before base64 encoding to limit token usage). Text segments that are empty or whitespace-only after rendering are stripped — there is no trailing empty text part.
Advanced Patterns
Conversation Simulation
[user] "What is 2 + 2?"
[assistant] "2 + 2 equals 4."
[user] "Can you show me visually?"
let diagram = generateImage(prompt: "Math diagram showing 2 + 2 = 4")
[assistant] "Here's a visual explanation: {{diagram | image}}"Multi-Step Vision Analysis
// Initial image
let original = "photo.jpg"
[user] "Analyze this: {{original | image}}"
// Generate analysis
let analysis = generate(message: "Describe the image in detail")
[assistant] "{{analysis}}"
// Create variations
let variation1 = generateImage(prompt: "{{analysis}} in watercolor style")
let variation2 = generateImage(prompt: "{{analysis}} in cartoon style")
[assistant] "Here are two artistic interpretations:"
[assistant] "Watercolor: {{variation1 | image}}"
[assistant] "Cartoon: {{variation2 | image}}"System Instructions with Context
[system] "You are a professional art critic."
[system] "Focus on composition, color, and technique."
let artwork = "painting.jpg"
[user] "Critique this painting: {{artwork | image}}"
let critique = generate(message: "Provide detailed critique")
[assistant] "{{critique}}"Iterative Image Generation
for i in range(3) {
let image = generateImage(
prompt: "Abstract art, attempt {{i + 1}}"
)
[assistant] "Attempt {{i + 1}}: {{image | image}}"
// generate() returns a string — coerce before comparing numerically
let feedback = generate(
message: "Rate this artwork from 1-10. Answer with just the number: {{image | image}}"
)
let rating = feedback as number
if rating > 8 {
"Found a great one!"
break
}
}Best Practices
1. Use Appropriate Roles
Match speaker roles to the message content:
[system]for instructions and context[user]for user input or questions[assistant](or bare strings) for responses
2. Image File Paths
Ensure image variables contain valid file paths:
// ✓ Good
let photo = generateImage(prompt: "sunset")
"Photo: {{photo | image}}"
// ✗ Bad - variable doesn't exist
"Photo: {{nonExistent | image}}"3. Vision Model Compatibility
Use vision-capable models when sending images:
let screenshot = "screen.png"
[user] "What's this? {{screenshot | image}}"
// Use a vision model
let analysis = generate(
message: "Analyze the image",
model: "claude-3-5-sonnet-20241022" // Vision-capable
)4. Text Summaries with Images
When using images, include descriptive text:
// ✓ Good - descriptive text
"Here's the sunset photo I generated: {{photo | image}}"
// ✗ Less clear
"{{photo | image}}"5. Organize Multi-Image Messages
For multiple images, structure them clearly:
"Comparison of three styles:"
[assistant] "Original: {{img1 | image}}"
[assistant] "Enhanced: {{img2 | image}}"
[assistant] "Artistic: {{img3 | image}}"Common Pitfalls
1. Forgetting the | image Filter
// ✗ Wrong - sends file path as text
"Photo: {{photo}}"
// ✓ Correct - embeds image
"Photo: {{photo | image}}"2. Using Images Without Vision Models
// ✗ May fail - non-vision model
[user] "What's this? {{img | image}}"
let result = generate(
message: "Analyze it",
model: "gpt-3.5-turbo" // Not vision-capable
)
// ✓ Works - vision model
let result = generate(
message: "Analyze it",
model: "gpt-4-vision"
)3. Template Syntax in Wrong Places
// ✗ Wrong - templates only belong inside strings (parse error):
// let name = {{userName}}
// ✓ Correct
let name = userName // Variable reference
"Hello, {{userName}}" // Template in stringSystem Logging and Timers vs. Chat Output
While bare strings and speaker-prefixed strings create user-facing chat messages that populate the chat feed and conversation history, developers often need to log internal diagnostics or measure performance without cluttering the chat window. For that, use the stdlib log.* (system logging) and time.* (stopwatch) namespaces — neither writes to chat.
log.info(message: "Started book rendering pipeline") // system log only, never in chat
time.info(label: "render-pdf", message: "Starting") // toggle stopwatch under a labelThese functions are specified in the Standard Library Reference.
Debugging Chat Output
Check Message History
The chat history is accessible in the context:
// Messages accumulate in context.chat.messages
"First message"
"Second message"
// Both messages are now in the chat historySilent vs. Chat Generation
Control whether generate() adds to chat. Silent is the default — generate() only writes to chat history when you pass chat: true:
// Silent (default) - doesn't add to chat
let analysis = generate(
message: "Analyze data"
)
// Opt in to chat history
let response = generate(
message: "Hello",
chat: true
)Saving Chat Output to Files
You can save chat messages to files using the save() function:
// Generate and save
let response = generate(message: "Write a report")
[assistant] "{{response}}"
save(content: response, filename: "report.txt")
// Save multi-part conversation
"Starting analysis..."
let analysis = generate(message: "Analyze data")
[assistant] "{{analysis}}"
let summary = "Analysis complete:\n{{analysis}}"
save(content: summary, filename: "analysis.txt")See Also
- Generating Text - Prompts and conversation history
- Generating Images - Image generation and variations
- Syntax Basics - Template interpolation and expressions
- Standard Library - Complete stdlib reference including save(), load(), copyFile()
- Syntax Reference - Echo statement formal syntax