# LionAGI Communication System Guide
## Overview
The Communication System is a foundational component of LionAGI that provides structured message handling, conversation management, and type-safe communication between different parts of the system.
> [!note] Core Functionality
> - Type-safe message handling
> - Role-based communication
> - Structured content management
> - Resource lifecycle tracking
> - Conversation state management
## Architecture
### Component Hierarchy
```mermaid
classDiagram
BaseMail <|-- RoledMessage
Component <|-- RoledMessage
RoledMessage <|-- SystemMessage
RoledMessage <|-- InstructionMessage
RoledMessage <|-- AssistantResponse
RoledMessage <|-- ActionRequest
class BaseMail {
+sender: ID
+recipient: ID
}
class RoledMessage {
+content: Note
+role: MessageRole
+metadata: Note
}
```
### Core Components
1. **Base Layer**
- **BaseMail**: Foundation for message handling
- **Component**: Base for component management
- **Element**: Core type with serialization
2. **Message Layer**
- **RoledMessage**: Base message with roles
- **MessageManager**: Conversation orchestration
- **MessageRole**: Role enumeration
3. **Specialized Messages**
- **SystemMessage**: System configuration
- **InstructionMessage**: User inputs
- **AssistantResponse**: AI outputs
- **ActionRequest**: Function calls
## Key Concepts
### Message Roles
> [!info] Available Roles
> - **SYSTEM**: Configuration and context
> - **USER**: Human input and queries
> - **ASSISTANT**: AI responses
> - **N/A**: Default/unspecified
### Message Flow
```mermaid
sequenceDiagram
participant User
participant Manager
participant Assistant
participant System
User->>Manager: InstructionMessage
Manager->>System: Get Context
System->>Manager: SystemMessage
Manager->>Assistant: Process
Assistant->>Manager: AssistantResponse
Manager->>User: Response
```
### Content Management
Messages use a flexible Note system for content:
```python
class RoledMessage:
content: Note = Field(
default_factory=Note,
description="Message content"
)
metadata: Note = Field(
default_factory=Note,
description="Message metadata"
)
```
> [!tip] Content Features
> - Structured storage
> - Type validation
> - Serialization support
> - Metadata tracking
> - Clone capabilities
## Usage Patterns
### 1. Basic Message Flow
```python
# Create message manager
manager = MessageManager()
# Add system context
manager.add_system_message("You are a helpful assistant.")
# Process user input
response = await manager.process_instruction(
"Tell me about Python."
)
```
### 2. Function Calling
```python
# Register function
@tool
async def process_data(data: dict) -> dict:
return {"processed": data}
# Create action request
request = ActionRequest(
function="process_data",
arguments={"data": input_data}
)
# Process request
response = await manager.process_action(request)
```
### 3. Conversation Management
```python
# Create conversation branch
branch = manager.create_branch()
# Add messages
branch.add_message(user_msg)
branch.add_message(assistant_msg)
# Get conversation history
history = branch.get_history()
```
## Best Practices
### 1. Message Design
> [!important] Key Principles
> - Keep messages focused and single-purpose
> - Include necessary context in metadata
> - Use appropriate message types
> - Validate content structure
> - Handle resources properly
### 2. Error Handling
```python
try:
response = await manager.process_message(msg)
except ValidationError:
# Handle invalid message format
pass
except ResourceError:
# Handle resource issues
pass
```
### 3. Resource Management
> [!warning] Resource Guidelines
> - Clean up resources after use
> - Track resource lifecycles
> - Handle timeouts appropriately
> - Monitor memory usage
> - Implement pooling for heavy resources
### 4. Type Safety
```python
# Use type hints
def process_message(
message: RoledMessage,
context: Optional[dict] = None
) -> AssistantResponse:
pass
# Validate content
@field_validator("content")
def validate_content(cls, v: Any) -> Note:
if not isinstance(v, (str, dict, Note)):
raise ValueError("Invalid content type")
return Note(v)
```
## Common Issues
### 1. Message Validation
- Ensure proper role assignment
- Validate content structure
- Check metadata completeness
- Verify resource references
### 2. State Management
- Track conversation state
- Handle branching properly
- Manage message history
- Clean up old messages
### 3. Performance
- Monitor message size
- Implement proper caching
- Handle large conversations
- Optimize resource usage
## Integration
### 1. With Action System
```python
class ActionBranch:
def __init__(self):
self.message_manager = MessageManager()
self.action_manager = ActionManager()
async def process(self, instruction):
# Process instruction
response = await self.message_manager.process(
instruction
)
# Handle actions
if response.has_action:
result = await self.action_manager.invoke(
response.action
)
```
### 2. With Validation System
```python
from pydantic import BaseModel
class MessageContent(BaseModel):
text: str
metadata: dict = {}
class ValidatedMessage(RoledMessage):
content: MessageContent
```
## See Also