🔐Message Context

The BoxLang AI module provides a powerful context system for AI messages that allows you to inject security information, RAG (Retrieval Augmented Generation) data, and other contextual information into your AI operations.

📋 Table of Contents


🔍 Overview

The context system provides a way to inject contextual data into AI messages:

  • Security context: User roles, permissions, tenant IDs, authentication tokens

  • RAG context: Retrieved documents, embeddings, search results

  • Application context: Request metadata, session info, environment data

The ${context} placeholder in messages is automatically replaced with JSON-serialized context data.


🚀 Using Context with aiChat()

The simplest way to use context is directly with aiChat():

The ${context} placeholder is replaced with the JSON-serialized context data before sending to the AI provider.

Without Placeholder

If you don't use ${context} in your message, the context is still available for interceptors but won't be automatically injected:


📝 Using Context with AiMessage

For more control, use AiMessage directly with fluent context methods:

Fluent API

Set Entire Context

Access Context

With System Messages


🔄 Using Context with Runnable Pipelines

Context works seamlessly with AiModel in runnable pipelines:

Direct Model Invocation

Pipeline with Context

With AiMessage in Pipelines


🤖 Using Context with Agents

Context is fully supported in AI agents:

Basic Agent with Context

Agent with RAG Context

Agent Streaming with Context


💡 Common Use Cases

1. RAG (Retrieval Augmented Generation)

2. Secure Multi-Tenant Application

3. Contextual Customer Support with Agent


✅ Best Practices

1. Don't Send Sensitive Data to AI

Context is sent to the AI provider. Be careful what gets injected:

2. Keep Context Lightweight

Don't overload context with large data:

3. Use Typed Context Keys

Establish conventions for context keys:



Copyright © 2023-2025 Ortus Solutions, Corp

Last updated