For the complete documentation index, see llms.txt. This page is also available as Markdown.

πŸ”Message Context

Inject security information, RAG data, and other contextual information into your AI messages.

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.

πŸ” 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():

// Pass context in options
response = aiChat(
    "You are an assistant. User context: ${context}. Help the user.",
    {},
    {
        context: {
            userId: "user-123",
            role: "admin",
            permissions: ["read", "write"]
        }
    }
);

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)

Retrieved documents are untrusted content β€” the ${context} binding above is fenced automatically by default (security.fencing.enabled), so the model treats it as data rather than instructions. See the Security Guide (Layer 3: Fencing).

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