"""
Enhanced Matrix integration tools for OllamaTools.
This module extends the basic Matrix integration with advanced features from
the modular and extended agents, including:
- Improved message response logic
- Natural language understanding
- Search integration
- Conversation history tracking and summarization
- Topic analysis
- Performance metrics
Dependencies:
- matrix-nio: For Matrix protocol support
- matrix-nio[e2e]: For end-to-end encryption support (optional)
- pyyaml: For configuration handling
- ollama: For Ollama API access
"""
import os
import sys
import yaml
import json
import asyncio
import logging
from typing import Dict, List, Optional, Union, Callable, Any, Set, Tuple
# Import from core module
from ollamatools.tools.enhanced_matrix_core import (
EnhancedMatrixClient,
_connect_enhanced_matrix
)
# Import from search module
from ollamatools.plugins.integrations.matrix.search import (
MODULAR_AGENT_AVAILABLE,
OPENSEARCH_AVAILABLE,
get_default_opensearch_config,
execute_search_for_message,
execute_search_query,
handle_search_command
)
# Import from history module
from ollamatools.plugins.integrations.matrix.history import (
load_conversation_history,
save_conversation_history,
record_conversation,
analyze_conversation_topics,
get_performance_metrics,
handle_history_command,
handle_topics_command,
handle_metrics_command
)
# Import from base matrix tools
from ollamatools.plugins.integrations.matrix.client import (
MatrixConfig,
load_matrix_config,
save_matrix_config,
create_default_matrix_config,
RoomMessageText
)
# Configure logging
logger = logging.getLogger(__name__)
# Synchronous wrapper functions for the module API
def connect_enhanced_matrix(
homeserver: str,
user_id: str,
password: str,
device_id: str = None,
ollama_host: str = "localhost:11434",
ollama_model: str = "llama3:latest",
ollama_prompt: str = None,
available_models: List[str] = None,
admin_users: List[str] = None,
opensearch_config: Dict[str, Any] = None,
ssl: bool = True,
enable_search: bool = True,
enable_conversation_tracking: bool = True,
max_context_length: int = 10,
max_conversation_history: int = 100,
respond_to_all_messages: bool = False
) -> Optional[EnhancedMatrixClient]:
"""
Connect to a Matrix homeserver with enhanced features.
Args:
homeserver: The URL of the Matrix homeserver
user_id: The Matrix user ID (e.g., @user:example.com)
password: The password for the Matrix account
device_id: A unique identifier for this device (for E2E encryption)
ollama_host: The host address for the Ollama API
ollama_model: The Ollama model to use for generating responses
ollama_prompt: An optional system prompt for the Ollama model
available_models: List of available Ollama models
admin_users: List of Matrix user IDs that can change models for all users
opensearch_config: Configuration for OpenSearchNG
ssl: Whether to use SSL for the Matrix connection
enable_search: Whether to enable search functionality
enable_conversation_tracking: Whether to enable conversation tracking
max_context_length: Maximum number of messages to keep in context
max_conversation_history: Maximum number of conversations to keep in history
respond_to_all_messages: Whether to respond to all messages (not just mentions)
Returns:
Optional[EnhancedMatrixClient]: A connected Enhanced Matrix client, or None if connection failed
"""
return asyncio.run(_connect_enhanced_matrix(
homeserver=homeserver,
user_id=user_id,
password=password,
device_id=device_id,
ollama_host=ollama_host,
ollama_model=ollama_model,
ollama_prompt=ollama_prompt,
available_models=available_models,
admin_users=admin_users,
opensearch_config=opensearch_config,
ssl=ssl,
enable_search=enable_search,
enable_conversation_tracking=enable_conversation_tracking,
max_context_length=max_context_length,
max_conversation_history=max_conversation_history,
respond_to_all_messages=respond_to_all_messages
))
def join_enhanced_matrix_room(client: EnhancedMatrixClient, room_id: str) -> bool:
"""
Join a Matrix room with an Enhanced Matrix client.
Args:
client: A connected Enhanced Matrix client
room_id: The ID of the room to join (e.g., #room:example.com)
Returns:
bool: True if joining was successful, False otherwise
"""
return asyncio.run(client.join_room(room_id))
def send_enhanced_matrix_message(client: EnhancedMatrixClient, room_id: str, message: str) -> bool:
"""
Send a message to a Matrix room with an Enhanced Matrix client.
Args:
client: A connected Enhanced Matrix client
room_id: The ID of the room to send the message to
message: The message to send
Returns:
bool: True if sending was successful, False otherwise
"""
return asyncio.run(client.send_message(room_id, message))
def listen_for_enhanced_matrix_messages(client: EnhancedMatrixClient) -> None:
"""
Start listening for messages in joined rooms with an Enhanced Matrix client.
This function will block until the client is stopped.
Args:
client: A connected Enhanced Matrix client
"""
asyncio.run(client.listen())
def create_enhanced_matrix_config() -> Dict:
"""
Create a default Enhanced Matrix configuration.
Returns:
Dict: The default configuration
"""
config = create_default_matrix_config()
# Add enhanced configuration
config["ENHANCED"] = {
"ENABLE_SEARCH": True,
"ENABLE_CONVERSATION_TRACKING": True,
"MAX_CONTEXT_LENGTH": 10,
"MAX_CONVERSATION_HISTORY": 100,
"RESPOND_TO_ALL_MESSAGES": False,
"OPENSEARCH": {
"BASE_URL": "http://localhost:8081",
"ENGINES": [
"google",
"bing",
"duckduckgo",
"brave"
],
"NUM_RESULTS": 5
}
}
return config
def disconnect_enhanced_matrix(client: EnhancedMatrixClient) -> None:
"""
Disconnect from the Matrix homeserver and clean up resources.
Args:
client: A connected Enhanced Matrix client
"""
asyncio.run(client.disconnect())
def process_with_enhanced_ollama(
client: EnhancedMatrixClient,
message: str,
sender: str = None,
room_id: str = None
) -> str:
"""
Process a message with Ollama using an Enhanced Matrix client.
Args:
client: A connected Enhanced Matrix client
message: The message to process
sender: The Matrix user ID of the sender
room_id: The ID of the room where the message was sent
Returns:
str: The response from Ollama
"""
return asyncio.run(client.process_with_ollama(message, sender, room_id))