function add_message_to_session
Adds a message to a chat session with thread-safe locking, storing role, content, timestamp, and optional metadata/references, then persists the session to disk.
/tf/active/vicechatdev/docchat/app.py
243 - 261
moderate
Purpose
This function manages the addition of messages to an in-memory chat session dictionary in a thread-safe manner. It's designed for chat applications where messages need to be tracked with timestamps, metadata, and references. The function ensures data consistency through locking mechanisms and persists changes to disk immediately after updating the session.
Source Code
def add_message_to_session(session_id, role, content, metadata=None, references=None):
"""Add a message to the chat session"""
with session_lock:
if session_id in chat_sessions:
message_data = {
'role': role,
'content': content,
'timestamp': datetime.now().isoformat()
}
# Add metadata and references if provided (for assistant messages)
if metadata:
message_data['metadata'] = metadata
if references:
message_data['references'] = references
chat_sessions[session_id]['messages'].append(message_data)
chat_sessions[session_id]['updated_at'] = datetime.now()
# Persist to disk while holding lock
save_session_to_disk(session_id)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
role |
- | - | positional_or_keyword |
content |
- | - | positional_or_keyword |
metadata |
- | None | positional_or_keyword |
references |
- | None | positional_or_keyword |
Parameter Details
session_id: Unique identifier for the chat session. Expected to be a string (likely UUID) that exists as a key in the global 'chat_sessions' dictionary. If the session_id doesn't exist, the function silently does nothing.
role: The role of the message sender. Typically 'user' or 'assistant' in chat applications. String value that indicates who generated the message.
content: The actual message content/text. String value containing the message body to be stored in the session.
metadata: Optional dictionary containing additional metadata about the message. Commonly used for assistant messages to store processing information, model details, or other contextual data. Defaults to None.
references: Optional list or dictionary containing references (likely document references or citations) associated with the message. Typically used for RAG (Retrieval-Augmented Generation) systems where assistant responses reference source documents. Defaults to None.
Return Value
This function does not return any value (implicitly returns None). It performs side effects by modifying the global 'chat_sessions' dictionary and persisting data to disk via 'save_session_to_disk'.
Dependencies
datetimethreading
Required Imports
from datetime import datetime
from threading import Lock
Usage Example
from datetime import datetime
from threading import Lock
# Required global setup
session_lock = Lock()
chat_sessions = {
'session-123': {
'messages': [],
'updated_at': datetime.now(),
'created_at': datetime.now()
}
}
def save_session_to_disk(session_id):
# Mock implementation
pass
# Add a user message
add_message_to_session(
session_id='session-123',
role='user',
content='What is the weather today?'
)
# Add an assistant message with metadata and references
add_message_to_session(
session_id='session-123',
role='assistant',
content='The weather is sunny with 75°F.',
metadata={'model': 'gpt-4', 'tokens': 150},
references=[{'doc_id': 'weather-001', 'page': 3}]
)
# Check the messages
print(chat_sessions['session-123']['messages'])
Best Practices
- Ensure 'session_lock' is properly initialized as a threading.Lock() before calling this function
- Always verify that the session_id exists in chat_sessions before calling, or handle the silent failure appropriately
- The function holds a lock during disk I/O (save_session_to_disk), which may cause performance bottlenecks under high concurrency - consider async persistence or queue-based persistence for production systems
- The 'chat_sessions' dictionary should have a consistent structure with 'messages' list and 'updated_at' fields
- Consider implementing session cleanup or expiration mechanisms to prevent unbounded memory growth
- For production use, add error handling around save_session_to_disk to prevent lock holding during failures
- The function modifies global state - ensure proper initialization and cleanup in multi-threaded environments
- Timestamps are stored in ISO format - ensure consistent timezone handling across your application
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function clear_session_v1 75.7% similar
-
function get_or_create_session 73.7% similar
-
function create_chat_session 71.4% similar
-
function update_session_settings 71.0% similar
-
function save_session_to_disk 69.1% similar