addMessage method
Implementation
Future<void> addMessage(
String role,
String content, {
List<Map<String, dynamic>>? toolCalls,
String? toolCallId,
}) async {
if (role.isEmpty && (toolCalls == null || toolCalls.isEmpty)) {
logger.warning(
'Attempted to add invalid message to memory',
tag: 'MEMORY',
extra: {'role': role, 'content_length': content.length},
);
return;
}
final message = {
'role': role,
'content': content.isEmpty ? null : content,
if (toolCalls != null) 'tool_calls': toolCalls,
if (toolCallId != null) 'tool_call_id': toolCallId,
};
// Save to persistence if available
if (persistence != null) {
await persistence!.saveMessage(
role,
content,
toolCalls: toolCalls,
toolCallId: toolCallId,
);
}
_shortMemory.add(message);
logger.debug(
'Added message to short-term memory',
tag: 'MEMORY',
extra: {
'role': role,
'content_length': content.length,
'has_tools': toolCalls != null,
'short_count': _shortMemory.length,
},
);
if (_shortMemory.length > shortLimit) {
logger.info(
'Short-term memory limit reached, summarizing to long-term memory',
tag: 'MEMORY',
extra: {'short_count': _shortMemory.length},
);
final messagesToSummarize = _shortMemory.toList();
final summary = await _summarizeMessages(messagesToSummarize);
final summaryMsg = {
'role': 'system',
'content': 'Historical context: $summary',
};
// Save summary to persistence
if (persistence != null) {
await persistence!.saveMessage(
'system',
'Historical context: $summary',
isSummary: true,
);
// Prune old non-summarized messages from persistence to save space
await persistence!.deleteOldMessages(shortLimit);
}
_longMemory.add(summaryMsg);
_shortMemory.clear();
logger.info(
'Added summary to long-term memory',
tag: 'MEMORY',
extra: {
'long_count': _longMemory.length,
'summary_length': summary.length,
},
);
// Prune long memory if needed
if (_longMemory.length > longLimit) {
final removed = _longMemory.removeAt(0);
logger.info(
'Pruned oldest long-term memory entry',
tag: 'MEMORY',
extra: {
'removed_length': removed['content'].length,
'long_count': _longMemory.length,
},
);
}
}
}