# LionAGI Communication System API Reference
## Overview
The Communication System provides the messaging infrastructure for LionAGI, handling structured messages, conversation management, and message routing with type safety and resource management.
## Core Types
### MessageRole
```python
class MessageRole(str, Enum):
```
Defines possible roles for messages in the system.
**Values:**
- `SYSTEM`: System-level messages providing context
- `USER`: Messages from users providing input
- `ASSISTANT`: Messages from AI assistants
### MessageFlag
```python
class MessageFlag(str, Enum):
```
Internal flags for message construction.
**Values:**
- `MESSAGE_CLONE`: Signal for message cloning
- `MESSAGE_LOAD`: Signal for message loading
> [!note] Flag Usage
> These flags are used internally by the system for message lifecycle management. You typically won't need to use them directly.
## Base Classes
### BaseMail
```python
class BaseMail(Element, Communicatable):
```
Base class for all message-based communication.
**Attributes:**
- `sender: ID.SenderRecipient` - Message sender ID or role
- `recipient: ID.SenderRecipient` - Message recipient ID or role
**Methods:**
#### `__init__`
```python
def __init__(self, **kwargs) -> None
```
Initialize base mail object.
> [!important] Validation
> Both sender and recipient are validated to ensure they are valid system roles or IDs.
### RoledMessage
```python
class RoledMessage(Component, BaseMail):
```
Base class for role-based messages.
**Attributes:**
- `content: Note` - Message content
- `role: MessageRole` - Message role
- `metadata: Note` - Additional metadata
**Properties:**
#### `image_content`
```python
@property
def image_content(self) -> list[dict[str, Any]] | None
```
Get image content if present.
#### `chat_msg`
```python
@property
def chat_msg(self) -> dict[str, Any] | None
```
Get message in chat format.
**Methods:**
#### `clone`
```python
def clone(self) -> RoledMessage
```
Create a copy with new identity.
#### `to_log`
```python
def to_log(self) -> Log
```
Convert to log entry.
## Message Manager
### MessageManager
```python
class MessageManager:
```
Central management system for messages and conversations.
**Attributes:**
- `messages: Pile[RoledMessage]` - Message collection
- `logger: LogManager` - Message logger
- `system: System` - System message
- `save_on_clear: bool` - Save logs on clear
**Methods:**
#### Message Creation
##### `create_instruction`
```python
@staticmethod
def create_instruction(
*,
sender: ID.SenderRecipient = None,
recipient: ID.SenderRecipient = None,
instruction: Instruction | JsonValue = None,
context: JsonValue = None,
guidance: JsonValue = None,
plain_content: str = None,
request_fields: list[str] | dict[str, Any] = None,
request_model: type[BaseModel] | BaseModel = None,
images: list = None,
image_detail: Literal["low", "high", "auto"] = None,
tool_schemas: dict | None = None,
**kwargs,
) -> Instruction
```
Create instruction message.
> [!tip] Creating Instructions
> Use this method to create structured instruction messages with:
> - Context and guidance
> - Type-safe request models
> - Image support
> - Tool integrations
##### `create_assistant_response`
```python
@staticmethod
def create_assistant_response(
*,
sender: Any = None,
recipient: Any = None,
assistant_response: AssistantResponse | Any = None,
) -> AssistantResponse
```
Create assistant response message.
##### `create_action_request`
```python
@staticmethod
def create_action_request(
*,
sender: ID.SenderRecipient = None,
recipient: ID.SenderRecipient = None,
function: str = None,
arguments: dict[str, Any] = None,
action_request: ActionRequest | None = None,
) -> ActionRequest
```
Create action request message.
#### Message Management
##### `add_message`
```python
def add_message(
self,
*,
sender: ID.SenderRecipient = None,
recipient: ID.SenderRecipient = None,
instruction: Instruction | JsonValue = None,
# ... other parameters ...
metadata: dict = None,
) -> RoledMessage
```
Add message to the manager.
> [!warning] Message Type Restrictions
> Only one message type can be added at a time. Attempting to add multiple types (e.g., both instruction and system) will raise a ValueError.
#### Message Access
##### `last_response`
```python
@property
def last_response(self) -> AssistantResponse | None
```
Get the most recent assistant response.
##### `last_instruction`
```python
@property
def last_instruction(self) -> Instruction | None
```
Get the most recent instruction.
##### `assistant_responses`
```python
@property
def assistant_responses(self) -> Pile[AssistantResponse]
```
Get all assistant responses.
##### `action_requests`
```python
@property
def action_requests(self) -> Pile[ActionRequest]
```
Get all action requests.
##### `action_responses`
```python
@property
def action_responses(self) -> Pile[ActionResponse]
```
Get all action responses.
#### State Management
##### `clear_messages`
```python
def clear_messages(self) -> None
```
Clear all messages except system message.
##### `to_chat_msgs`
```python
def to_chat_msgs(self, progress=None) -> list[dict]
```
Convert messages to chat format.
> [!note] Chat Format
> Messages are converted to a format compatible with chat interfaces, including:
> - Role information
> - Content formatting
> - Image handling
> - Metadata preservation
## Specialized Messages
### System Message
```python
class System(RoledMessage):
```
System-level messages providing context and configuration.
**Methods:**
#### `__init__`
```python
def __init__(
self,
*,
system: Any = None,
system_datetime: bool | str = None,
**kwargs
) -> None
```
Initialize system message.
### Instruction Message
```python
class Instruction(RoledMessage):
```
User instructions and queries.
**Attributes:**
- `instruction: JsonValue` - Primary instruction content
- `context: JsonValue` - Additional context
- `guidance: JsonValue` - Optional guidance
- `request_fields: list[str] | dict` - Fields to request
- `request_model: BaseModel` - Validation model
### AssistantResponse
```python
class AssistantResponse(RoledMessage):
```
AI assistant responses.
**Attributes:**
- `assistant_response: Any` - Response content
- `model_response: dict | None` - Raw model output
- `functions: list[dict] | None` - Available functions
### ActionRequest
```python
class ActionRequest(RoledMessage):
```
Function execution requests.
**Attributes:**
- `function: str` - Function name
- `arguments: dict[str, Any]` - Function arguments
- `is_responded: bool` - Response status
### ActionResponse
```python
class ActionResponse(RoledMessage):
```
Function execution results.
**Attributes:**
- `action_request: ActionRequest` - Original request
- `output: Any` - Function output
## Type Definitions
```python
JsonValue = Union[str, int, float, bool, list, dict, None]
ID.SenderRecipient = Literal["system", "user", "assistant", "N/A"] | str
```
## Best Practices
### Message Creation
> [!tip] Creating Messages
> 1. Use appropriate message types for each purpose
> 2. Include relevant metadata
> 3. Validate content structure
> 4. Handle resources properly
> 5. Use type hints
Example:
```python
# Create instruction
instruction = manager.create_instruction(
instruction="Process data",
context={"data_type": "json"},
request_model=DataModel
)
# Create response
response = manager.create_assistant_response(
assistant_response={"result": "processed"}
)
```
### Error Handling
```python
try:
response = manager.create_action_response(
action_request=request,
action_response=result
)
except ValueError as e:
# Handle invalid request
pass
```
### Resource Management
> [!important] Resource Guidelines
> 1. Clean up unused messages
> 2. Clear message history when appropriate
> 3. Save logs before clearing
> 4. Monitor message pile size
> 5. Handle large conversations efficiently
Example:
```python
# Save and clear messages
if manager.messages.size > threshold:
manager.clear_messages() # Logs are saved if save_on_clear=True
```
## Common Issues
### Message Validation
- Invalid role assignments
- Missing required fields
- Incorrect content types
- Resource cleanup failures
### State Management
- Message ordering issues
- History management
- Branch synchronization
- Resource leaks
## See Also
- [[Communication System Guide]]