Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Guardrails ai Guardrails Messages

From Leeroopedia
Knowledge Sources
Domains Prompt Engineering, LLM Integration
Last Updated 2026-02-14 00:00 GMT

Overview

The Messages class represents a sequence of role-based chat messages for LLM interactions, supporting constant substitution, schema injection, and template formatting.

Description

Messages wraps a list of message dictionaries (each with role and content keys) and provides the same constant-substitution and output-schema-injection behavior as the prompt classes. On initialization, it iterates through messages, substituting ${gr.<constant_name>} patterns in string content and optionally injecting output schema references. The class implements the iterator protocol (__iter__, __next__) for iterating over messages. The format method accepts keyword arguments and applies Template.safe_substitute to each message's content, filtering keywords to only those that appear as template variables in that message. Content values can be raw strings or Prompt/Instructions instances.

Usage

Use this class when building multi-message chat prompts for LLM calls (e.g., system + user messages). It is used internally by the Guard class when messages-based prompt specifications are provided, and it handles template variable formatting across all messages in the sequence.

Code Reference

Source Location

  • Repository: Guardrails
  • File: guardrails/prompt/messages.py

Signature

class Messages:
    def __init__(
        self,
        source: List[Dict[str, Union[str, Prompt, Instructions]]],
        output_schema: Optional[str] = None,
        *,
        xml_output_schema: Optional[str] = None,
    )

    def __iter__(self) -> "Messages"
    def __next__(self) -> Dict[str, Union[str, Prompt, Instructions]]

    def format(self, **kwargs) -> "Messages"
    def substitute_constants(self, text: str) -> str

Import

from guardrails.prompt.messages import Messages

I/O Contract

__init__

Parameter Type Description
source List[Dict[str, Union[str, Prompt, Instructions]]] List of message dictionaries with role and content keys
output_schema Optional[str] JSON Schema string to substitute into $output_schema placeholders in message content
xml_output_schema Optional[str] XML Schema string to substitute into $xml_output_schema placeholders (keyword-only)

format

Parameter Type Description
**kwargs Any Keyword arguments to substitute into message templates; only keys matching template variables in each message are used
Returns Type Description
Formatted messages Messages A new Messages instance with all template variables substituted across all messages

substitute_constants

Parameter Type Description
text str Text containing ${gr.<constant_name>} patterns
Returns Type Description
Substituted text str Text with all Guardrails constants replaced by their values

Usage Examples

from guardrails.prompt.messages import Messages

# Create a chat-style message sequence with template variables
messages = Messages(
    source=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Extract ${entity_type} from: ${text}"},
    ]
)

# Format with keyword arguments
formatted = messages.format(entity_type="names", text="Alice met Bob at the park.")
for msg in formatted:
    print(f"{msg['role']}: {msg['content']}")
# system: You are a helpful assistant.
# user: Extract names from: Alice met Bob at the park.

# With output schema injection
messages_with_schema = Messages(
    source=[
        {"role": "system", "content": "Respond according to: $output_schema"},
        {"role": "user", "content": "Generate a person record."},
    ],
    output_schema='{"type": "object", "properties": {"name": {"type": "string"}}}'
)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment